Path: blob/master/test/jdk/java/io/File/GetXSpace.java
41149 views
/*1* Copyright (c) 2005, 2020, 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* @run main/othervm -Djava.security.manager=allow GetXSpace30*/3132import java.io.BufferedReader;33import java.io.File;34import java.io.FilePermission;35import java.io.InputStreamReader;36import java.io.IOException;37import java.nio.file.Files;38import java.nio.file.FileStore;39import java.nio.file.Path;40import java.security.Permission;41import java.util.ArrayList;42import java.util.regex.Matcher;43import java.util.regex.Pattern;4445import static java.lang.System.err;46import static java.lang.System.out;4748public class GetXSpace {4950private static SecurityManager [] sma = { null, new Allow(), new DenyFSA(),51new DenyRead() };5253private static final String OS_NAME = System.getProperty("os.name");54private static final boolean IS_MAC = OS_NAME.startsWith("Mac");55private static final boolean IS_WIN = OS_NAME.startsWith("Windows");5657// FileSystem Total Used Available Use% MountedOn58private static final Pattern DF_PATTERN = Pattern.compile("([^\\s]+)\\s+(\\d+)\\s+\\d+\\s+(\\d+)\\s+\\d+%\\s+([^\\s].*)\n");5960private static int fail = 0;61private static int pass = 0;62private static Throwable first;6364static void reset() {65fail = 0;66pass = 0;67first = null;68}6970static void pass() {71pass++;72}7374static void fail(String p) {75setFirst(p);76System.err.format("FAILED: %s%n", p);77fail++;78}7980static void fail(String p, long exp, String cmp, long got) {81String s = String.format("'%s': %d %s %d", p, exp, cmp, got);82setFirst(s);83System.err.format("FAILED: %s%n", s);84fail++;85}8687private static void fail(String p, Class ex) {88String s = String.format("'%s': expected %s - FAILED%n", p, ex.getName());89setFirst(s);90System.err.format("FAILED: %s%n", s);91fail++;92}9394private static void setFirst(String s) {95if (first == null) {96first = new RuntimeException(s);97}98}99100private static class Space {101private static final long KSIZE = 1024;102private final String name;103private final long total;104private final long free;105106Space(String total, String free, String name) {107try {108this.total = Long.valueOf(total) * KSIZE;109this.free = Long.valueOf(free) * KSIZE;110} catch (NumberFormatException x) {111throw new RuntimeException("the regex should have caught this", x);112}113this.name = name;114}115116String name() { return name; }117long total() { return total; }118long free() { return free; }119boolean woomFree(long freeSpace) {120return ((freeSpace >= (free / 10)) && (freeSpace <= (free * 10)));121}122public String toString() {123return String.format("%s (%d/%d)", name, free, total);124}125}126127private static ArrayList<Space> space(String f) throws IOException {128ArrayList<Space> al = new ArrayList<>();129130String cmd = "df -k -P" + (f == null ? "" : " " + f);131StringBuilder sb = new StringBuilder();132Process p = Runtime.getRuntime().exec(cmd);133try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()))) {134String s;135int i = 0;136while ((s = in.readLine()) != null) {137// skip header138if (i++ == 0) continue;139sb.append(s).append("\n");140}141}142out.println(sb);143144Matcher m = DF_PATTERN.matcher(sb);145int j = 0;146while (j < sb.length()) {147if (m.find(j)) {148// swap can change while this test is running149if (!m.group(1).equals("swap")) {150String name = f;151if (name == null) {152// cygwin's df lists windows path as FileSystem (1st group)153name = IS_WIN ? m.group(1) : m.group(4);154}155al.add(new Space(m.group(2), m.group(3), name));;156}157j = m.end() + 1;158} else {159throw new RuntimeException("unrecognized df output format: "160+ "charAt(" + j + ") = '"161+ sb.charAt(j) + "'");162}163}164165if (al.size() == 0) {166// df did not produce output167String name = (f == null ? "" : f);168al.add(new Space("0", "0", name));169}170return al;171}172173private static void tryCatch(Space s) {174out.format("%s:%n", s.name());175File f = new File(s.name());176SecurityManager sm = System.getSecurityManager();177if (sm instanceof Deny) {178String fmt = " %14s: \"%s\" thrown as expected%n";179try {180f.getTotalSpace();181fail(s.name(), SecurityException.class);182} catch (SecurityException x) {183out.format(fmt, "getTotalSpace", x);184pass();185}186try {187f.getFreeSpace();188fail(s.name(), SecurityException.class);189} catch (SecurityException x) {190out.format(fmt, "getFreeSpace", x);191pass();192}193try {194f.getUsableSpace();195fail(s.name(), SecurityException.class);196} catch (SecurityException x) {197out.format(fmt, "getUsableSpace", x);198pass();199}200}201}202203private static void compare(Space s) {204File f = new File(s.name());205long ts = f.getTotalSpace();206long fs = f.getFreeSpace();207long us = f.getUsableSpace();208209out.format("%s:%n", s.name());210String fmt = " %-4s total= %12d free = %12d usable = %12d%n";211out.format(fmt, "df", s.total(), 0, s.free());212out.format(fmt, "getX", ts, fs, us);213214// if the file system can dynamically change size, this check will fail215if (ts != s.total()) {216long blockSize = 1;217long numBlocks = 0;218try {219FileStore fileStore = Files.getFileStore(f.toPath());220blockSize = fileStore.getBlockSize();221numBlocks = fileStore.getTotalSpace()/blockSize;222} catch (IOException e) {223throw new RuntimeException(e);224}225226227// On macOS, the number of 1024 byte blocks might be incorrectly228// calculated by 'df' using integer division by 2 of the number of229// 512 byte blocks, resulting in a size smaller than the actual230// value when the number of blocks is odd.231if (!IS_MAC || blockSize != 512 || numBlocks % 2 == 0232|| ts - s.total() != 512) {233fail(s.name(), s.total(), "!=", ts);234}235} else {236pass();237}238239// unix df returns statvfs.f_bavail240long tsp = (!IS_WIN ? us : fs);241if (!s.woomFree(tsp)) {242fail(s.name(), s.free(), "??", tsp);243} else {244pass();245}246247if (fs > s.total()) {248fail(s.name(), s.total(), ">", fs);249} else {250pass();251}252253if (us > s.total()) {254fail(s.name(), s.total(), ">", us);255} else {256pass();257}258}259260private static String FILE_PREFIX = "/getSpace.";261private static void compareZeroNonExist() {262File f;263while (true) {264f = new File(FILE_PREFIX + Math.random());265if (f.exists()) {266continue;267}268break;269}270271long [] s = { f.getTotalSpace(), f.getFreeSpace(), f.getUsableSpace() };272273for (int i = 0; i < s.length; i++) {274if (s[i] != 0L) {275fail(f.getName(), s[i], "!=", 0L);276} else {277pass();278}279}280}281282private static void compareZeroExist() {283try {284File f = File.createTempFile("tmp", null, new File("."));285286long [] s = { f.getTotalSpace(), f.getFreeSpace(), f.getUsableSpace() };287288for (int i = 0; i < s.length; i++) {289if (s[i] == 0L) {290fail(f.getName(), s[i], "==", 0L);291} else {292pass();293}294}295} catch (IOException x) {296x.printStackTrace();297fail("Couldn't create temp file for test");298}299}300301private static class Allow extends SecurityManager {302public void checkRead(String file) {}303public void checkPermission(Permission p) {}304public void checkPermission(Permission p, Object context) {}305}306307private static class Deny extends SecurityManager {308public void checkPermission(Permission p) {309if (p.implies(new RuntimePermission("setSecurityManager"))310|| p.implies(new RuntimePermission("getProtectionDomain")))311return;312super.checkPermission(p);313}314315public void checkPermission(Permission p, Object context) {316if (p.implies(new RuntimePermission("setSecurityManager"))317|| p.implies(new RuntimePermission("getProtectionDomain")))318return;319super.checkPermission(p, context);320}321}322323private static class DenyFSA extends Deny {324private String err = "sorry - getFileSystemAttributes";325326public void checkPermission(Permission p) {327if (p.implies(new RuntimePermission("getFileSystemAttributes")))328throw new SecurityException(err);329super.checkPermission(p);330}331332public void checkPermission(Permission p, Object context) {333if (p.implies(new RuntimePermission("getFileSystemAttributes")))334throw new SecurityException(err);335super.checkPermission(p, context);336}337}338339private static class DenyRead extends Deny {340private String err = "sorry - checkRead()";341342public void checkRead(String file) {343throw new SecurityException(err);344}345}346347private static int testFile(Path dir) {348String dirName = dir.toString();349out.format("--- Testing %s%n", dirName);350ArrayList<Space> l;351try {352l = space(dirName);353} catch (IOException x) {354throw new RuntimeException(dirName + " can't get file system information", x);355}356compare(l.get(0));357358if (fail != 0) {359err.format("%d tests: %d failure(s); first: %s%n",360fail + pass, fail, first);361} else {362out.format("all %d tests passed%n", fail + pass);363}364365return fail != 0 ? 1 : 0;366}367368private static int testDF() {369out.println("--- Testing df");370// Find all of the partitions on the machine and verify that the size371// returned by "df" is equivalent to File.getXSpace() values.372ArrayList<Space> l;373try {374l = space(null);375} catch (IOException x) {376throw new RuntimeException("can't get file system information", x);377}378if (l.size() == 0)379throw new RuntimeException("no partitions?");380381for (int i = 0; i < sma.length; i++) {382System.setSecurityManager(sma[i]);383SecurityManager sm = System.getSecurityManager();384if (sma[i] != null && sm == null)385throw new RuntimeException("Test configuration error "386+ " - can't set security manager");387388out.format("%nSecurityManager = %s%n" ,389(sm == null ? "null" : sm.getClass().getName()));390for (var s : l) {391if (sm instanceof Deny) {392tryCatch(s);393} else {394compare(s);395compareZeroNonExist();396compareZeroExist();397}398}399}400401System.setSecurityManager(null);402403if (fail != 0) {404err.format("%d tests: %d failure(s); first: %s%n",405fail + pass, fail, first);406} else {407out.format("all %d tests passed%n", fail + pass);408}409410return fail != 0 ? 1 : 0;411}412413private static void perms(File file, boolean allow) throws IOException {414file.setExecutable(allow, false);415file.setReadable(allow, false);416file.setWritable(allow, false);417}418419private static void deny(Path path) throws IOException {420perms(path.toFile(), false);421}422423private static void allow(Path path) throws IOException {424perms(path.toFile(), true);425}426427public static void main(String[] args) throws Exception {428int failedTests = testDF();429reset();430431Path tmpDir = Files.createTempDirectory(null);432Path tmpSubdir = Files.createTempDirectory(tmpDir, null);433Path tmpFile = Files.createTempFile(tmpSubdir, "foo", null);434435deny(tmpSubdir);436failedTests += testFile(tmpFile);437438allow(tmpSubdir);439Files.delete(tmpFile);440Files.delete(tmpSubdir);441Files.delete(tmpDir);442443if (failedTests > 0) {444throw new RuntimeException(failedTests + " test(s) failed");445}446}447}448449450