File: MonitorVmStartTerminate.java

package info (click to toggle)
openjdk-11 11.0.4%2B11-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 757,028 kB
  • sloc: java: 5,016,041; xml: 1,191,974; cpp: 934,731; ansic: 555,697; sh: 24,299; objc: 12,703; python: 3,602; asm: 3,415; makefile: 2,772; awk: 351; sed: 172; perl: 114; jsp: 24; csh: 3
file content (328 lines) | stat: -rw-r--r-- 11,756 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/*
 * Copyright (c) 2004, 2017, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Semaphore;

import jdk.testlibrary.OutputAnalyzer;
import jdk.testlibrary.ProcessTools;
import sun.jvmstat.monitor.MonitorException;
import sun.jvmstat.monitor.MonitoredHost;
import sun.jvmstat.monitor.MonitoredVm;
import sun.jvmstat.monitor.MonitoredVmUtil;
import sun.jvmstat.monitor.VmIdentifier;
import sun.jvmstat.monitor.event.HostEvent;
import sun.jvmstat.monitor.event.HostListener;
import sun.jvmstat.monitor.event.VmStatusChangeEvent;

/*

 Test starts ten Java processes, each with a unique id.

 Each process creates a file named after the id and then it waits for
 the test to remove the file, at which the Java process exits.

 The processes are monitored by the test to make sure notifications
 are sent when they are started/terminated.

 To avoid Java processes being left behind, in case of an unexpected
 failure, shutdown hooks are installed that remove files when the test
 exits. If files are not removed, i.e. due to a JVM crash, the Java
 processes will exit themselves after 1000 s.

*/

/*
 * @test
 * @bug 4990825
 * @summary attach to external but local JVM processes
 * @library /lib/testlibrary
 * @modules java.management
 *          jdk.internal.jvmstat/sun.jvmstat.monitor
 *          jdk.internal.jvmstat/sun.jvmstat.monitor.event
 * @build jdk.testlibrary.*
 * @run main/othervm MonitorVmStartTerminate
 */
public final class MonitorVmStartTerminate {

    private static final int PROCESS_COUNT = 10;

    public static void main(String... args) throws Exception {

        MonitoredHost host = MonitoredHost.getMonitoredHost("localhost");
        host.setInterval(1); // 1 ms

        String id = UUID.randomUUID().toString();

        List<JavaProcess> javaProcesses = new ArrayList<>();
        for (int i = 0; i < PROCESS_COUNT; i++) {
            javaProcesses.add(new JavaProcess(id + "_" + i));
        }

        Listener listener = new Listener(host, javaProcesses);
        host.addHostListener(listener);
        for (JavaProcess javaProcess : javaProcesses) {
            javaProcess.start();
        }

        // Wait for all processes to start before terminating
        // them, so pids are not reused within a poll interval.
        System.out.println("Waiting for all processes to get started notification");
        listener.started.acquire(PROCESS_COUNT);

        for (JavaProcess javaProcess : javaProcesses) {
            javaProcess.terminate();
        }
        System.out.println("Waiting for all processes to get terminated notification");
        listener.terminated.acquire(PROCESS_COUNT);

        host.removeHostListener(listener);
    }

    private static final class Listener implements HostListener {
        private final Semaphore started = new Semaphore(0);
        private final Semaphore terminated = new Semaphore(0);
        private final MonitoredHost host;
        private final List<JavaProcess> processes;

        public Listener(MonitoredHost host, List<JavaProcess> processes) {
            this.host = host;
            this.processes = processes;
            printStatus();
        }

        @Override
        @SuppressWarnings("unchecked")
        public void vmStatusChanged(VmStatusChangeEvent event) {
            releaseStarted(event.getStarted());
            releaseTerminated(event.getTerminated());
            printStatus();
        }

        private void printStatus() {
            System.out.printf("started=%d, terminated=%d\n",
                    started.availablePermits(), terminated.availablePermits());
        }

        @Override
        public void disconnected(HostEvent arg0) {
            // ignore
        }

        private void releaseStarted(Set<Integer> ids) {
            System.out.println("realeaseStarted(" + ids + ")");
            for (Integer id : ids) {
                releaseStarted(id);
            }
        }

        private void releaseStarted(Integer id) {
            for (JavaProcess jp : processes) {
                if (hasMainArgs(id, jp.getMainArgsIdentifier())) {
                    // store id for terminated identification
                    jp.setId(id);
                    System.out.println("RELEASED (id=" + jp.getId() + ", args=" + jp.getMainArgsIdentifier() + ")");
                    started.release();
                    return;
                }
            }
        }

        private void releaseTerminated(Set<Integer> ids) {
            System.out.println("releaseTerminated(" + ids + ")");
            for (Integer id : ids) {
                releaseTerminated(id);
            }
        }

        private void releaseTerminated(Integer id) {
            for (JavaProcess jp : processes) {
                if (id.equals(jp.getId())) {
                    System.out.println("RELEASED (id=" + jp.getId() + ", args=" + jp.getMainArgsIdentifier() + ")");
                    terminated.release();
                    return;
                }
            }
        }

        private boolean hasMainArgs(Integer id, String args) {
            try {
                VmIdentifier vmid = new VmIdentifier("//" + id.intValue());
                MonitoredVm target = host.getMonitoredVm(vmid);
                String monitoredArgs = MonitoredVmUtil.mainArgs(target);
                if (monitoredArgs != null && monitoredArgs.contains(args)) {
                    return true;
                }
            } catch (URISyntaxException | MonitorException e) {
                // ok. process probably not running
            }
            return false;
        }
    }

    public final static class JavaProcess {

        private static final class ShutdownHook extends Thread {
            private final JavaProcess javaProcess;

            public ShutdownHook(JavaProcess javaProcess) {
                this.javaProcess = javaProcess;
            }

            public void run() {
                javaProcess.terminate();
            }
        }

        public static void main(String[] args) throws InterruptedException {
            try {
                Path path = Paths.get(args[0]);
                createFile(path);
                waitForRemoval(path);
            } catch (Throwable t) {
                t.printStackTrace();
                System.exit(1);
            }
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        private static void createFile(Path path) throws IOException {
            Files.write(path, new byte[0], StandardOpenOption.CREATE);
        }

        private static void waitForRemoval(Path path) {
            String timeoutFactorText = System.getProperty("test.timeout.factor", "1.0");
            double timeoutFactor = Double.parseDouble(timeoutFactorText);
            long timeoutNanos = 1000_000_000L*(long)(1000*timeoutFactor);
            long start = System.nanoTime();
            while (true) {
                long now = System.nanoTime();
                long waited = now - start;
                System.out.println("Waiting for " + path + " to be removed, " + waited + " ns");
                if (!Files.exists(path)) {
                    return;
                }
                if (waited > timeoutNanos) {
                    System.out.println("Start: " + start);
                    System.out.println("Now: " + now);
                    System.out.println("Process timed out after " + waited + " ns. Abort.");
                    System.exit(1);
                }
                takeNap();
            }
        }

        private static void takeNap() {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // ignore
            }
        }

        private final String mainArgsIdentifier;
        private final ShutdownHook shutdownHook;
        private volatile Integer id;

        public JavaProcess(String mainArgsIdentifier) {
            this.mainArgsIdentifier = mainArgsIdentifier;
            this.shutdownHook = new ShutdownHook(this);
        }

        /**
         * Starts a Java process asynchronously.
         *
         * The process runs until {@link #stop()} is called. If test exits
         * unexpectedly the process will be cleaned up by a shutdown hook.
         *
         * @throws Exception
         */
        public void start() throws Exception {
            Runtime.getRuntime().addShutdownHook(shutdownHook);
            System.out.println("Starting " + getMainArgsIdentifier());

            Runnable r = new Runnable() {
                @Override
                public void run() {
                    try {
                        executeJava();
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                }
            };
            new Thread(r).start();
        }

        public void terminate() {
            try {
                System.out.println("Terminating " + mainArgsIdentifier);
                // File must be created before proceeding,
                // otherwise Java process may loop forever
                // waiting for file to be removed.
                Path path = Paths.get(mainArgsIdentifier);
                while (!Files.exists(path)) {
                    takeNap();
                }
                Files.delete(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Runtime.getRuntime().removeShutdownHook(shutdownHook);
        }

        private void executeJava() throws Throwable {
            String className = JavaProcess.class.getName();
            String classPath = System.getProperty("test.classes");
            ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
                "-Dtest.timeout.factor=" + System.getProperty("test.timeout.factor", "1.0"),
                "-cp", classPath, className, mainArgsIdentifier);
            OutputAnalyzer ob = ProcessTools.executeProcess(pb);
            System.out.println("Java Process " + getMainArgsIdentifier() + " stderr:"
                    + ob.getStderr());
            System.err.println("Java Process " + getMainArgsIdentifier() + " stdout:"
                    + ob.getStdout());
        }

        public String getMainArgsIdentifier() {
            return mainArgsIdentifier;
        }
    }
}