diff --git a/src/jdk.jfr/share/classes/jdk/jfr/Recording.java b/src/jdk.jfr/share/classes/jdk/jfr/Recording.java --- a/src/jdk.jfr/share/classes/jdk/jfr/Recording.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/Recording.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2019, 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 @@ -413,6 +413,36 @@ internal.setMaxSize(maxSize); } + /** + * Determines how often events are made available for streaming. + * + * @param interval the interval at which events are made available for streaming. + * + * @throws IllegalArgumentException if {@code interval} is negative + * + * @throws IllegalStateException if the recording is in the {@code CLOSED} state + * + * @since 14 + */ + public void setFlushInterval(Duration interval) { + Objects.nonNull(interval); + if (interval.isNegative()) { + throw new IllegalArgumentException("Stream interval can't be negative"); + } + internal.setFlushInterval(interval); + } + + /** + * Returns how often events are made available for streaming purposes. + * + * @return the flush interval, or {@code null} if no interval has been set + * + * @since 14 + */ + public Duration getFlushInterval() { + return internal.getFlushInterval(); + } + /** * Determines how far back data is kept in the disk repository. *
diff --git a/src/jdk.jfr/share/classes/jdk/jfr/consumer/EventStream.java b/src/jdk.jfr/share/classes/jdk/jfr/consumer/EventStream.java new file mode 100644 --- /dev/null +++ b/src/jdk.jfr/share/classes/jdk/jfr/consumer/EventStream.java @@ -0,0 +1,364 @@ +/* + * Copyright (c) 2019, 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * 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. + */ + +package jdk.jfr.consumer; + +import java.io.IOException; +import java.nio.file.Path; +import java.security.AccessControlContext; +import java.security.AccessController; +import java.time.Duration; +import java.time.Instant; +import java.util.Objects; +import java.util.function.Consumer; + +import jdk.jfr.internal.SecuritySupport; +import jdk.jfr.internal.Utils; +import jdk.jfr.internal.consumer.EventDirectoryStream; +import jdk.jfr.internal.consumer.EventFileStream; +import jdk.jfr.internal.consumer.FileAccess; + +/** + * Represents a stream of events. + *
+ * A stream is a sequence of events and the way to interact with a stream is to + * register actions. The {@code EventStream} interface is not to be implemented + * and future versions of the JDK may prevent this completely. + *
+ * To receive a notification when an event arrives, register an action using the + * {@link #onEvent(Consumer)} method. To filter the stream for an event with a + * specific name, use {@link #onEvent(String, Consumer)} method. + *
+ * By default, the same {@code RecordedEvent} object can be used to + * represent two or more distinct events. That object can be delivered + * multiple times to the same action as well as to other actions. To use an + * event object after the action is completed, the + * {@link #setReuse(boolean)} method should be set to {@code false} so a + * new object is allocated for each event. + *
+ * Events are delivered in batches. To receive a notification when a batch is + * complete, register an action using the {@link #onFlush(Runnable)} method. + * This is an opportunity to aggregate or push data to external systems while + * the Java Virtual Machine (JVM) is preparing the next batch. + *
+ * Events within a batch are sorted chronologically by their end time. + * Well-ordering of events is only maintained for events available to the JVM at + * the point of flush, i.e. for the set of events delivered as a unit in a + * single batch. Events delivered in a batch could therefore be out-of-order + * compared to events delivered in a previous batch, but never out-of-order with + * events within the same batch. If ordering is not a concern, sorting can be + * disabled using the {@link #setOrdered(boolean)} method. + *
+ * To dispatch events to registered actions, the stream must be started. To + * start processing in the current thread, invoke the {@link #start()} method. + * To process actions asynchronously in a separate thread, invoke the + * {@link #startAsync()} method. To await completion of the stream, use the + * awaitTermination {@link #awaitTermination()} or the + * {@link #awaitTermination(Duration)} method. + *
+ * When a stream ends it is automatically closed. To manually stop processing of + * events, close the stream by invoking the {@link #close()} method. A stream + * can also be automatically closed in exceptional circumstances, for example if + * the JVM that is being monitored exits. To receive a notification in any of + * these occasions, use the {@link #onClose(Runnable)} method to register an + * action. + *
+ * If an unexpected exception occurs in an action, it is possible to catch the + * exception in an error handler. An error handler can be registered using the + * {@link #onError(Runnable)} method. If no error handler is registered, the + * default behavior is to print the exception and its backtrace to the standard + * error stream. + *
+ * The following example shows how an {@code EventStream} can be used to listen + * to events on a JVM running Flight Recorder + * + *
+ *
+ * try (var es = EventStream.openRepository()) {
+ * es.onEvent("jdk.CPULoad", event -> {
+ * System.out.println("CPU Load " + event.getEndTime());
+ * System.out.println(" Machine total: " + 100 * event.getFloat("machineTotal") + "%");
+ * System.out.println(" JVM User: " + 100 * event.getFloat("jvmUser") + "%");
+ * System.out.println(" JVM System: " + 100 * event.getFloat("jvmSystem") + "%");
+ * System.out.println();
+ * });
+ * es.onEvent("jdk.GarbageCollection", event -> {
+ * System.out.println("Garbage collection: " + event.getLong("gcId"));
+ * System.out.println(" Cause: " + event.getString("cause"));
+ * System.out.println(" Total pause: " + event.getDuration("sumOfPauses"));
+ * System.out.println(" Longest pause: " + event.getDuration("longestPause"));
+ * System.out.println();
+ * });
+ * es.start();
+ * }
+ *
+ *
+ * + * To start recording together with the stream, see {@link RecordingStream}. + * + * @since 14 + */ +public interface EventStream extends AutoCloseable { + /** + * Creates a stream from the repository of the current Java Virtual Machine + * (JVM). + *
+ * By default, the stream starts with the next event flushed by Flight + * Recorder. + * + * @return an event stream, not {@code null} + * + * @throws IOException if a stream can't be opened, or an I/O error occurs + * when trying to access the repository + * + * @throws SecurityException if a security manager exists and the caller + * does not have + * {@code FlightRecorderPermission("accessFlightRecorder")} + */ + public static EventStream openRepository() throws IOException { + Utils.checkAccessFlightRecorder(); + return new EventDirectoryStream(AccessController.getContext(), null, SecuritySupport.PRIVILIGED, false); + } + + /** + * Creates an event stream from a disk repository. + *
+ * By default, the stream starts with the next event flushed by Flight + * Recorder. + * + * @param directory location of the disk repository, not {@code null} + * + * @return an event stream, not {@code null} + * + * @throws IOException if a stream can't be opened, or an I/O error occurs + * when trying to access the repository + * + * @throws SecurityException if a security manager exists and its + * {@code checkRead} method denies read access to the directory, or + * files in the directory. + */ + public static EventStream openRepository(Path directory) throws IOException { + Objects.nonNull(directory); + AccessControlContext acc = AccessController.getContext(); + return new EventDirectoryStream(acc, directory, FileAccess.UNPRIVILIGED, false); + } + + /** + * Creates an event stream from a file. + *
+ * By default, the stream starts with the first event in the file.
+ *
+ * @param file location of the file, not {@code null}
+ *
+ * @return an event stream, not {@code null}
+ *
+ * @throws IOException if the file can't be opened, or an I/O error occurs
+ * during reading
+ *
+ * @throws SecurityException if a security manager exists and its
+ * {@code checkRead} method denies read access to the file
+ */
+ static EventStream openFile(Path file) throws IOException {
+ return new EventFileStream(AccessController.getContext(), file);
+ }
+
+ /**
+ * Registers an action to perform on all events in the stream.
+ *
+ * @param action an action to perform on each {@code RecordedEvent}, not
+ * {@code null}
+ */
+ void onEvent(Consumer
+ * if an action is not registered, an exception stack trace is printed to
+ * standard error.
+ *
+ * Registering an action overrides the default behavior. If multiple actions
+ * have been registered, they are performed in the order of registration.
+ *
+ * If this method itself throws an exception, resulting behavior is
+ * undefined.
+ *
+ * @param action an action to perform if an exception occurs, not
+ * {@code null}
+ */
+ void onError(Consumer
+ * If the stream is already closed, the action will be performed immediately
+ * in the current thread.
+ *
+ * @param action an action to perform after the stream is closed, not
+ * {@code null}
+ * @see #close()
+ */
+ void onClose(Runnable action);
+
+ /**
+ * Releases all resources associated with this stream.
+ *
+ * Closing a previously closed stream has no effect.
+ */
+ void close();
+
+ /**
+ * Unregisters an action.
+ *
+ * If the action has been registered multiple times, all instances are
+ * unregistered.
+ *
+ * @param action the action to unregister, not {@code null}
+ *
+ * @return {@code true} if the action was unregistered, {@code false}
+ * otherwise
+ *
+ * @see #onEvent(Consumer)
+ * @see #onEvent(String, Consumer)
+ * @see #onFlush(Runnable)
+ * @see #onClose(Runnable)
+ * @see #onError(Consumer)
+ */
+ boolean remove(Object action);
+
+ /**
+ * Specifies that the event object in an {@link #onEvent(Consumer)} action
+ * can be reused.
+ *
+ * If reuse is set to {@code true), an action should not keep a reference
+ * to the event object after the action has completed.
+ *
+ * @param reuse {@code true} if an event object can be reused, {@code false}
+ * otherwise
+ */
+ void setReuse(boolean reuse);
+
+ /**
+ * Specifies that events arrives in chronological order, sorted by the time
+ * they were committed to the stream.
+ *
+ * @param ordered if event objects arrive in chronological order to
+ * {@code #onEvent(Consumer)}
+ */
+ void setOrdered(boolean ordered);
+
+ /**
+ * Specifies the start time of the stream.
+ *
+ * The start time must be set before starting the stream
+ *
+ * @param startTime the start time, not {@code null}
+ *
+ * @throws IllegalStateException if the stream is already started
+ *
+ * @see #start()
+ * @see #startAsync()
+ */
+ void setStartTime(Instant startTime);
+
+ /**
+ * Specifies the end time of the stream.
+ *
+ * The end time must be set before starting the stream.
+ *
+ * At end time, the stream is closed.
+ *
+ * @param endTime the end time, not {@code null}
+ *
+ * @throws IllegalStateException if the stream is already started
+ *
+ * @see #start()
+ * @see #startAsync()
+ */
+ void setEndTime(Instant endTime);
+
+ /**
+ * Start processing of actions.
+ *
+ * Actions are performed in the current thread.
+ *
+ * @throws IllegalStateException if the stream is already started or closed
+ */
+ void start();
+
+ /**
+ * Start asynchronous processing of actions.
+ *
+ * Actions are performed in a single separate thread.
+ *
+ * @throws IllegalStateException if the stream is already started or closed
+ */
+ void startAsync();
+
+ /**
+ * Blocks until all actions are completed, or the stream is closed, or the
+ * timeout occurs, or the current thread is interrupted, whichever happens
+ * first.
+ *
+ * @param timeout the maximum time to wait, not {@code null}
+ *
+ * @throws IllegalArgumentException if timeout is negative
+ * @throws InterruptedException if interrupted while waiting
+ *
+ * @see #start()
+ * @see #startAsync()
+ * @see Thread#interrupt()
+ */
+ void awaitTermination(Duration timeout) throws InterruptedException;
+
+ /**
+ * Blocks until all actions are completed, or the stream is closed, or the
+ * current thread is interrupted, whichever happens first.
+ *
+ * @throws InterruptedException if interrupted while waiting
+ *
+ * @see #start()
+ * @see #startAsync()
+ * @see Thread#interrupt()
+ */
+ void awaitTermination() throws InterruptedException;
+}
diff --git a/src/jdk.jfr/share/classes/jdk/jfr/consumer/RecordingStream.java b/src/jdk.jfr/share/classes/jdk/jfr/consumer/RecordingStream.java
new file mode 100644
--- /dev/null
+++ b/src/jdk.jfr/share/classes/jdk/jfr/consumer/RecordingStream.java
@@ -0,0 +1,362 @@
+/*
+ * Copyright (c) 2019, 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. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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.
+ */
+
+package jdk.jfr.consumer;
+
+import java.io.IOException;
+import java.security.AccessControlContext;
+import java.security.AccessController;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Map;
+import java.util.function.Consumer;
+
+import jdk.jfr.Configuration;
+import jdk.jfr.Event;
+import jdk.jfr.EventSettings;
+import jdk.jfr.EventType;
+import jdk.jfr.Recording;
+import jdk.jfr.internal.PlatformRecording;
+import jdk.jfr.internal.PrivateAccess;
+import jdk.jfr.internal.SecuritySupport;
+import jdk.jfr.internal.Utils;
+import jdk.jfr.internal.consumer.EventDirectoryStream;
+
+/**
+ * A recording stream produces events from the current JVM (Java Virtual
+ * Machine).
+ *
+ * The following example shows how to record events using the default
+ * configuration and print the Garbage Collection, CPU Load and JVM Information
+ * event to standard out.
+ *
+ * The following example shows how to create a recording stream that uses a
+ * predefined configuration.
+ *
+ *
+ * If multiple events have the same name (for example, the same class is
+ * loaded in different class loaders), then all events that match the name
+ * are enabled. To enable a specific class, use the {@link #enable(Class)}
+ * method or a {@code String} representation of the event type ID.
+ *
+ * @param name the settings for the event, not {@code null}
+ *
+ * @return an event setting for further configuration, not {@code null}
+ *
+ * @see EventType
+ */
+ public EventSettings enable(String name) {
+ return recording.enable(name);
+ }
+
+ /**
+ * Replaces all settings for this recording stream.
+ *
+ * The following example records 20 seconds using the "default" configuration
+ * and then changes settings to the "profile" configuration.
+ *
+ *
+ * If multiple events with same name (for example, the same class is loaded
+ * in different class loaders), then all events that match the name are
+ * disabled. To disable a specific class, use the {@link #disable(Class)}
+ * method or a {@code String} representation of the event type ID.
+ *
+ * @param name the settings for the event, not {@code null}
+ *
+ * @return an event setting for further configuration, not {@code null}
+ *
+ */
+ public EventSettings disable(String name) {
+ return recording.disable(name);
+ }
+
+ /**
+ * Disables event.
+ *
+ * @param eventClass the event to enable, not {@code null}
+ *
+ * @throws IllegalArgumentException if {@code eventClass} is an abstract
+ * class or not a subclass of {@link Event}
+ *
+ * @return an event setting for further configuration, not {@code null}
+ *
+ */
+ public EventSettings disable(Class extends Event> eventClass) {
+ return recording.disable(eventClass);
+ }
+
+ /**
+ * Determines how far back data is kept for the stream.
+ *
+ * To control the amount of recording data stored on disk, the maximum
+ * length of time to retain the data can be specified. Data stored on disk
+ * that is older than the specified length of time is removed by the Java
+ * Virtual Machine (JVM).
+ *
+ * If neither maximum limit or the maximum age is set, the size of the
+ * recording may grow indefinitely if events are on
+ *
+ * @param maxAge the length of time that data is kept, or {@code null} if
+ * infinite
+ *
+ * @throws IllegalArgumentException if {@code maxAge} is negative
+ *
+ * @throws IllegalStateException if the recording is in the {@code CLOSED}
+ * state
+ */
+ public void setMaxAge(Duration maxAge) {
+ recording.setMaxAge(maxAge);
+ }
+
+ /**
+ * Determines how much data is kept for the stream.
+ *
+ * To control the amount of recording data that is stored on disk, the
+ * maximum amount of data to retain can be specified. When the maximum limit
+ * is exceeded, the Java Virtual Machine (JVM) removes the oldest chunk to
+ * make room for a more recent chunk.
+ *
+ * If neither maximum limit or the maximum age is set, the size of the
+ * recording may grow indefinitely.
+ *
+ * The size is measured in bytes.
+ *
+ * @param maxSize the amount of data to retain, {@code 0} if infinite
+ *
+ * @throws IllegalArgumentException if {@code maxSize} is negative
+ *
+ * @throws IllegalStateException if the recording is in {@code CLOSED} state
+ */
+ public void setMaxSize(long maxSize) {
+ recording.setMaxSize(maxSize);
+ }
+
+ /**
+ * Determines how often events are made available for streaming.
+ *
+ * @param interval the interval at which events are made available to the
+ * stream, no {@code null}
+ *
+ * @throws IllegalArgumentException if {@code interval} is negative
+ *
+ * @throws IllegalStateException if the stream is closed
+ */
+ public void setFlushInterval(Duration interval) {
+ recording.setFlushInterval(interval);
+ }
+
+ @Override
+ public void setReuse(boolean reuse) {
+ directoryStream.setReuse(reuse);
+ }
+
+ @Override
+ public void setOrdered(boolean ordered) {
+ directoryStream.setOrdered(ordered);
+ }
+
+ @Override
+ public void setStartTime(Instant startTime) {
+ directoryStream.setStartTime(startTime);
+ }
+
+ @Override
+ public void setEndTime(Instant endTime) {
+ directoryStream.setStartTime(endTime);
+ }
+
+ @Override
+ public void onEvent(String eventName, Consumer
+ *
+ *
+ * @since 14
+ */
+public final class RecordingStream implements AutoCloseable, EventStream {
+
+ private final Recording recording;
+ private final EventDirectoryStream directoryStream;
+
+ /**
+ * Creates an event stream for the current JVM (Java Virtual Machine).
+ *
+ * @throws IllegalStateException if Flight Recorder can't be created (for
+ * example, if the Java Virtual Machine (JVM) lacks Flight Recorder
+ * support, or if the file repository can't be created or accessed)
+ *
+ * @throws SecurityException if a security manager exists and the caller
+ * does not have
+ * {@code FlightRecorderPermission("accessFlightRecorder")}
+ */
+ public RecordingStream() {
+ Utils.checkAccessFlightRecorder();
+ AccessControlContext acc = AccessController.getContext();
+ this.recording = new Recording();
+ this.recording.setFlushInterval(Duration.ofMillis(1000));
+ try {
+ this.directoryStream = new EventDirectoryStream(acc, null, SecuritySupport.PRIVILIGED, true);
+ } catch (IOException ioe) {
+ this.recording.close();
+ throw new IllegalStateException(ioe.getMessage());
+ }
+ }
+
+ /**
+ * Creates a recording stream using settings from a configuration.
+ *
+ * Configuration c = Configuration.getConfiguration("default");
+ * try (var rs = new RecordingStream(c)) {
+ * rs.onEvent("jdk.GarbageCollection", System.out::println);
+ * rs.onEvent("jdk.CPULoad", System.out::println);
+ * rs.onEvent("jdk.JVMInformation", System.out::println);
+ * rs.start();
+ * }
+ * }
+ *
+ *
+ *
+ *
+ * @param configuration configuration that contains the settings to use,
+ * not {@code null}
+ *
+ * @throws IllegalStateException if Flight Recorder can't be created (for
+ * example, if the Java Virtual Machine (JVM) lacks Flight Recorder
+ * support, or if the file repository can't be created or accessed)
+ *
+ * @throws SecurityException if a security manager is used and
+ * FlightRecorderPermission "accessFlightRecorder" is not set.
+ *
+ * @see Configuration
+ */
+ public RecordingStream(Configuration configuration) {
+ this();
+ recording.setSettings(configuration.getSettings());
+ }
+
+ /**
+ * Enables the event with the specified name.
+ *
+ * var c = Configuration.getConfiguration("default");
+ * try (var rs = new RecordingStream(c)) {
+ * rs.onEvent(System.out::println);
+ * rs.start();
+ * }
+ *
+ *
+ *
+ *
+ * @param settings the settings to set, not {@code null}
+ *
+ * @see Recording#setSettings(Map)
+ */
+ public void setSettings(Map
+ * Configuration defaultConfiguration = Configuration.getConfiguration("default");
+ * Configuration profileConfiguration = Configuration.getConfiguration("profile");
+ * try (var rs = new RecordingStream(defaultConfiguration) {
+ * rs.onEvent(System.out::println);
+ * rs.startAsync();
+ * Thread.sleep(20_000);
+ * rs.setSettings(profileConfiguration.getSettings());
+ * Thread.sleep(20_000);
+ * }
+ *
+ *