Path: blob/master/test/jdk/java/io/File/GetXSpace.java
66644 views
/*1* Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/**24* @test25* @bug 4057701 6286712 6364377 818191926* @requires (os.family == "linux" | os.family == "mac" |27* os.family == "windows")28* @summary Basic functionality of File.get-X-Space methods.29* @library .. /test/lib30* @build jdk.test.lib.Platform31* @run main/othervm -Djava.security.manager=allow GetXSpace32*/3334import java.io.BufferedReader;35import java.io.File;36import java.io.FilePermission;37import java.io.InputStreamReader;38import java.io.IOException;39import java.nio.file.Files;40import java.nio.file.FileStore;41import java.nio.file.NoSuchFileException;42import java.nio.file.Path;43import java.security.Permission;44import java.util.ArrayList;45import java.util.regex.Matcher;46import java.util.regex.Pattern;47import jdk.test.lib.Platform;48import jdk.test.lib.Platform;4950import static java.lang.System.err;51import static java.lang.System.out;5253@SuppressWarnings("removal")54public class GetXSpace {5556private static SecurityManager [] sma = { null, new Allow(), new DenyFSA(),57new DenyRead() };5859// FileSystem Total Used Available Use% MountedOn60private static final Pattern DF_PATTERN = Pattern.compile("([^\\s]+)\\s+(\\d+)\\s+\\d+\\s+(\\d+)\\s+\\d+%\\s+([^\\s].*)\n");6162private static int fail = 0;63private static int pass = 0;64private static Throwable first;6566static void reset() {67fail = 0;68pass = 0;69first = null;70}7172static void pass() {73pass++;74}7576static void fail(String p) {77setFirst(p);78System.err.format("FAILED: %s%n", p);79fail++;80}8182static void fail(String p, long exp, String cmp, long got) {83String s = String.format("'%s': %d %s %d", p, exp, cmp, got);84setFirst(s);85System.err.format("FAILED: %s%n", s);86fail++;87}8889private static void fail(String p, Class ex) {90String s = String.format("'%s': expected %s - FAILED%n", p, ex.getName());91setFirst(s);92System.err.format("FAILED: %s%n", s);93fail++;94}9596private static void setFirst(String s) {97if (first == null) {98first = new RuntimeException(s);99}100}101102private static class Space {103private static final long KSIZE = 1024;104private final String name;105private final long total;106private final long free;107108Space(String total, String free, String name) {109try {110this.total = Long.valueOf(total) * KSIZE;111this.free = Long.valueOf(free) * KSIZE;112} catch (NumberFormatException x) {113throw new RuntimeException("the regex should have caught this", x);114}115this.name = name;116}117118String name() { return name; }119long total() { return total; }120long free() { return free; }121boolean woomFree(long freeSpace) {122return ((freeSpace >= (free / 10)) && (freeSpace <= (free * 10)));123}124public String toString() {125return String.format("%s (%d/%d)", name, free, total);126}127}128129private static ArrayList<Space> space(String f) throws IOException {130ArrayList<Space> al = new ArrayList<>();131132String cmd = "df -k -P" + (f == null ? "" : " " + f);133StringBuilder sb = new StringBuilder();134Process p = Runtime.getRuntime().exec(cmd);135try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()))) {136String s;137int i = 0;138while ((s = in.readLine()) != null) {139// skip header140if (i++ == 0) continue;141sb.append(s).append("\n");142}143}144out.println(sb);145146Matcher m = DF_PATTERN.matcher(sb);147int j = 0;148while (j < sb.length()) {149if (m.find(j)) {150// swap can change while this test is running151if (!m.group(1).equals("swap")) {152String name = f;153if (name == null) {154// cygwin's df lists windows path as FileSystem (1st group)155name = Platform.isWindows() ? m.group(1) : m.group(4);156}157al.add(new Space(m.group(2), m.group(3), name));;158}159j = m.end() + 1;160} else {161throw new RuntimeException("unrecognized df output format: "162+ "charAt(" + j + ") = '"163+ sb.charAt(j) + "'");164}165}166167if (al.size() == 0) {168// df did not produce output169String name = (f == null ? "" : f);170al.add(new Space("0", "0", name));171}172return al;173}174175private static void tryCatch(Space s) {176out.format("%s:%n", s.name());177File f = new File(s.name());178SecurityManager sm = System.getSecurityManager();179if (sm instanceof Deny) {180String fmt = " %14s: \"%s\" thrown as expected%n";181try {182f.getTotalSpace();183fail(s.name(), SecurityException.class);184} catch (SecurityException x) {185out.format(fmt, "getTotalSpace", x);186pass();187}188try {189f.getFreeSpace();190fail(s.name(), SecurityException.class);191} catch (SecurityException x) {192out.format(fmt, "getFreeSpace", x);193pass();194}195try {196f.getUsableSpace();197fail(s.name(), SecurityException.class);198} catch (SecurityException x) {199out.format(fmt, "getUsableSpace", x);200pass();201}202}203}204205private static void compare(Space s) {206File f = new File(s.name());207long ts = f.getTotalSpace();208long fs = f.getFreeSpace();209long us = f.getUsableSpace();210211out.format("%s:%n", s.name());212String fmt = " %-4s total= %12d free = %12d usable = %12d%n";213out.format(fmt, "df", s.total(), 0, s.free());214out.format(fmt, "getX", ts, fs, us);215216// If the file system can dynamically change size, this check will fail.217// This can happen on macOS for the /dev files system.218if (ts != s.total() && (!Platform.isOSX() || !s.name().equals("/dev"))) {219long blockSize = 1;220long numBlocks = 0;221try {222FileStore fileStore = Files.getFileStore(f.toPath());223blockSize = fileStore.getBlockSize();224numBlocks = fileStore.getTotalSpace()/blockSize;225} catch (NoSuchFileException nsfe) {226// On Linux, ignore the NSFE if the path is one of the227// /run/user/$UID mounts created by pam_systemd(8) as it228// might be deleted during the test229if (!Platform.isLinux() || s.name().indexOf("/run/user") == -1)230throw new RuntimeException(nsfe);231} catch (IOException e) {232throw new RuntimeException(e);233}234235// On macOS, the number of 1024 byte blocks might be incorrectly236// calculated by 'df' using integer division by 2 of the number of237// 512 byte blocks, resulting in a size smaller than the actual238// value when the number of blocks is odd.239if (!Platform.isOSX() || blockSize != 512 || numBlocks % 2 == 0240|| ts - s.total() != 512) {241fail(s.name(), s.total(), "!=", ts);242}243} else {244pass();245}246247// unix df returns statvfs.f_bavail248long tsp = (!Platform.isWindows() ? us : fs);249if (!s.woomFree(tsp)) {250fail(s.name(), s.free(), "??", tsp);251} else {252pass();253}254255if (fs > s.total()) {256fail(s.name(), s.total(), ">", fs);257} else {258pass();259}260261if (us > s.total()) {262fail(s.name(), s.total(), ">", us);263} else {264pass();265}266}267268private static String FILE_PREFIX = "/getSpace.";269private static void compareZeroNonExist() {270File f;271while (true) {272f = new File(FILE_PREFIX + Math.random());273if (f.exists()) {274continue;275}276break;277}278279long [] s = { f.getTotalSpace(), f.getFreeSpace(), f.getUsableSpace() };280281for (int i = 0; i < s.length; i++) {282if (s[i] != 0L) {283fail(f.getName(), s[i], "!=", 0L);284} else {285pass();286}287}288}289290private static void compareZeroExist() {291try {292File f = File.createTempFile("tmp", null, new File("."));293294long [] s = { f.getTotalSpace(), f.getFreeSpace(), f.getUsableSpace() };295296for (int i = 0; i < s.length; i++) {297if (s[i] == 0L) {298fail(f.getName(), s[i], "==", 0L);299} else {300pass();301}302}303} catch (IOException x) {304x.printStackTrace();305fail("Couldn't create temp file for test");306}307}308309private static class Allow extends SecurityManager {310public void checkRead(String file) {}311public void checkPermission(Permission p) {}312public void checkPermission(Permission p, Object context) {}313}314315private static class Deny extends SecurityManager {316public void checkPermission(Permission p) {317if (p.implies(new RuntimePermission("setSecurityManager"))318|| p.implies(new RuntimePermission("getProtectionDomain")))319return;320super.checkPermission(p);321}322323public void checkPermission(Permission p, Object context) {324if (p.implies(new RuntimePermission("setSecurityManager"))325|| p.implies(new RuntimePermission("getProtectionDomain")))326return;327super.checkPermission(p, context);328}329}330331private static class DenyFSA extends Deny {332private String err = "sorry - getFileSystemAttributes";333334public void checkPermission(Permission p) {335if (p.implies(new RuntimePermission("getFileSystemAttributes")))336throw new SecurityException(err);337super.checkPermission(p);338}339340public void checkPermission(Permission p, Object context) {341if (p.implies(new RuntimePermission("getFileSystemAttributes")))342throw new SecurityException(err);343super.checkPermission(p, context);344}345}346347private static class DenyRead extends Deny {348private String err = "sorry - checkRead()";349350public void checkRead(String file) {351throw new SecurityException(err);352}353}354355private static int testFile(Path dir) {356String dirName = dir.toString();357out.format("--- Testing %s%n", dirName);358ArrayList<Space> l;359try {360l = space(dirName);361} catch (IOException x) {362throw new RuntimeException(dirName + " can't get file system information", x);363}364compare(l.get(0));365366if (fail != 0) {367err.format("%d tests: %d failure(s); first: %s%n",368fail + pass, fail, first);369} else {370out.format("all %d tests passed%n", fail + pass);371}372373return fail != 0 ? 1 : 0;374}375376private static int testDF() {377out.println("--- Testing df");378// Find all of the partitions on the machine and verify that the size379// returned by "df" is equivalent to File.getXSpace() values.380ArrayList<Space> l;381try {382l = space(null);383} catch (IOException x) {384throw new RuntimeException("can't get file system information", x);385}386if (l.size() == 0)387throw new RuntimeException("no partitions?");388389for (int i = 0; i < sma.length; i++) {390System.setSecurityManager(sma[i]);391SecurityManager sm = System.getSecurityManager();392if (sma[i] != null && sm == null)393throw new RuntimeException("Test configuration error "394+ " - can't set security manager");395396out.format("%nSecurityManager = %s%n" ,397(sm == null ? "null" : sm.getClass().getName()));398for (var s : l) {399if (sm instanceof Deny) {400tryCatch(s);401} else {402compare(s);403compareZeroNonExist();404compareZeroExist();405}406}407}408409System.setSecurityManager(null);410411if (fail != 0) {412err.format("%d tests: %d failure(s); first: %s%n",413fail + pass, fail, first);414} else {415out.format("all %d tests passed%n", fail + pass);416}417418return fail != 0 ? 1 : 0;419}420421private static void perms(File file, boolean allow) throws IOException {422file.setExecutable(allow, false);423file.setReadable(allow, false);424file.setWritable(allow, false);425}426427private static void deny(Path path) throws IOException {428perms(path.toFile(), false);429}430431private static void allow(Path path) throws IOException {432perms(path.toFile(), true);433}434435public static void main(String[] args) throws Exception {436int failedTests = testDF();437reset();438439Path tmpDir = Files.createTempDirectory(null);440Path tmpSubdir = Files.createTempDirectory(tmpDir, null);441Path tmpFile = Files.createTempFile(tmpSubdir, "foo", null);442443deny(tmpSubdir);444failedTests += testFile(tmpFile);445446allow(tmpSubdir);447Files.delete(tmpFile);448Files.delete(tmpSubdir);449Files.delete(tmpDir);450451if (failedTests > 0) {452throw new RuntimeException(failedTests + " test(s) failed");453}454}455}456457458