1 /*
2  * Copyright (c) 2013, 2018, 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.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 package jdk.jfr.jmx;
27 
28 import java.io.BufferedOutputStream;
29 import java.io.File;
30 import java.io.FileOutputStream;
31 import java.io.IOException;
32 import java.lang.management.ManagementFactory;
33 import java.time.Instant;
34 import java.util.ArrayList;
35 import java.util.HashMap;
36 import java.util.List;
37 import java.util.Map;
38 
39 import com.sun.tools.attach.VirtualMachine;
40 import jdk.jfr.EventType;
41 import jdk.jfr.FlightRecorder;
42 import jdk.jfr.Recording;
43 import jdk.jfr.RecordingState;
44 import jdk.jfr.SettingDescriptor;
45 import jdk.jfr.consumer.RecordedEvent;
46 import jdk.jfr.consumer.RecordingFile;
47 import jdk.management.jfr.EventTypeInfo;
48 import jdk.management.jfr.FlightRecorderMXBean;
49 import jdk.management.jfr.RecordingInfo;
50 import jdk.management.jfr.SettingDescriptorInfo;
51 import jdk.test.lib.Asserts;
52 import jdk.test.lib.jfr.CommonHelper;
53 import jdk.test.lib.jfr.Events;
54 
55 import javax.management.JMX;
56 import javax.management.MBeanServerConnection;
57 import javax.management.ObjectName;
58 import javax.management.remote.JMXConnector;
59 import javax.management.remote.JMXConnectorFactory;
60 import javax.management.remote.JMXServiceURL;
61 
62 public class JmxHelper {
63     private static final String LOCAL_CONNECTION_ADDRESS = "com.sun.management.jmxremote.localConnectorAddress";
64 
getJmxRecording(long recId)65     public static RecordingInfo getJmxRecording(long recId) {
66         for (RecordingInfo r : getFlighteRecorderMXBean().getRecordings()) {
67             if (r.getId() == recId) {
68                 return r;
69             }
70         }
71         Asserts.fail("No RecordingInfo with id " + recId);
72         return null;
73     }
74 
getJavaRecording(long recId)75     public static Recording getJavaRecording(long recId) {
76         for (Recording r : FlightRecorder.getFlightRecorder().getRecordings()) {
77             if (r.getId() == recId) {
78                 return r;
79             }
80         }
81         Asserts.fail("No Recording with id " + recId);
82         return null;
83     }
84 
verifyState(long recId, RecordingState state, List<RecordingInfo> recordings)85     public static void verifyState(long recId, RecordingState state, List<RecordingInfo> recordings) {
86         RecordingInfo r = verifyExists(recId, recordings);
87         verifyState(r, state);
88     }
89 
verifyState(RecordingInfo recording, RecordingState state)90     public static void verifyState(RecordingInfo recording, RecordingState state) {
91         final String actual = recording.getState().toString();
92         final String expected = state.toString();
93         Asserts.assertEquals(actual, expected, "Wrong state");
94     }
95 
verifyState(long recId, RecordingState state, FlightRecorderMXBean bean)96     public static void verifyState(long recId, RecordingState state, FlightRecorderMXBean bean) throws Exception {
97         FlightRecorder jfr = FlightRecorder.getFlightRecorder();
98         Recording recording = CommonHelper.verifyExists(recId, jfr.getRecordings());
99         CommonHelper.verifyRecordingState(recording, state);
100         verifyState(recId, state, bean.getRecordings());
101     }
102 
verifyNotExists(long recId, List<RecordingInfo> recordings)103     public static void verifyNotExists(long recId, List<RecordingInfo> recordings) {
104         for (RecordingInfo r : recordings) {
105             if (recId == r.getId()) {
106                 logRecordingInfos(recordings);
107                 Asserts.fail("Recording should not exist, id=" + recId);
108             }
109         }
110     }
111 
verifyExists(long recId, List<RecordingInfo> recordings)112     public static RecordingInfo verifyExists(long recId, List<RecordingInfo> recordings) {
113         for (RecordingInfo r : recordings) {
114             if (recId == r.getId()) {
115                 return r;
116             }
117         }
118         logRecordingInfos(recordings);
119         Asserts.fail("Recording not found, id=" + recId);
120         return null;
121     }
122 
123 
logRecordingInfos(List<RecordingInfo> recordings)124     public static void logRecordingInfos(List<RecordingInfo> recordings) {
125         System.out.println("RecordingInfos:");
126         for (RecordingInfo r : recordings) {
127             System.out.println(asString(r));
128         }
129     }
130 
logRecordings(List<Recording> recordings)131     public static void logRecordings(List<Recording> recordings) {
132         System.out.println("Recordings:");
133         for (Recording r : recordings) {
134             System.out.println(asString(r));
135         }
136     }
137 
dump(long streamId, FlightRecorderMXBean bean)138     static File dump(long streamId, FlightRecorderMXBean bean) throws IOException {
139         File f = File.createTempFile("stream_" + streamId + "_", ".jfr", new File("."));
140         try (FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos)) {
141             while (true) {
142                 byte[] data = bean.readStream(streamId);
143                 if (data == null) {
144                     bos.flush();
145                     return f;
146                 }
147                 bos.write(data);
148             }
149         }
150     }
151 
parseStream(long streamId, FlightRecorderMXBean bean)152     public static List<RecordedEvent> parseStream(long streamId, FlightRecorderMXBean bean) throws Exception {
153         File dumpFile = dump(streamId, bean);
154         System.out.println("data.length=" + dumpFile.length());
155         List<RecordedEvent> events = new ArrayList<>();
156         for (RecordedEvent event : RecordingFile.readAllEvents(dumpFile.toPath())) {
157             System.out.println("EVENT:" + event);
158             events.add(event);
159         }
160         return events;
161     }
162 
verifyEquals(RecordingInfo ri, Recording r)163     public static void verifyEquals(RecordingInfo ri, Recording r) {
164         String destination = r.getDestination() != null ? r.getDestination().toString() : null;
165         long maxAge = r.getMaxAge() != null ? r.getMaxAge().getSeconds() : 0;
166         long duration = r.getDuration() != null ? r.getDuration().getSeconds() : 0;
167 
168         Asserts.assertEquals(destination, ri.getDestination(), "Wrong destination");
169         Asserts.assertEquals(r.getDumpOnExit(), ri.getDumpOnExit(), "Wrong dumpOnExit");
170         Asserts.assertEquals(duration, ri.getDuration(), "Wrong duration");
171         Asserts.assertEquals(r.getId(), ri.getId(), "Wrong id");
172         Asserts.assertEquals(maxAge, ri.getMaxAge(), "Wrong maxAge");
173         Asserts.assertEquals(r.getMaxSize(), ri.getMaxSize(), "Wrong maxSize");
174         Asserts.assertEquals(r.getName(), ri.getName(), "Wrong name");
175         Asserts.assertEquals(r.getSize(), ri.getSize(), "Wrong size");
176         Asserts.assertEquals(toEpochMillis(r.getStartTime()), ri.getStartTime(), "Wrong startTime");
177         Asserts.assertEquals(r.getState().toString(), ri.getState(), "Wrong state");
178         Asserts.assertEquals(toEpochMillis(r.getStopTime()), ri.getStopTime(), "Wrong stopTime");
179 
180         verifyMapEquals(r.getSettings(), ri.getSettings());
181     }
182 
asString(RecordingInfo r)183     public static String asString(RecordingInfo r) {
184         StringBuffer sb = new StringBuffer();
185         sb.append(String.format("RecordingInfo:%n"));
186         sb.append(String.format("destination=%s%n", r.getDestination()));
187         sb.append(String.format("dumpOnExit=%b%n", r.getDumpOnExit()));
188         sb.append(String.format("duration=%d%n", r.getDuration()));
189         sb.append(String.format("id=%d%n", r.getId()));
190         sb.append(String.format("maxAge=%d%n", r.getMaxAge()));
191         sb.append(String.format("maxSize=%d%n", r.getMaxSize()));
192         sb.append(String.format("getName=%s%n", r.getName()));
193         sb.append(String.format("size=%d%n", r.getSize()));
194         sb.append(String.format("startTime=%d%n", r.getStartTime()));
195         sb.append(String.format("state=%s%n", r.getState()));
196         sb.append(String.format("stopTime=%d%n", r.getStopTime()));
197         return sb.toString();
198     }
199 
asString(Recording r)200     public static String asString(Recording r) {
201         StringBuffer sb = new StringBuffer();
202         sb.append(String.format("Recording:%n"));
203         sb.append(String.format("destination=%s%n", r.getDestination()));
204         sb.append(String.format("dumpOnExit=%b%n", r.getDumpOnExit()));
205         sb.append(String.format("duration=%d%n", r.getDuration().getSeconds()));
206         sb.append(String.format("id=%d%n", r.getId()));
207         sb.append(String.format("maxAge=%d%n", r.getMaxAge().getSeconds()));
208         sb.append(String.format("maxSize=%d%n", r.getMaxSize()));
209         sb.append(String.format("getName=%s%n", r.getName()));
210         sb.append(String.format("size=%d%n", r.getSize()));
211         sb.append(String.format("startTime=%d%n", toEpochMillis(r.getStartTime())));
212         sb.append(String.format("state=%s%n", r.getState()));
213         sb.append(String.format("stopTime=%d%n", toEpochMillis(r.getStopTime())));
214         return sb.toString();
215     }
216 
verifyMapEquals(Map<String, String> a, Map<String, String> b)217     public static void verifyMapEquals(Map<String, String> a, Map<String, String> b) {
218         try {
219             Asserts.assertEquals(a.size(), b.size(), "Wrong number of keys");
220             for (String key : a.keySet()) {
221                 Asserts.assertTrue(a.containsKey(key), "Missing key " + key);
222                 Asserts.assertEquals(a.get(key), b.get(key), "Wrong values for key " + key);
223                 //System.out.printf("equal: %s=%s%n", key, a.get(key));
224             }
225         } catch (Exception e) {
226             System.out.println("Error: " + e.getMessage());
227             logMap("a", a);
228             logMap("b", b);
229             throw e;
230         }
231     }
232 
logMap(String name, Map<String, String> map)233     public static void logMap(String name, Map<String, String> map) {
234         for (String key : map.keySet()) {
235             System.out.printf("map %s: %s=%s%n", name, key, map.get(key));
236         }
237     }
238 
toEpochMillis(Instant instant)239     private static long toEpochMillis(Instant instant) {
240         return instant != null ? instant.toEpochMilli() : 0;
241     }
242 
verifyEventSettingsEqual(EventType javaType, EventTypeInfo jmxType)243     public static void verifyEventSettingsEqual(EventType javaType, EventTypeInfo jmxType) {
244         Map<String, SettingDescriptor> javaSettings = new HashMap<>();
245         for (SettingDescriptor settingDescriptor : javaType.getSettingDescriptors()) {
246             javaSettings.put(settingDescriptor.getName(), settingDescriptor);
247         }
248         Asserts.assertFalse(javaSettings.isEmpty(), "No ValueDescriptor for EventType " + javaType.getName());
249 
250         for (SettingDescriptorInfo jmxSetting : jmxType.getSettingDescriptors()) {
251             final String name = jmxSetting.getName();
252             System.out.printf("SettingDescriptorInfo: %s#%s=%s%n", jmxType.getName(), name, jmxSetting.getDefaultValue());
253             SettingDescriptor javaSetting = javaSettings.remove(name);
254             Asserts.assertNotNull(javaSetting, "No Setting for name " + name);
255             Asserts.assertEquals(jmxSetting.getDefaultValue(), Events.getSetting(javaType, name).getDefaultValue(), "Wrong default value");
256             Asserts.assertEquals(jmxSetting.getDescription(), javaSetting.getDescription(), "Wrong description");
257             Asserts.assertEquals(jmxSetting.getLabel(), javaSetting.getLabel(), "Wrong label");
258             Asserts.assertEquals(jmxSetting.getName(), javaSetting.getName(), "Wrong name");
259             Asserts.assertEquals(jmxSetting.getTypeName(), javaSetting.getTypeName(), "Wrong type name");
260             Asserts.assertEquals(jmxSetting.getContentType(), javaSetting.getContentType());
261         }
262 
263         // Verify that all Settings have been matched.
264         if (!javaSettings.isEmpty()) {
265             for (String name : javaSettings.keySet()) {
266                 System.out.println("Missing setting" + name + " in EventTypeInfo for " + javaType.getName());
267             }
268             System.out.println();
269             System.out.println(javaType.getName() + " Java API");
270             System.out.println("===============");
271             for (SettingDescriptor v : javaType.getSettingDescriptors()) {
272                 System.out.println(" - " + v.getName());
273             }
274             System.out.println();
275             System.out.println(jmxType.getName() + " JMX API");
276             System.out.println("===============");
277             for (SettingDescriptorInfo v : jmxType.getSettingDescriptors()) {
278                 System.out.println(" - " + v.getName());
279             }
280 
281             Asserts.fail("Missing setting");
282         }
283     }
284 
285 
getFlighteRecorderMXBean()286     public static FlightRecorderMXBean getFlighteRecorderMXBean() {
287         return ManagementFactory.getPlatformMXBean(FlightRecorderMXBean.class);
288     }
289 
getPID()290     public static long getPID(){
291         return ManagementFactory.getRuntimeMXBean().getPid();
292     }
293 
getFlighteRecorderMXBean(long pid)294     public static FlightRecorderMXBean getFlighteRecorderMXBean(long pid) throws Exception {
295         VirtualMachine targetVM = VirtualMachine.attach("" + pid);
296         String jmxServiceUrl = targetVM.getAgentProperties().getProperty(LOCAL_CONNECTION_ADDRESS);
297         JMXServiceURL jmxURL = new JMXServiceURL(jmxServiceUrl);
298         JMXConnector connector = JMXConnectorFactory.connect(jmxURL);
299         MBeanServerConnection connection = connector.getMBeanServerConnection();
300 
301         ObjectName objectName = new ObjectName("jdk.management.jfr:type=FlightRecorder");
302         return JMX.newMXBeanProxy(connection, objectName, FlightRecorderMXBean.class);
303     }
304 }
305