1 /*
   2  * Copyright (c) 2016, 2019, 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.consumer;
  27 
  28 import java.io.Closeable;
  29 import java.io.EOFException;
  30 import java.io.File;
  31 import java.io.IOException;
  32 import java.nio.file.NoSuchFileException;
  33 import java.nio.file.Path;
  34 import java.util.ArrayList;
  35 import java.util.Collections;
  36 import java.util.HashSet;
  37 import java.util.List;
  38 
  39 import jdk.jfr.EventType;
  40 import jdk.jfr.internal.MetadataDescriptor;
  41 import jdk.jfr.internal.Type;
  42 import jdk.jfr.internal.consumer.ChunkHeader;
  43 import jdk.jfr.internal.consumer.RecordingInput;
  44 import jdk.jfr.internal.consumer.RecordingInternals;
  45 
  46 /**
  47  * A recording file.
  48  * <p>
  49  * The following example shows how read and print all events in a recording file.
  50  *
  51  * <pre>
  52  * <code>
  53  * try (RecordingFile recordingFile = new RecordingFile(Paths.get("recording.jfr"))) {
  54  *   while (recordingFile.hasMoreEvents()) {
  55  *     RecordedEvent event = recordingFile.readEvent();
  56  *     System.out.println(event);
  57  *   }
  58  * }
  59  * </code>
  60  * </pre>
  61  *
  62  * @since 8
  63  */
  64 public final class RecordingFile implements Closeable {
  65     static{
  66         RecordingInternals.INSTANCE = new RecordingInternals() {
  67             public List<Type> readTypes(RecordingFile file) throws IOException {
  68                 return file.readTypes();
  69             }
  70 
  71             public boolean isLastEventInChunk(RecordingFile file) {
  72                 return file.isLastEventInChunk;
  73             }
  74 
  75             @Override
  76             public Object getOffsetDataTime(RecordedObject event, String name) {
  77                 return event.getOffsetDateTime(name);
  78             }
  79 
  80             @Override
  81             public void sort(List<RecordedEvent> events) {
  82                Collections.sort(events, (e1, e2) -> Long.compare(e1.endTime, e2.endTime));
  83             }
  84         };
  85     }
  86 
  87     private boolean isLastEventInChunk;
  88     private final File file;
  89     private RecordingInput input;
  90     private ChunkParser chunkParser;
  91     private RecordedEvent nextEvent;
  92     private boolean eof;
  93 
  94     /**
  95      * Creates a recording file.
  96      *
  97      * @param file the path of the file to open, not {@code null}
  98      * @throws IOException if it's not a valid recording file, or an I/O error
  99      *         occurred
 100      * @throws NoSuchFileException if the {@code file} can't be located
 101      *
 102      * @throws SecurityException if a security manager exists and its
 103      *         {@code checkRead} method denies read access to the file.
 104      */
 105     public RecordingFile(Path file) throws IOException {
 106         this.file = file.toFile();
 107         this.input = new RecordingInput(this.file);
 108         findNext();
 109     }
 110 
 111     /**
 112      * Reads the next event in the recording.
 113      *
 114      * @return the next event, not {@code null}
 115      *
 116      * @throws EOFException if no more events exist in the recording file
 117      * @throws IOException if an I/O error occurs.
 118      *
 119      * @see #hasMoreEvents()
 120      */
 121     public RecordedEvent readEvent() throws IOException {
 122         if (eof) {
 123             ensureOpen();
 124             throw new EOFException();
 125         }
 126         isLastEventInChunk = false;
 127         RecordedEvent event = nextEvent;
 128         nextEvent = chunkParser.readEvent();
 129         if (nextEvent == null) {
 130             isLastEventInChunk = true;
 131             findNext();
 132         }
 133         return event;
 134     }
 135 
 136     /**
 137      * Returns {@code true} if unread events exist in the recording file,
 138      * {@code false} otherwise.
 139      *
 140      * @return {@code true} if unread events exist in the recording, {@code false}
 141      *         otherwise.
 142      */
 143     public boolean hasMoreEvents() {
 144         return !eof;
 145     }
 146 
 147     /**
 148      * Returns a list of all event types in this recording.
 149      *
 150      * @return a list of event types, not {@code null}
 151      * @throws IOException if an I/O error occurred while reading from the file
 152      *
 153      * @see #hasMoreEvents()
 154      */
 155     public List<EventType> readEventTypes() throws IOException {
 156         ensureOpen();
 157         List<EventType> types = new ArrayList<>();
 158         HashSet<Long> foundIds = new HashSet<>();
 159         try (RecordingInput ri = new RecordingInput(file)) {
 160             ChunkHeader ch = new ChunkHeader(ri);
 161             aggregateEventTypeForChunk(ch, types, foundIds);
 162             while (!ch.isLastChunk()) {
 163                 ch = ch.nextHeader();
 164                 aggregateEventTypeForChunk(ch, types, foundIds);
 165             }
 166         }
 167         return types;
 168     }
 169 
 170     List<Type> readTypes() throws IOException  {
 171         ensureOpen();
 172         List<Type> types = new ArrayList<>();
 173         HashSet<Long> foundIds = new HashSet<>();
 174         try (RecordingInput ri = new RecordingInput(file)) {
 175             ChunkHeader ch = new ChunkHeader(ri);
 176             aggregateTypeForChunk(ch, types, foundIds);
 177             while (!ch.isLastChunk()) {
 178                 ch = ch.nextHeader();
 179                 aggregateTypeForChunk(ch, types, foundIds);
 180             }
 181         }
 182         return types;
 183     }
 184 
 185     private void aggregateTypeForChunk(ChunkHeader ch, List<Type> types, HashSet<Long> foundIds) throws IOException {
 186         MetadataDescriptor m = ch.readMetadata();
 187         for (Type t : m.getTypes()) {
 188             if (!foundIds.contains(t.getId())) {
 189                 types.add(t);
 190                 foundIds.add(t.getId());
 191             }
 192         }
 193     }
 194 
 195     private static void aggregateEventTypeForChunk(ChunkHeader ch, List<EventType> types, HashSet<Long> foundIds) throws IOException {
 196         MetadataDescriptor m = ch.readMetadata();
 197         for (EventType t : m.getEventTypes()) {
 198             if (!foundIds.contains(t.getId())) {
 199                 types.add(t);
 200                 foundIds.add(t.getId());
 201             }
 202         }
 203     }
 204 
 205     /**
 206      * Closes this recording file and releases any system resources that are
 207      * associated with it.
 208      *
 209      * @throws IOException if an I/O error occurred
 210      */
 211     public void close() throws IOException {
 212         if (input != null) {
 213             eof = true;
 214             input.close();
 215             chunkParser = null;
 216             input = null;
 217             nextEvent = null;
 218         }
 219     }
 220 
 221     /**
 222      * Returns a list of all events in a file.
 223      * <p>
 224      * This method is intended for simple cases where it's convenient to read all
 225      * events in a single operation. It isn't intended for reading large files.
 226      *
 227      * @param path the path to the file, not {@code null}
 228      *
 229      * @return the events from the file as a {@code List} object; whether the
 230      *         {@code List} is modifiable or not is implementation dependent and
 231      *         therefore not specified, not {@code null}
 232      *
 233      * @throws IOException if an I/O error occurred, it's not a Flight Recorder
 234      *         file or a version of a JFR file that can't be parsed
 235      *
 236      * @throws SecurityException if a security manager exists and its
 237      *         {@code checkRead} method denies read access to the file.
 238      */
 239     public static List<RecordedEvent> readAllEvents(Path path) throws IOException {
 240         try (RecordingFile r = new RecordingFile(path)) {
 241             List<RecordedEvent> list = new ArrayList<>();
 242             while (r.hasMoreEvents()) {
 243                 list.add(r.readEvent());
 244             }
 245             return list;
 246         }
 247     }
 248 
 249     // either sets next to an event or sets eof to true
 250     private void findNext() throws IOException {
 251         while (nextEvent == null) {
 252             if (chunkParser == null) {
 253                 chunkParser = new ChunkParser(input);
 254             } else if (!chunkParser.isLastChunk()) {
 255                 chunkParser = chunkParser.nextChunkParser();
 256             } else {
 257                 eof = true;
 258                 return;
 259             }
 260             nextEvent = chunkParser.readEvent();
 261         }
 262     }
 263 
 264     private void ensureOpen() throws IOException {
 265         if (input == null) {
 266             throw new IOException("Stream Closed");
 267         }
 268     }
 269 }