Path: blob/master/test/hotspot/jtreg/runtime/8176717/TestInheritFD.java
64478 views
/*1* Copyright (c) 2018, 2022, 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";81public static final String USER_DIR = System.getProperty("user.dir");8283// first VM84public static void main(String[] args) throws Exception {85String logPath = Utils.createTempFile("logging", LOG_SUFFIX).toFile().getName();86File commFile = Utils.createTempFile("communication", ".txt").toFile();8788if (!isWindows() && !lsofCommand().isPresent()) {89throw new SkippedException("Could not find lsof like command");90}9192ProcessBuilder pb = createJavaProcessBuilder(93"-Xlog:gc:\"" + logPath + "\"",94"-Dtest.jdk=" + getProperty("test.jdk"),95VMStartedWithLogging.class.getName(),96logPath);9798pb.redirectOutput(commFile); // use temp file to communicate between processes99pb.start();100101String out = "";102do {103out = new String(readAllBytes(commFile.toPath()));104Thread.sleep(100);105System.out.println("SLEEP 100 millis");106} while (!out.contains(EXIT));107108System.out.println(out);109if (out.contains(RETAINS_FD)) {110System.out.println("Log file was not inherited by third VM");111} else {112throw new RuntimeException("could not match: " + RETAINS_FD);113}114}115116static class VMStartedWithLogging {117// second VM118public static void main(String[] args) throws IOException, InterruptedException {119ProcessBuilder pb = createJavaProcessBuilder(120"-Dtest.jdk=" + getProperty("test.jdk"),121VMShouldNotInheritFileDescriptors.class.getName(),122args[0],123"" + ProcessHandle.current().pid());124pb.inheritIO(); // in future, redirect information from third VM to first VM125pb.start();126127if (!isWindows()) {128System.out.println("(Second VM) Open file descriptors:\n" + outputContainingFilenames().stream().collect(joining("\n")));129}130}131}132133static class VMShouldNotInheritFileDescriptors {134// third VM135public static void main(String[] args) throws InterruptedException {136try {137File logFile = new File(args[0]);138long parentPid = parseLong(args[1]);139fakeLeakyJVM(false); // for debugging of test case140141if (isWindows()) {142windows(logFile, parentPid);143} else {144Collection<String> output = outputContainingFilenames();145System.out.println("(Third VM) Open file descriptors:\n" + output.stream().collect(joining("\n")));146System.out.println(findOpenLogFile(output) ? LEAKS_FD : RETAINS_FD);147}148} catch (Exception e) {149System.out.println(e.toString());150} finally {151System.out.println(EXIT);152}153}154}155156// for debugging of test case157@SuppressWarnings("resource")158static void fakeLeakyJVM(boolean fake) {159if (fake) {160try {161new FileOutputStream("fakeLeakyJVM" + LOG_SUFFIX, false);162} catch (FileNotFoundException e) {163}164}165}166167static Stream<String> run(String... args){168try {169return new BufferedReader(new InputStreamReader(new ProcessBuilder(args).start().getInputStream())).lines();170} catch (IOException e) {171throw new RuntimeException(e);172}173}174175static Optional<String[]> lsofCommandCache = stream(new String[][]{176{"/usr/bin/lsof", "-p"},177{"/usr/sbin/lsof", "-p"},178{"/bin/lsof", "-p"},179{"/sbin/lsof", "-p"},180{"/usr/local/bin/lsof", "-p"}})181.filter(args -> new File(args[0]).exists())182.findFirst();183184static Optional<String[]> lsofCommand() {185return lsofCommandCache;186}187188static Collection<String> outputContainingFilenames() {189long pid = ProcessHandle.current().pid();190String[] command = lsofCommand().orElseThrow(() -> new RuntimeException("lsof like command not found"));191// Only search the directory in which the VM is running (user.dir property).192System.out.println("using command: " + command[0] + " -a +d " + USER_DIR + " " + command[1] + " " + pid);193return run(command[0], "-a", "+d", USER_DIR, command[1], "" + pid).collect(toList());194}195196static boolean findOpenLogFile(Collection<String> fileNames) {197String pid = Long.toString(ProcessHandle.current().pid());198String[] command = lsofCommand().orElseThrow(() ->199new RuntimeException("lsof like command not found"));200String lsof = command[0];201boolean isBusybox = Platform.isBusybox(lsof);202return fileNames.stream()203// lsof from busybox does not support "-p" option204.filter(fileName -> !isBusybox || fileName.contains(pid))205.filter(fileName -> fileName.contains(LOG_SUFFIX))206.findAny()207.isPresent();208}209210static void windows(File f, long parentPid) throws InterruptedException {211System.out.println("waiting for pid: " + parentPid);212ProcessHandle.of(parentPid).ifPresent(handle -> handle.onExit().join());213System.out.println("trying to rename file to the same name: " + f);214System.out.println(f.renameTo(f) ? RETAINS_FD : LEAKS_FD); // this parts communicates a closed file descriptor by printing "VM RESULT => RETAINS FD"215}216}217218219220