Java Code Examples for jdk.jfr.consumer.RecordingFile#readAllEvents()

The following examples show how to use jdk.jfr.consumer.RecordingFile#readAllEvents() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestJcmdStartWithSettings.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void assertHasEvent(File file, String eventType, String threadName) throws Exception {
    for (RecordedEvent event : RecordingFile.readAllEvents(file.toPath())) {
        if (Events.isEventType(event, eventType)) {
            System.out.println(event);
            RecordedThread t = event.getThread();
            if (t == null) {
                throw new Exception("Thread null for event " + eventType);
            }
            if (threadName.equals(t.getJavaName())) {
                System.out.println("Found event: " + event);
                return;
            }
        }
    }
    Asserts.fail("No events of type " + eventType);
}
 
Example 2
Source File: TestDestReadOnly.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    Path readOnlyDir = FileHelper.createReadOnlyDir(Paths.get(".", "readonly"));
    if (!FileHelper.isReadOnlyPath(readOnlyDir)) {
        System.out.println("Failed to create read-only dir. Running as root?. Test ignored");
        return;
    }

    Path readOnlyDest = Paths.get(readOnlyDir.toString(), "readonly.jfr");
    Recording r = new Recording();
    r.enable(EventNames.OSInformation);
    r.setToDisk(true);
    verifyException(()->{r.setDestination(readOnlyDest);}, "No exception for setDestination to read-only dir");

    System.out.println("r.getDestination() = " + r.getDestination());

    // Verify that it works if we set destination to a writable dir.
    Path dest = Paths.get(".", "my.jfr");
    r.setDestination(dest);
    r.start();
    r.stop();
    r.close();
    Asserts.assertTrue(Files.exists(dest), "No recording file: " + dest);
    List<RecordedEvent> events = RecordingFile.readAllEvents(dest);
    Asserts.assertFalse(events.isEmpty(), "No event found");
    System.out.printf("Found event %s in %s%n", events.get(0).getEventType().getName(), dest.toString());
}
 
Example 3
Source File: TestDestWithDuration.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    Path dest = Paths.get(".", "my.jfr");
    Recording r = new Recording();
    SimpleEventHelper.enable(r, true);
    r.setDestination(dest);
    r.start();
    SimpleEventHelper.createEvent(1);

    // Waiting for recording to auto close after duration
    r.setDuration(Duration.ofSeconds(1));
    System.out.println("Waiting for recording to auto close after duration");
    CommonHelper.waitForRecordingState(r, RecordingState.CLOSED);
    System.out.println("recording state = " + r.getState());
    Asserts.assertEquals(r.getState(), RecordingState.CLOSED, "Recording not closed");

    Asserts.assertTrue(Files.exists(dest), "No recording file: " + dest);
    System.out.printf("Recording file size=%d%n", Files.size(dest));
    Asserts.assertNotEquals(Files.size(dest), 0L, "File length 0. Should at least be some bytes");

    List<RecordedEvent> events = RecordingFile.readAllEvents(dest);
    Asserts.assertFalse(events.isEmpty(), "No event found");
    System.out.printf("Found event %s%n", events.get(0).getEventType().getName());
}
 
Example 4
Source File: PromotionFailedEvent.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void test(String testName, String[] vmFlags) throws Throwable {
    String jfr_file = testName + ".jfr";

    if (!ExecuteOOMApp.execute(EVENT_SETTINGS_FILE, jfr_file, vmFlags, BYTES_TO_ALLOCATE)) {
        System.out.println("OOM happened in the other thread(not test thread). Skip test.");
        // Skip test, process terminates due to the OOME error in the different thread
        return;
    }

    // This test can not always trigger the expected event.
    // Test is ok even if no events found.
    List<RecordedEvent> events = RecordingFile.readAllEvents(Paths.get(jfr_file));
    for (RecordedEvent event : events) {
        System.out.println("Event: " + event);
        long smallestSize = Events.assertField(event, "promotionFailed.smallestSize").atLeast(1L).getValue();
        long firstSize = Events.assertField(event, "promotionFailed.firstSize").atLeast(smallestSize).getValue();
        long totalSize = Events.assertField(event, "promotionFailed.totalSize").atLeast(firstSize).getValue();
        long objectCount = Events.assertField(event, "promotionFailed.objectCount").atLeast(1L).getValue();
        Asserts.assertLessThanOrEqual(smallestSize * objectCount, totalSize, "smallestSize * objectCount <= totalSize");
    }
}
 
Example 5
Source File: TestDumpState.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void checkEvents(Recording r, List<Integer> expectedIds) throws Exception {
    Path path = Paths.get(".", String.format("%d.jfr", recordingCounter++));
    r.dump(path);
    Asserts.assertTrue(Files.exists(path), "Recording file does not exist: " + path);

    int index = 0;

    for (RecordedEvent event : RecordingFile.readAllEvents(path)) {
        Events.isEventType(event, SimpleEvent.class.getName());
        Integer id = Events.assertField(event, "id").getValue();
        System.out.println("Got event with id " + id);
        Asserts.assertGreaterThan(expectedIds.size(), index, "Too many Events found");
        Asserts.assertEquals(id, expectedIds.get(index), "Wrong id at index " + index);
        ++index;
    }
    Asserts.assertEquals(index, expectedIds.size(), "Too few Events found");
}
 
Example 6
Source File: TestDestFileExist.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    Path dest = Paths.get(".", "my.jfr");
    System.out.println("dest=" + dest);
    Files.write(dest, "Dummy data".getBytes());
    assertTrue(Files.exists(dest), "Test error: Failed to create file");
    System.out.println("file size before recording:" + Files.size(dest));
    Recording r = new Recording();
    r.enable(EventNames.OSInformation);
    r.setDestination(dest);
    r.start();
    r.stop();
    List<RecordedEvent> events = RecordingFile.readAllEvents(dest);
    Asserts.assertFalse(events.isEmpty(), "No events found");
    System.out.println(events.iterator().next());
    r.close();
}
 
Example 7
Source File: TestDestReadOnly.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    Path readOnlyDir = FileHelper.createReadOnlyDir(Paths.get(".", "readonly"));
    if (!FileHelper.isReadOnlyPath(readOnlyDir)) {
        System.out.println("Failed to create read-only dir. Running as root?. Test ignored");
        return;
    }

    Path readOnlyDest = Paths.get(readOnlyDir.toString(), "readonly.jfr");
    Recording r = new Recording();
    r.enable(EventNames.OSInformation);
    r.setToDisk(true);
    verifyException(()->{r.setDestination(readOnlyDest);}, "No exception for setDestination to read-only dir");

    System.out.println("r.getDestination() = " + r.getDestination());

    // Verify that it works if we set destination to a writable dir.
    Path dest = Paths.get(".", "my.jfr");
    r.setDestination(dest);
    r.start();
    r.stop();
    r.close();
    Asserts.assertTrue(Files.exists(dest), "No recording file: " + dest);
    List<RecordedEvent> events = RecordingFile.readAllEvents(dest);
    Asserts.assertFalse(events.isEmpty(), "No event found");
    System.out.printf("Found event %s in %s%n", events.get(0).getEventType().getName(), dest.toString());
}
 
Example 8
Source File: TestCloneRepeat.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void verifyEvents(Path path, List<Integer> ids) throws Exception {
    List<RecordedEvent> events = RecordingFile.readAllEvents(path);
    Iterator<RecordedEvent> iterator = events.iterator();
    for (int i=0; i<ids.size(); i++) {
        Asserts.assertTrue(iterator.hasNext(), "Missing event " + ids.get(i));
        EventField idField = Events.assertField(iterator.next(), "id");
        System.out.println("Event.id=" + idField.getValue());
        idField.equal(ids.get(i).intValue());
    }
    if (iterator.hasNext()) {
        Asserts.fail("Got extra event: " + iterator.next());
    }
}
 
Example 9
Source File: TestPrintJSON.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws Throwable {

        Path recordingFile = ExecuteHelper.createProfilingRecording().toAbsolutePath();

        OutputAnalyzer output = ExecuteHelper.jfr("print", "--json", "--stack-depth", "999", recordingFile.toString());
        String json = output.getStdout();

        // Parse JSON using Nashorn
        String statement = "var jsonObject = " + json;
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName("nashorn");
        engine.eval(statement);
        JSObject o = (JSObject) engine.get("jsonObject");
        JSObject recording = (JSObject) o.getMember("recording");
        JSObject jsonEvents = (JSObject) recording.getMember("events");

        List<RecordedEvent> events = RecordingFile.readAllEvents(recordingFile);
        Collections.sort(events, (e1, e2) -> e1.getEndTime().compareTo(e2.getEndTime()));
        // Verify events are equal
        Iterator<RecordedEvent> it = events.iterator();

        for (Object jsonEvent : jsonEvents.values()) {
            RecordedEvent recordedEvent = it.next();
            String typeName = recordedEvent.getEventType().getName();
            Asserts.assertEquals(typeName, ((JSObject) jsonEvent).getMember("type").toString());
            assertEquals(jsonEvent, recordedEvent);
        }
        Asserts.assertFalse(events.size() != jsonEvents.values().size(), "Incorrect number of events");
    }
 
Example 10
Source File: FileHelper.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void verifyRecording(File file) throws Exception {
    Asserts.assertTrue(file.exists(), file.getAbsolutePath() + " does not exist");
    Asserts.assertTrue(file.isFile(), file.getAbsolutePath() + " is not a file");
    Asserts.assertGreaterThan(file.length(), 0L, "Size of recording is 0.");
    List<RecordedEvent> events = RecordingFile.readAllEvents(file.toPath());
    for (RecordedEvent event : events) {
        System.out.printf("First event in recording '%s':%n%s", file.getName(), event);
        return;
    }
    Asserts.fail("No events in file " + file.getName());
}
 
Example 11
Source File: TestJcmdDumpPathToGCRoots.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void testDump(String pathToGcRoots, Map<String, String> settings, boolean expectedChains) throws Exception {
    try (Recording r = new Recording()) {
        Map<String, String> p = new HashMap<>(settings);
        p.put(EventNames.OldObjectSample + "#" + Enabled.NAME, "true");
        r.setName("dodo");
        r.setSettings(p);
        r.setToDisk(true);
        r.start();
        clearLeak();
        System.out.println("Recording id: " + r.getId());
        System.out.println("Settings: " + settings.toString());
        System.out.println("Command: JFR.dump " + pathToGcRoots);
        System.out.println("Chains expected: " + expectedChains);
        buildLeak();
        System.gc();
        System.gc();
        File recording = new File("TestJcmdDumpPathToGCRoots" + r.getId() + ".jfr");
        recording.delete();
        JcmdHelper.jcmd("JFR.dump", "name=dodo", pathToGcRoots, "filename=" + recording.getAbsolutePath());
        r.setSettings(Collections.emptyMap());
        List<RecordedEvent> events = RecordingFile.readAllEvents(recording.toPath());
        if (events.isEmpty()) {
            throw new Exception("No events found in recoding");
        }
        boolean chains = hasChains(events);
        if (expectedChains && !chains) {
            System.out.println(events);
            throw new Exception("Expected chains but found none");
        }
        if (!expectedChains && chains) {
            System.out.println(events);
            throw new Exception("Didn't expect chains but found some");
        }
    }
}
 
Example 12
Source File: TestReadTwice.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Throwable {
    Recording r = new Recording();
    r.enable(MyEvent.class).withoutStackTrace();
    r.start();

    // Commit a single event to the recording
    MyEvent event = new MyEvent();
    event.commit();

    r.stop();

    // Dump the recording to a file
    Path path = Files.createTempFile("recording", ".jfr");
    System.out.println("Dumping to " + path);
    r.dump(path);
    r.close();

    // Read all events from the file in one go
    List<RecordedEvent> events = RecordingFile.readAllEvents(path);

    // Read again the same events one by one
    RecordingFile rfile = new RecordingFile(path);
    List<RecordedEvent> events2 = new LinkedList<>();
    while (rfile.hasMoreEvents()) {
        events2.add(rfile.readEvent());
    }

    // Compare sizes
    Asserts.assertEquals(events.size(), events2.size());
    rfile.close();
}
 
Example 13
Source File: TestDumpMultiple.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void verifyRecording(Path path, int... ids) throws Exception {
    Asserts.assertTrue(Files.exists(path), "Recording file does not exist: " + path);
    int countEvent = 0;
    for (RecordedEvent event : RecordingFile.readAllEvents(path)) {
        int id = Events.assertField(event, "id").getValue();
        System.out.printf("Recording '%s' id=%d%n", path, id);
        Asserts.assertTrue(ids.length > countEvent, "Found extra event");
        Events.assertField(event, "id").equal(ids[countEvent]);
        ++countEvent;
    }
    // We expect exactly 4 events in each file. 2 events * 2 chunks
    Asserts.assertEquals(countEvent, ids.length, "Found too few events");
}
 
Example 14
Source File: TestInheritedAnnotations.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws Exception {
    try (Recording r = new Recording()) {
        r.enable(EventNames.ActiveSetting);
        r.start();
        UncleEvent u = new UncleEvent();
        u.commit();
        FatherEvent f = new FatherEvent();
        f.commit();
        SonEvent s = new SonEvent();
        s.commit();
        AuntEvent a = new AuntEvent();
        a.commit();
        CousineEvent c = new CousineEvent();
        c.commit();

        r.stop();
        Path p = Utils.createTempFile("inherited-annotations", ".jfr");
        r.dump(p);
        List<RecordedEvent> events = RecordingFile.readAllEvents(p);
        assertNoGrandFather(events);
        assertUncle(events);
        assertNoFather(events);
        assertNoAunt();
        assertNoCousine(events);
        assertSon(events);
        assertSettings(events);
    }
}
 
Example 15
Source File: JmxHelper.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static List<RecordedEvent> parseStream(long streamId, FlightRecorderMXBean bean) throws Exception {
    File dumpFile = dump(streamId, bean);
    System.out.println("data.length=" + dumpFile.length());
    List<RecordedEvent> events = new ArrayList<>();
    for (RecordedEvent event : RecordingFile.readAllEvents(dumpFile.toPath())) {
        System.out.println("EVENT:" + event);
        events.add(event);
    }
    return events;
}
 
Example 16
Source File: TestInheritedAnnotations.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws Exception {
    try (Recording r = new Recording()) {
        r.enable(EventNames.ActiveSetting);
        r.start();
        UncleEvent u = new UncleEvent();
        u.commit();
        FatherEvent f = new FatherEvent();
        f.commit();
        SonEvent s = new SonEvent();
        s.commit();
        AuntEvent a = new AuntEvent();
        a.commit();
        CousineEvent c = new CousineEvent();
        c.commit();

        r.stop();
        Path p = Files.createTempFile("temp", ".jfr");
        r.dump(p);
        List<RecordedEvent> events = RecordingFile.readAllEvents(p);
        assertNoGrandFather(events);
        assertUncle(events);
        assertNoFather(events);
        assertNoAunt();
        assertNoCousine(events);
        assertSon(events);
        assertSettings(events);
    }
}
 
Example 17
Source File: JmxHelper.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static List<RecordedEvent> parseStream(long streamId, FlightRecorderMXBean bean) throws Exception {
    File dumpFile = dump(streamId, bean);
    System.out.println("data.length=" + dumpFile.length());
    List<RecordedEvent> events = new ArrayList<>();
    for (RecordedEvent event : RecordingFile.readAllEvents(dumpFile.toPath())) {
        System.out.println("EVENT:" + event);
        events.add(event);
    }
    return events;
}
 
Example 18
Source File: TestShutdownEvent.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void runSubtest(int subTestIndex) throws Exception {
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true,
                            "-XX:+LogJFR",
                            "-XX:-CreateMinidumpOnCrash",
                            "-XX:StartFlightRecording=filename=./dumped.jfr,dumponexit=true,settings=default",
                            "jdk.jfr.event.runtime.TestShutdownEvent$TestMain",
                            String.valueOf(subTestIndex));
    OutputAnalyzer output = ProcessTools.executeProcess(pb);
    System.out.println(output.getOutput());
    int exitCode = output.getExitValue();
    System.out.println("Exit code: " + exitCode);

    String recordingName = output.firstMatch("emergency jfr file: (.*.jfr)", 1);
    if (recordingName == null) {
        recordingName = "./dumped.jfr";
    }

    List<RecordedEvent> events = RecordingFile.readAllEvents(Paths.get(recordingName));
    List<RecordedEvent> filteredEvents = events.stream()
        .filter(e -> e.getEventType().getName().equals(EventNames.Shutdown))
        .sorted(Comparator.comparing(RecordedEvent::getStartTime))
        .collect(Collectors.toList());

    Asserts.assertEquals(filteredEvents.size(), 1);
    RecordedEvent event = filteredEvents.get(0);
    subTests[subTestIndex].verifyEvents(event, exitCode);
}
 
Example 19
Source File: TestDestInvalid.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Throwable {
    Recording r = new Recording();
    r.enable(EventNames.OSInformation);
    r.setToDisk(true);

    Asserts.assertNull(r.getDestination(), "dest not null by default");

    // Set destination to empty path (same as curr dir, not a file)
    verifyException(()->{r.setDestination(Paths.get(""));}, "No exception for setDestination(\"\")", IOException.class);
    System.out.println("1 destination: " + r.getDestination());
    Asserts.assertNull(r.getDestination(), "default dest not null after failed setDest");

    // Set dest to a valid path. This should be kept when a new setDest fails.
    Path dest = Paths.get(".", "my.jfr");
    r.setDestination(dest);
    System.out.println("2 destination: " + r.getDestination());
    Asserts.assertEquals(dest, r.getDestination(), "Wrong get/set dest");

    // Null is allowed for setDestination()
    r.setDestination(null);
    System.out.println("3 destination: " + r.getDestination());
    Asserts.assertNull(r.getDestination(), "dest not null after setDest(null)");

    // Reset dest to correct value and make ssure it is not overwritten
    r.setDestination(dest);
    System.out.println("4 destination: " + r.getDestination());
    Asserts.assertEquals(dest, r.getDestination(), "Wrong get/set dest");

    // Set destination to an existing dir. Old dest is saved.
    verifyException(()->{r.setDestination(Paths.get("."));}, "No exception for setDestination(.)", IOException.class);
    System.out.println("5 destination: " + r.getDestination());
    Asserts.assertEquals(dest, r.getDestination(), "Wrong get/set dest");

    // Set destination to a non-existing dir. Old dest is saved.
    verifyException(()->{r.setDestination(Paths.get(".", "missingdir", "my.jfr"));}, "No exception for setDestination(dirNotExists)", IOException.class);
    System.out.println("6 destination: " + r.getDestination());
    Asserts.assertEquals(dest, r.getDestination(), "Wrong get/set dest");

    // Verify that it works with the old setDest value.
    r.start();
    r.stop();
    r.close();
    Asserts.assertTrue(Files.exists(dest), "No recording file: " + dest);
    List<RecordedEvent> events = RecordingFile.readAllEvents(dest);
    Asserts.assertFalse(events.isEmpty(), "No event found");
    System.out.printf("Found event %s in %s%n", events.get(0).getEventType().getName(), dest.toString());
}
 
Example 20
Source File: TestUnsupportedVM.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String... args) throws Exception {
    if (Boolean.getBoolean("prepare-recording")) {
        Recording r = new Recording(Configuration.getConfiguration("default"));
        r.start();
        r.stop();
        r.dump(RECORDING_FILE);
        r.close();
        return;
    }

    System.out.println("jdk.jfr.unsupportedvm=" + System.getProperty("jdk.jfr.unsupportedvm"));
    // Class FlightRecorder
    if (FlightRecorder.isAvailable()) {
        throw new AssertionError("JFR should not be available on an unsupported VM");
    }

    if (FlightRecorder.isInitialized()) {
        throw new AssertionError("JFR should not be initialized on an unsupported VM");
    }

    assertIllegalStateException(() -> FlightRecorder.getFlightRecorder());
    assertSwallow(() -> FlightRecorder.addListener(new FlightRecorderListener() {}));
    assertSwallow(() -> FlightRecorder.removeListener(new FlightRecorderListener() {}));
    assertSwallow(() -> FlightRecorder.register(MyEvent.class));
    assertSwallow(() -> FlightRecorder.unregister(MyEvent.class));
    assertSwallow(() -> FlightRecorder.addPeriodicEvent(MyEvent.class, new Runnable() { public void run() {} }));
    assertSwallow(() -> FlightRecorder.removePeriodicEvent(new Runnable() { public void run() {} }));

    // Class Configuration
    if (!Configuration.getConfigurations().isEmpty()) {
        throw new AssertionError("Configuration files should not exist on an unsupported VM");
    }
    Path jfcFile = Utils.createTempFile("empty", ".jfr");
    assertIOException(() -> Configuration.getConfiguration("default"));
    assertIOException(() -> Configuration.create(jfcFile));
    assertIOException(() -> Configuration.create(new FileReader(jfcFile.toFile())));

    // Class EventType
    assertInternalError(() -> EventType.getEventType(MyEvent.class));

    // Class EventFactory
    assertInternalError(() -> EventFactory.create(new ArrayList<>(), new ArrayList<>()));

    // Create a static event
    MyEvent myEvent = new MyEvent();
    myEvent.begin();
    myEvent.end();
    myEvent.shouldCommit();
    myEvent.commit();

    // Trigger class initialization failure
    for (Class<?> c : APIClasses) {
        assertNoClassInitFailure(c);
    }

    // jdk.jfr.consumer.*
    // Only run this part of tests if we are on VM
    // that can produce a recording file
    if (Files.exists(RECORDING_FILE)) {
        for(RecordedEvent re : RecordingFile.readAllEvents(RECORDING_FILE)) {
            System.out.println(re);
        }
    }
}