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