Path: blob/master/test/hotspot/jtreg/runtime/8176717/TestInheritFD.java
40942 views
/*1* Copyright (c) 2018, 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*/2223import static java.lang.Long.parseLong;24import static java.lang.System.getProperty;25import static java.nio.file.Files.readAllBytes;26import static java.util.Arrays.stream;27import static java.util.stream.Collectors.joining;28import static java.util.stream.Collectors.toList;29import static jdk.test.lib.process.ProcessTools.createJavaProcessBuilder;30import static jdk.test.lib.Platform.isWindows;31import jdk.test.lib.Utils;32import jdk.test.lib.Platform;33import jtreg.SkippedException;3435import java.io.BufferedReader;36import java.io.File;37import java.io.FileNotFoundException;38import java.io.FileOutputStream;39import java.io.IOException;40import java.io.InputStreamReader;41import java.util.Collection;42import java.util.Optional;43import java.util.stream.Stream;4445/*46* @test TestInheritFD47* @bug 8176717 8176809 822250048* @summary a new process should not inherit open file descriptors49* @comment On Aix lsof requires root privileges.50* @requires os.family != "aix"51* @library /test/lib52* @modules java.base/jdk.internal.misc53* java.management54* @run driver TestInheritFD55*/5657/**58* Test that HotSpot does not leak logging file descriptors.59*60* This test is performed in three steps. The first VM starts a second VM with61* gc logging enabled. The second VM starts a third VM and redirects the third62* VMs output to the first VM, it then exits and hopefully closes its log file.63*64* The third VM waits for the second to exit and close its log file. After that,65* the third VM tries to rename the log file of the second VM. If it succeeds in66* doing so it means that the third VM did not inherit the open log file67* (windows can not rename opened files easily)68*69* The third VM communicates the success to rename the file by printing "CLOSED70* FD". The first VM checks that the string was printed by the third VM.71*72* On unix like systems "lsof" is used.73*/7475public class TestInheritFD {7677public static final String LEAKS_FD = "VM RESULT => LEAKS FD";78public static final String RETAINS_FD = "VM RESULT => RETAINS FD";79public static final String EXIT = "VM RESULT => VM EXIT";80public static final String LOG_SUFFIX = ".strangelogsuffixthatcanbecheckedfor";8182// first VM83public static void main(String[] args) throws Exception {84String logPath = Utils.createTempFile("logging", LOG_SUFFIX).toFile().getName();85File commFile = Utils.createTempFile("communication", ".txt").toFile();8687if (!isWindows() && !lsofCommand().isPresent()) {88throw new SkippedException("Could not find lsof like command");89}9091ProcessBuilder pb = createJavaProcessBuilder(92"-Xlog:gc:\"" + logPath + "\"",93"-Dtest.jdk=" + getProperty("test.jdk"),94VMStartedWithLogging.class.getName(),95logPath);9697pb.redirectOutput(commFile); // use temp file to communicate between processes98pb.start();99100String out = "";101do {102out = new String(readAllBytes(commFile.toPath()));103Thread.sleep(100);104System.out.println("SLEEP 100 millis");105} while (!out.contains(EXIT));106107System.out.println(out);108if (out.contains(RETAINS_FD)) {109System.out.println("Log file was not inherited by third VM");110} else {111throw new RuntimeException("could not match: " + RETAINS_FD);112}113}114115static class VMStartedWithLogging {116// second VM117public static void main(String[] args) throws IOException, InterruptedException {118ProcessBuilder pb = createJavaProcessBuilder(119"-Dtest.jdk=" + getProperty("test.jdk"),120VMShouldNotInheritFileDescriptors.class.getName(),121args[0],122"" + ProcessHandle.current().pid());123pb.inheritIO(); // in future, redirect information from third VM to first VM124pb.start();125126if (!isWindows()) {127System.out.println("(Second VM) Open file descriptors:\n" + outputContainingFilenames().stream().collect(joining("\n")));128}129}130}131132static class VMShouldNotInheritFileDescriptors {133// third VM134public static void main(String[] args) throws InterruptedException {135try {136File logFile = new File(args[0]);137long parentPid = parseLong(args[1]);138fakeLeakyJVM(false); // for debugging of test case139140if (isWindows()) {141windows(logFile, parentPid);142} else {143Collection<String> output = outputContainingFilenames();144System.out.println("(Third VM) Open file descriptors:\n" + output.stream().collect(joining("\n")));145System.out.println(findOpenLogFile(output) ? LEAKS_FD : RETAINS_FD);146}147} catch (Exception e) {148System.out.println(e.toString());149} finally {150System.out.println(EXIT);151}152}153}154155// for debugging of test case156@SuppressWarnings("resource")157static void fakeLeakyJVM(boolean fake) {158if (fake) {159try {160new FileOutputStream("fakeLeakyJVM" + LOG_SUFFIX, false);161} catch (FileNotFoundException e) {162}163}164}165166static Stream<String> run(String... args){167try {168return new BufferedReader(new InputStreamReader(new ProcessBuilder(args).start().getInputStream())).lines();169} catch (IOException e) {170throw new RuntimeException(e);171}172}173174static Optional<String[]> lsofCommandCache = stream(new String[][]{175{"/usr/bin/lsof", "-p"},176{"/usr/sbin/lsof", "-p"},177{"/bin/lsof", "-p"},178{"/sbin/lsof", "-p"},179{"/usr/local/bin/lsof", "-p"}})180.filter(args -> new File(args[0]).exists())181.findFirst();182183static Optional<String[]> lsofCommand() {184return lsofCommandCache;185}186187static Collection<String> outputContainingFilenames() {188long pid = ProcessHandle.current().pid();189190String[] command = lsofCommand().orElseThrow(() -> new RuntimeException("lsof like command not found"));191System.out.println("using command: " + command[0] + " " + command[1]);192return run(command[0], command[1], "" + pid).collect(toList());193}194195static boolean findOpenLogFile(Collection<String> fileNames) {196String pid = Long.toString(ProcessHandle.current().pid());197String[] command = lsofCommand().orElseThrow(() ->198new RuntimeException("lsof like command not found"));199String lsof = command[0];200boolean isBusybox = Platform.isBusybox(lsof);201return fileNames.stream()202// lsof from busybox does not support "-p" option203.filter(fileName -> !isBusybox || fileName.contains(pid))204.filter(fileName -> fileName.contains(LOG_SUFFIX))205.findAny()206.isPresent();207}208209static void windows(File f, long parentPid) throws InterruptedException {210System.out.println("waiting for pid: " + parentPid);211ProcessHandle.of(parentPid).ifPresent(handle -> handle.onExit().join());212System.out.println("trying to rename file to the same name: " + f);213System.out.println(f.renameTo(f) ? RETAINS_FD : LEAKS_FD); // this parts communicates a closed file descriptor by printing "VM RESULT => RETAINS FD"214}215}216217218219