1 /*
  2  * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  */
 23 
 24 import java.io.IOException;
 25 import java.time.Duration;
 26 import java.time.Instant;
 27 import java.util.ArrayList;
 28 import java.util.List;
 29 import java.util.concurrent.ArrayBlockingQueue;
 30 import java.util.concurrent.CompletableFuture;
 31 import java.util.concurrent.ConcurrentHashMap;
 32 import java.util.concurrent.ExecutionException;
 33 import java.util.concurrent.TimeUnit;
 34 
 35 import jdk.test.lib.Utils;
 36 
 37 import org.testng.annotations.Test;
 38 import org.testng.Assert;
 39 import org.testng.TestNG;
 40 
 41 /*
 42  * @test
 43  * @requires vm.flagless
 44  * @library /test/lib
 45  * @modules jdk.management
 46  * @build jdk.test.lib.Utils
 47  * @run testng OnExitTest
 48  * @summary Functions of Process.onExit and ProcessHandle.onExit
 49  * @author Roger Riggs
 50  */
 51 
 52 public class OnExitTest extends ProcessUtil {
 53 
 54     @SuppressWarnings("raw_types")
 55     public static void main(String[] args) {
 56         Class<?>[] testclass = { OnExitTest.class};
 57         TestNG testng = new TestNG();
 58         testng.setTestClasses(testclass);
 59         testng.run();
 60     }
 61 
 62     /**
 63      * Basic test of exitValue and onExit.
 64      */
 65     @Test
 66     public static void test1() {
 67         try {
 68             int[] exitValues = {0, 1, 10};
 69             for (int value : exitValues) {
 70                 Process p = JavaChild.spawn("exit", Integer.toString(value));
 71                 CompletableFuture<Process> future = p.onExit();
 72                 future.thenAccept( (ph) -> {
 73                     int actualExitValue = ph.exitValue();
 74                     printf(" javaChild done: %s, exitStatus: %d%n",
 75                             ph, actualExitValue);
 76                     Assert.assertEquals(actualExitValue, value, "actualExitValue incorrect");
 77                     Assert.assertEquals(ph, p, "Different Process passed to thenAccept");
 78                 });
 79 
 80                 Process h = future.get();
 81                 Assert.assertEquals(h, p);
 82                 Assert.assertEquals(p.exitValue(), value);
 83                 Assert.assertFalse(p.isAlive(), "Process should not be alive");
 84                 p.waitFor();
 85             }
 86         } catch (IOException | InterruptedException | ExecutionException ex) {
 87             Assert.fail(ex.getMessage(), ex);
 88         } finally {
 89             destroyProcessTree(ProcessHandle.current());
 90         }
 91     }
 92 
 93     /**
 94      * Test of Completion handler when parent is killed.
 95      * Spawn 1 child to spawn 3 children each with 2 children.
 96      */
 97     @Test
 98     public static void test2() {
 99 
100         // Please note (JDK-8284282):
101         //
102         // On Unix, this test relies on the ability of the system to adopt orphaned processes and
103         // reap them in a timely fashion. In other words, the ability to prevent orphans from becoming
104         // zombies.
105         //
106         // Therefore, on misconfigured or broken systems, this test may fail. These failures will manifest
107         // as timeouts. The failures depend on timing: they may not happen at all, be intermittent or
108         // constant.
109         //
110         // That will rarely be a problem on bare-metal systems but may be more common when running in
111         // Docker. Misconfigured Docker instances may run with an initial process unable to reap. One
112         // infamous example would be running jtreg tests inside a Docker via Jenkins CI.
113         //
114         // This is quite difficult - and inefficient - to fix inside this test, and rather easy to
115         // avoid. For a detailed analysis, as well as proposed workarounds, please see JDK-8284282.
116         //
117         ProcessHandle procHandle = null;
118         try {
119             ConcurrentHashMap<ProcessHandle, ProcessHandle> processes = new ConcurrentHashMap<>();
120             List<ProcessHandle> children = getChildren(ProcessHandle.current());
121             children.forEach(ProcessUtil::printProcess);
122 
123             JavaChild proc = JavaChild.spawnJavaChild("stdin");
124             procHandle = proc.toHandle();
125             printf(" spawned: %d%n", proc.pid());
126 
127             proc.forEachOutputLine((s) -> {
128                 String[] split = s.trim().split(" ");
129                 if (split.length == 3 && split[1].equals("spawn")) {
130                     Long child = Long.valueOf(split[2]);
131                     Long parent = Long.valueOf(split[0].split(":")[0]);
132                     processes.put(ProcessHandle.of(child).get(), ProcessHandle.of(parent).get());
133                 }
134             });
135 
136             proc.sendAction("spawn", "3", "stdin");
137 
138             proc.sendAction("child", "spawn", "2", "stdin");
139 
140             // Poll until all 9 child processes exist or the timeout is reached
141             int expected = 9;
142             long timeout = Utils.adjustTimeout(10L);
143             Instant endTimeout = Instant.now().plusSeconds(timeout);
144             do {
145                 Thread.sleep(200L);
146                 printf(" subprocess count: %d, waiting for %d%n", processes.size(), expected);
147             } while (processes.size() < expected &&
148                     Instant.now().isBefore(endTimeout));
149 
150             if (processes.size() < expected) {
151                 printf("WARNING: not all children have been started. Can't complete test.%n");
152                 printf("         You can try to increase the timeout or%n");
153                 printf("         you can try to use a faster VM (i.e. not a debug version).%n");
154             }
155             children = getDescendants(procHandle);
156 
157             ConcurrentHashMap<ProcessHandle, CompletableFuture<ProcessHandle>> completions =
158                     new ConcurrentHashMap<>();
159             Instant startTime = Instant.now();
160             // Create a future for each of the 9 children
161             processes.forEach( (p, parent) -> {
162                         CompletableFuture<ProcessHandle> cf = p.onExit().whenComplete((ph, ex) -> {
163                             Duration elapsed = Duration.between(startTime, Instant.now());
164                             printf("whenComplete: pid: %s, exception: %s, thread: %s, elapsed: %s%n",
165                                     ph, ex, Thread.currentThread(), elapsed);
166                         });
167                         completions.put(p, cf);
168                     });
169 
170             // Check that each of the spawned processes is included in the children
171             List<ProcessHandle> remaining = new ArrayList<>(children);
172             processes.forEach((p, parent) -> {
173                 Assert.assertTrue(remaining.remove(p), "spawned process should have been in children");
174             });
175 
176             // Remove Win32 system spawned conhost.exe processes
177             remaining.removeIf(ProcessUtil::isWindowsConsole);
178 
179             remaining.forEach(p -> printProcess(p, "unexpected: "));
180             if (remaining.size() > 0) {
181                 // Show full list for debugging
182                 ProcessUtil.logTaskList();
183             }
184 
185             proc.destroy();  // kill off the parent
186             proc.waitFor();
187 
188             // Wait for all the processes and corresponding onExit CF to be completed
189             processes.forEach((p, parent) -> {
190                 try {
191                     p.onExit().get();
192                     completions.get(p).join();
193                 } catch (InterruptedException | ExecutionException ex) {
194                     // ignore
195                 }
196             });
197 
198             // Verify that all 9 exit handlers were called with the correct ProcessHandle
199             processes.forEach((p, parent) -> {
200                 ProcessHandle value = completions.get(p).getNow(null);
201                 Assert.assertEquals(p, value, "onExit.get value expected: " + p
202                         + ", actual: " + value
203                         + ": " + p.info());
204             });
205 
206             // Show the status of the original children
207             children.forEach(p -> printProcess(p, "after onExit:"));
208 
209             Assert.assertEquals(proc.isAlive(), false, "destroyed process is alive:: %s%n" + proc);
210         } catch (IOException | InterruptedException ex) {
211             Assert.fail(ex.getMessage());
212         } finally {
213             if (procHandle != null) {
214                 destroyProcessTree(procHandle);
215             }
216         }
217     }
218 
219     /**
220      * Verify that onExit completes for a non-child process only when
221      * the process has exited.
222      * Spawn a child (A) waiting to be commanded to exit.
223      * Spawn a child (B) to wait for that process to exit.
224      * Command (A) to exit.
225      * Check that (B) does not complete until (A) has exited.
226      */
227     @Test
228     public static void peerOnExitTest() {
229         String line = null;
230         ArrayBlockingQueue<String> alines = new ArrayBlockingQueue<>(100);
231         ArrayBlockingQueue<String> blines = new ArrayBlockingQueue<>(100);
232         JavaChild A = null;
233         try {
234             String[] split;
235             A = JavaChild.spawnJavaChild("stdin");
236             A.forEachOutputLine(l -> alines.add(l));
237 
238             // Verify A is running
239             A.sendAction("pid");
240             do {
241                 split = getSplitLine(alines);
242             } while (!"pid".equals(split[1]));
243 
244             JavaChild B = null;
245             try {
246                 B = JavaChild.spawnJavaChild("stdin");
247                 B.forEachOutputLine(l -> blines.add(l));
248 
249                 // Verify B is running
250                 B.sendAction("pid");
251                 do {
252                     split = getSplitLine(blines);
253                 } while (!"pid".equals(split[1]));
254 
255                 // Tell B to wait for A's pid
256                 B.sendAction("waitpid", A.pid());
257 
258                 // Wait a bit to see if B will prematurely report the termination of A
259                 try {
260                     line = blines.poll(5L, TimeUnit.SECONDS);
261                 } catch (InterruptedException ie) {
262                     Assert.fail("interrupted", ie);
263                 }
264                 Assert.assertNull(line, "waitpid didn't wait");
265 
266                 A.toHandle().onExit().thenAccept(p -> {
267                     System.out.printf(" A.toHandle().onExit().A info: %s, now: %s%n",
268                             p.info(), Instant.now());
269                 });
270 
271                 A.onExit().thenAccept(p -> {
272                     System.out.printf(" A.onExit().A info: %s, now: %s%n",
273                             p.info(), Instant.now());
274                 });
275 
276                 ProcessHandle.Info A_info = A.info();
277 
278                 A.sendAction("exit", 0L);
279 
280                 // Look for B to report that A has exited
281                 do {
282                     Instant start = Instant.now();
283                     while (blines.isEmpty() && A.isAlive()) {
284                         A_info = A.info(); // Spin
285                     }
286                     Instant end = Instant.now();
287                     System.out.printf(" a.isAlive: %s, a.info: %s, @%s%n", A.isAlive(), A.info(),
288                             Duration.between(start, end));
289 
290                     split = getSplitLine(blines);
291                 } while (!"waitpid".equals(split[1]));
292 
293                 Assert.assertEquals(split[2], "false",  "Process A should not be alive");
294 
295                 B.sendAction("exit", 0L);
296             } catch (IOException ioe) {
297                 Assert.fail("unable to start JavaChild B", ioe);
298             } finally {
299                 B.destroyForcibly();
300             }
301         } catch (IOException ioe2) {
302             Assert.fail("unable to start JavaChild A", ioe2);
303         } finally {
304             A.destroyForcibly();
305         }
306     }
307 
308     private static boolean DEBUG = true;
309 
310     /**
311      * Get a line from the queue and split into words on whitespace.
312      * Log to stdout if requested.
313      * @param queue a queue of strings
314      * @return the words split from the line.
315      */
316     private static String[] getSplitLine(ArrayBlockingQueue<String> queue) {
317         try {
318             String line = queue.take();
319             String[] split = line.split("\\s");
320             if (DEBUG) {
321                 System.out.printf("  Child Output: %s%n", line);
322             }
323             return split;
324         } catch (InterruptedException ie) {
325             Assert.fail("interrupted", ie);
326             return null;
327         }
328     }
329 
330 }