24
import static java.lang.Character.isDigit;
25
import static java.lang.Long.parseLong;
26
import static java.lang.System.getProperty;
27
import static java.nio.file.Files.readAllBytes;
28
import static java.util.Arrays.stream;
29
import static java.util.stream.Collectors.joining;
30
import static java.util.stream.Collectors.toList;
31
import static jdk.test.lib.process.ProcessTools.createLimitedTestJavaProcessBuilder;
32
import static jdk.test.lib.Platform.isWindows;
33
import jdk.test.lib.Utils;
34
import jdk.test.lib.Platform;
35
import jtreg.SkippedException;
37
import java.io.BufferedReader;
39
import java.io.FileNotFoundException;
40
import java.io.FileOutputStream;
41
import java.io.IOException;
42
import java.io.InputStreamReader;
43
import java.util.Collection;
44
import java.util.concurrent.TimeoutException;
45
import java.util.concurrent.CompletionException;
46
import java.util.concurrent.TimeUnit;
47
import java.util.Optional;
48
import java.util.stream.Stream;
81
public class TestInheritFD {
83
public static final String LEAKS_FD = "VM RESULT => LEAKS FD";
84
public static final String RETAINS_FD = "VM RESULT => RETAINS FD";
85
public static final String EXIT = "VM RESULT => VM EXIT";
86
public static final String LOG_SUFFIX = ".strangelogsuffixthatcanbecheckedfor";
87
public static final String USER_DIR = System.getProperty("user.dir");
88
public static final String LSOF_PID_PREFIX = " VM lsof pid=";
89
public static final String SECOND_VM_PID_PREFIX = "Second VM pid=";
90
public static final String THIRD_VM_PID_PREFIX = "Third VM pid=";
91
public static final String THIRD_VM_WAITING_PREFIX = "Third VM waiting for second VM pid=";
93
public static float timeoutFactor = Float.parseFloat(System.getProperty("test.timeout.factor", "1.0"));
94
public static long subProcessTimeout = (long)(15L * timeoutFactor);
97
private static long extractPidFromStringOffset(String str, int start) {
99
for (end = start; end < str.length(); end++) {
100
if (!isDigit(str.charAt(end))) {
107
return parseLong(str.substring(start, end));
117
private static Result waitForSubPids(File commFile) throws Exception {
120
long secondVMPID = -1;
121
long secondVMlsofPID = -1;
122
long thirdVMPID = -1;
123
long thirdVMlsofPID = -1;
125
String doneWithPattern;
127
doneWithPattern = THIRD_VM_PID_PREFIX;
129
doneWithPattern = "Third" + LSOF_PID_PREFIX;
132
out = new String(readAllBytes(commFile.toPath()));
133
if (secondVMPID == -1) {
134
int ind = out.indexOf(SECOND_VM_PID_PREFIX);
136
int startPid = ind + SECOND_VM_PID_PREFIX.length();
137
secondVMPID = extractPidFromStringOffset(out, startPid);
138
System.out.println("secondVMPID=" + secondVMPID);
141
if (!isWindows() && secondVMlsofPID == -1) {
142
String prefix = "Second" + LSOF_PID_PREFIX;
143
int ind = out.indexOf(prefix);
145
int startPid = ind + prefix.length();
146
secondVMlsofPID = extractPidFromStringOffset(out, startPid);
147
System.out.println("secondVMlsofPID=" + secondVMlsofPID);
150
if (thirdVMPID == -1) {
151
int ind = out.indexOf(THIRD_VM_PID_PREFIX);
153
int startPid = ind + THIRD_VM_PID_PREFIX.length();
154
thirdVMPID = extractPidFromStringOffset(out, startPid);
155
System.out.println("thirdVMPID=" + thirdVMPID);
158
if (!isWindows() && thirdVMlsofPID == -1) {
159
String prefix = "Third" + LSOF_PID_PREFIX;
160
int ind = out.indexOf(prefix);
162
int startPid = ind + prefix.length();
163
thirdVMlsofPID = extractPidFromStringOffset(out, startPid);
164
System.out.println("thirdVMlsofPID=" + thirdVMlsofPID);
169
} while (!out.contains(doneWithPattern) && !out.contains(EXIT));
171
System.out.println("Called Thread.sleep(100) " + sleepCnt + " times.");
173
long subPids[] = new long[4];
174
String subNames[] = new String[4];
176
if (!isWindows() && secondVMlsofPID != -1) {
178
subPids[ind] = secondVMlsofPID;
179
subNames[ind] = "second VM lsof";
183
subPids[ind] = secondVMPID;
184
subNames[ind] = "second VM";
186
if (!isWindows() && thirdVMlsofPID != -1) {
188
subPids[ind] = thirdVMlsofPID;
189
subNames[ind] = "third VM lsof";
193
subPids[ind] = thirdVMPID;
194
subNames[ind] = "third VM";
199
for (; ind < subPids.length; ind++) {
205
for (ind = 0; ind < subPids.length; ind++) {
206
if (subPids[ind] == -1) {
209
System.out.print("subs[" + ind + "]={pid=" + subPids[ind] + ", name=" + subNames[ind] + "}");
210
ProcessHandle.of(subPids[ind]).ifPresent(handle -> handle.onExit().orTimeout(subProcessTimeout, TimeUnit.SECONDS).join());
211
System.out.println(" finished.");
213
} catch (Exception e) {
215
System.out.println(" Exception was thrown while trying to join() subPids: " + e.toString());
219
out = new String(readAllBytes(commFile.toPath()));
220
System.out.println("<BEGIN commFile contents>");
221
System.out.println(out);
222
System.out.println("<END commFile contents>");
224
if (out.contains(RETAINS_FD)) {
225
return Result.FOUND_RETAINS_FD;
226
} else if (out.contains(LEAKS_FD)) {
227
return Result.FOUND_LEAKS_FD;
229
return Result.FOUND_NONE;
234
public static void main(String[] args) throws Exception {
235
System.out.println("subProcessTimeout=" + subProcessTimeout + " seconds.");
236
System.out.println("First VM starts.");
237
String logPath = Utils.createTempFile("logging", LOG_SUFFIX).toFile().getName();
238
File commFile = Utils.createTempFile("communication", ".txt").toFile();
240
if (!isWindows() && !lsofCommand().isPresent()) {
241
throw new SkippedException("Could not find lsof like command");
244
ProcessBuilder pb = createLimitedTestJavaProcessBuilder(
245
"-Xlog:gc:\"" + logPath + "\"",
246
"-Dtest.jdk=" + getProperty("test.jdk"),
247
VMStartedWithLogging.class.getName(),
250
pb.redirectOutput(commFile);
253
Result result = waitForSubPids(commFile);
254
if (result == Result.FOUND_RETAINS_FD) {
255
System.out.println("Log file was not inherited by third VM.");
256
} else if (result == Result.FOUND_LEAKS_FD) {
257
throw new RuntimeException("Log file was leaked to the third VM.");
259
throw new RuntimeException("Found neither message, test failed to run correctly");
261
System.out.println("First VM ends.");
264
static class VMStartedWithLogging {
266
public static void main(String[] args) throws IOException, InterruptedException {
267
System.out.println(SECOND_VM_PID_PREFIX + ProcessHandle.current().pid());
268
ProcessBuilder pb = createLimitedTestJavaProcessBuilder(
269
"-Dtest.jdk=" + getProperty("test.jdk"),
270
VMShouldNotInheritFileDescriptors.class.getName(),
272
"" + ProcessHandle.current().pid());
277
System.out.println("(Second VM) Open file descriptors:\n" + outputContainingFilenames("Second").stream().collect(joining("\n")));
280
Thread.sleep(300 * 1000);
282
System.out.println("Second VM ends.");
286
static class VMShouldNotInheritFileDescriptors {
288
public static void main(String[] args) throws InterruptedException {
289
System.out.println(THIRD_VM_PID_PREFIX + ProcessHandle.current().pid());
291
File logFile = new File(args[0]);
292
long parentPid = parseLong(args[1]);
295
System.out.println(THIRD_VM_WAITING_PREFIX + parentPid);
296
ProcessHandle.of(parentPid).ifPresent(handle -> handle.onExit().orTimeout(subProcessTimeout, TimeUnit.SECONDS).join());
301
Collection<String> output = outputContainingFilenames("Third");
302
System.out.println("(Third VM) Open file descriptors:\n" + output.stream().collect(joining("\n")));
303
System.out.println(findOpenLogFile(output) ? LEAKS_FD : RETAINS_FD);
306
Thread.sleep(300 * 1000);
308
} catch (CompletionException e) {
309
if (e.getCause() instanceof TimeoutException) {
310
System.out.println("(Third VM) Timed out waiting for second VM: " + e.toString());
312
System.out.println("(Third VM) Exception was thrown: " + e.toString());
315
} catch (Exception e) {
316
System.out.println("(Third VM) Exception was thrown: " + e.toString());
319
System.out.println(EXIT);
320
System.out.println("Third VM ends.");
326
@SuppressWarnings("resource")
327
static void fakeLeakyJVM(boolean fake) {
330
new FileOutputStream("fakeLeakyJVM" + LOG_SUFFIX, false);
331
} catch (FileNotFoundException e) {
336
static Stream<String> runLsof(String whichVM, String... args){
338
Process lsof = new ProcessBuilder(args).start();
339
System.out.println(whichVM + LSOF_PID_PREFIX + lsof.pid());
340
return new BufferedReader(new InputStreamReader(lsof.getInputStream())).lines();
341
} catch (IOException e) {
342
throw new RuntimeException(e);
346
static Optional<String[]> lsofCommandCache = stream(new String[][]{
347
{"/usr/bin/lsof", "-p"},
348
{"/usr/sbin/lsof", "-p"},
350
{"/sbin/lsof", "-p"},
351
{"/usr/local/bin/lsof", "-p"}})
352
.filter(args -> new File(args[0]).exists())
355
static Optional<String[]> lsofCommand() {
356
return lsofCommandCache;
359
static Collection<String> outputContainingFilenames(String whichVM) {
360
long pid = ProcessHandle.current().pid();
361
String[] command = lsofCommand().orElseThrow(() -> new RuntimeException("lsof like command not found"));
363
System.out.println("using command: " + command[0] + " -a +d " + USER_DIR + " " + command[1] + " " + pid);
364
return runLsof(whichVM, command[0], "-a", "+d", USER_DIR, command[1], "" + pid).collect(toList());
367
static boolean findOpenLogFile(Collection<String> fileNames) {
368
String pid = Long.toString(ProcessHandle.current().pid());
369
String[] command = lsofCommand().orElseThrow(() ->
370
new RuntimeException("lsof like command not found"));
371
String lsof = command[0];
372
boolean isBusybox = Platform.isBusybox(lsof);
373
return fileNames.stream()
375
.filter(fileName -> !isBusybox || fileName.contains(pid))
376
.filter(fileName -> fileName.contains(LOG_SUFFIX))
381
static void windows(File f) throws InterruptedException {
382
System.out.println("trying to rename file to the same name: " + f);
383
System.out.println(f.renameTo(f) ? RETAINS_FD : LEAKS_FD);