1 /*
   2  * Copyright (c) 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.api.consumer;
  27 
  28 import java.io.FileNotFoundException;
  29 import java.io.FileWriter;
  30 import java.io.IOException;
  31 import java.io.RandomAccessFile;
  32 import java.nio.file.Files;
  33 import java.nio.file.Path;
  34 import java.nio.file.Paths;
  35 import java.util.Arrays;
  36 import java.util.HashSet;
  37 import java.util.List;
  38 import java.util.StringJoiner;
  39 
  40 
  41 import jdk.jfr.Event;
  42 import jdk.jfr.EventType;
  43 import jdk.jfr.FlightRecorder;
  44 import jdk.jfr.Name;
  45 import jdk.jfr.Recording;
  46 import jdk.jfr.Registered;
  47 import jdk.jfr.consumer.RecordedEvent;
  48 import jdk.jfr.consumer.RecordingFile;
  49 import jdk.test.lib.Asserts;
  50 import jdk.test.lib.Utils;
  51 
  52 /*
  53  * @test
  54  * @summary Verifies that all methods in RecordingFIle are working
  55  * @key jfr
  56  * @library /test/lib
  57  * @run main/othervm jdk.jfr.api.consumer.TestRecordingFile
  58  */
  59 public class TestRecordingFile {
  60 
  61     static class TestEvent1 extends Event {
  62     }
  63 
  64     static class TestEvent2 extends Event {
  65     }
  66 
  67     static class TestEvent3 extends Event {
  68     }
  69 
  70     private static String TEST_CLASS_BASE = "TestRecordingFile$TestEvent";
  71     private final static int EVENT_COUNT = 3;
  72     private final static int HEADER_SIZE = 68;
  73     private final static long METADATA_OFFSET = 24;
  74 
  75     public static void main(String[] args) throws Throwable {
  76 
  77         // create some recording data
  78         Recording r = new Recording();
  79         r.enable(TestEvent1.class).withoutStackTrace();
  80         r.enable(TestEvent2.class).withoutStackTrace();
  81         r.enable(TestEvent3.class).withoutStackTrace();
  82         r.start();
  83         TestEvent1 t1 = new TestEvent1();
  84         t1.commit();
  85         TestEvent2 t2 = new TestEvent2();
  86         t2.commit();
  87         TestEvent3 t3 = new TestEvent3();
  88         t3.commit();
  89         r.stop();
  90         Path valid = Utils.createTempFile("three-event-recording", ".jfr");
  91         r.dump(valid);
  92         r.close();
  93 
  94         Path brokenWithZeros = createBrokenWIthZeros(valid);
  95         Path brokenMetadata = createBrokenMetadata(valid);
  96         // prepare event sets
  97         testNewRecordingFile(valid, brokenWithZeros);
  98         testIterate(valid, brokenWithZeros);
  99         testReadAllEvents(valid, brokenWithZeros);
 100         testReadEventTypes(valid, brokenMetadata);
 101         testClose(valid);
 102         testReadEventTypesMultiChunk();
 103         testReadEventTypeWithUnregistration(false, false);
 104         testReadEventTypeWithUnregistration(false, true);
 105         testReadEventTypeWithUnregistration(true, false);
 106         testReadEventTypeWithUnregistration(true, true);
 107     }
 108 
 109     private static void testReadEventTypeWithUnregistration(boolean disk, boolean background) throws Exception {
 110         FlightRecorder.register(Event1.class);
 111         FlightRecorder.register(Event2.class);
 112         FlightRecorder.register(Event3.class);
 113         Recording backgrundRecording = new Recording();
 114         if (disk) {
 115             backgrundRecording.setToDisk(disk);
 116         }
 117         if (background) {
 118             backgrundRecording.start();
 119         }
 120         recordAndVerify(disk, background,new int[] {1,2, 3}, new int[] {});
 121         FlightRecorder.unregister(Event2.class);
 122         recordAndVerify(disk, background,  new int[] {1, 3}, new int[] {2});
 123         FlightRecorder.unregister(Event1.class);
 124         FlightRecorder.register(Event2.class);
 125         recordAndVerify(disk,background, new int[] {2, 3}, new int[] {1});
 126         FlightRecorder.unregister(Event3.class);
 127         FlightRecorder.register(Event3.class);
 128         FlightRecorder.unregister(Event2.class);
 129         FlightRecorder.unregister(Event3.class);
 130         FlightRecorder.register(Event1.class);
 131         FlightRecorder.unregister(Event1.class);
 132         FlightRecorder.register(Event1.class);
 133         FlightRecorder.register(Event2.class);
 134         recordAndVerify(disk, background,new int[] {1, 2}, new int[] {3});
 135         if (background) {
 136             backgrundRecording.close();
 137         }
 138     }
 139 
 140     private static void recordAndVerify(boolean disk, boolean background,  int[] shouldExist, int[] shouldNotExist) throws Exception {
 141         StringJoiner sb  = new StringJoiner("-");
 142         for (int i = 0; i <shouldExist.length; i++) {
 143             sb.add(Integer.toString(shouldExist[i]));
 144         }
 145         System.out.println("Verifying recordings: disk=" + disk + " background=" + background);
 146         System.out.println("Should exist: " + Arrays.toString(shouldExist));
 147         System.out.println("Should not exist: " + Arrays.toString(shouldNotExist));
 148 
 149         Path p = Utils.createTempFile(sb.toString(), ".jfr");
 150         System.out.println("Filename: " + p);
 151         try (Recording r = new Recording()) {
 152             r.start();
 153             r.stop();
 154             r.dump(p);
 155             try (RecordingFile f = new RecordingFile(p)) {
 156                 List<EventType> types = f.readEventTypes();
 157                 for (int i = 0; i< shouldExist.length; i++) {
 158                     assertHasEventType(types, "Event" + shouldExist[i]);
 159                 }
 160                 for (int i = 0; i< shouldNotExist.length; i++) {
 161                     assertMissingEventType(types, "Event" + shouldNotExist[i]);
 162                 }
 163             }
 164         }
 165         System.out.println();
 166         System.out.println();
 167     }
 168 
 169     @Registered(false)
 170     @Name("Event1")
 171     private static class Event1 extends Event {
 172     }
 173     @Registered(false)
 174     @Name("Event2")
 175     private static class Event2 extends Event {
 176     }
 177     @Registered(false)
 178     @Name("Event3")
 179     private static class Event3 extends Event {
 180     }
 181 
 182     private static void testReadEventTypesMultiChunk() throws Exception {
 183 
 184         Path twoEventTypes = Utils.createTempFile("two-event-types", ".jfr");
 185         Path threeEventTypes = Utils.createTempFile("three-event-types", ".jfr");
 186        try (Recording r1 = new Recording()) {
 187            r1.start();
 188            FlightRecorder.register(Event1.class);
 189            try (Recording r2 = new Recording()) {
 190                r2.start();
 191                FlightRecorder.register(Event2.class);
 192 
 193                // Ensure that metadata are written twice.
 194                try (Recording rotator = new Recording()) {
 195                    rotator.start();
 196                    rotator.stop();
 197                }
 198                r2.stop();
 199                r2.dump(twoEventTypes);;
 200            }
 201            FlightRecorder.register(Event3.class);
 202            r1.stop();
 203            r1.dump(threeEventTypes);;
 204        }
 205        try (RecordingFile f = new RecordingFile(twoEventTypes)) {
 206            List<EventType> types = f.readEventTypes();
 207            assertUniqueEventTypes(types);
 208            assertHasEventType(types, "Event1");
 209            assertHasEventType(types, "Event2");
 210            assertMissingEventType(types, "Event3");
 211        }
 212        try (RecordingFile f = new RecordingFile(twoEventTypes)) {
 213            List<EventType> types = f.readEventTypes();
 214            assertUniqueEventTypes(types);
 215            assertHasEventType(types, "Event1");
 216            assertHasEventType(types, "Event2");
 217            assertMissingEventType(types, "Event3");
 218        }
 219 
 220     }
 221 
 222     private static void assertMissingEventType(List<EventType> types,String name) throws Exception {
 223         EventType type = findEventType(types, name);
 224         if (type != null) {
 225             throw new Exception("Found unexpected event type " + name);
 226         }
 227     }
 228 
 229     private static void assertHasEventType(List<EventType> types,String name) throws Exception {
 230         EventType type = findEventType(types, name);
 231         if (type == null) {
 232             throw new Exception("Missing event type " + name);
 233         }
 234     }
 235 
 236     private static EventType findEventType(List<EventType> types, String name) {
 237         for (EventType t : types) {
 238             if (t.getName().equals(name)) {
 239                 return t;
 240             }
 241         }
 242         return null;
 243     }
 244 
 245     private static void assertUniqueEventTypes(List<EventType> types) {
 246         HashSet<Long> ids = new HashSet<>();
 247         for (EventType type : types) {
 248             ids.add(type.getId());
 249         }
 250         Asserts.assertEquals(types.size(), ids.size(), "Event types repeated. " + types);
 251     }
 252 
 253     private static Path createBrokenWIthZeros(Path valid) throws Exception {
 254         try {
 255             Path broken = Utils.createTempFile("broken-events", ".jfr");
 256             Files.delete(broken);
 257             Files.copy(valid, broken);
 258             RandomAccessFile raf = new RandomAccessFile(broken.toFile(), "rw");
 259             raf.seek(HEADER_SIZE);
 260             int size = (int) Files.size(broken);
 261             byte[] ones = new byte[size - HEADER_SIZE];
 262             for (int i = 0; i < ones.length; i++) {
 263                 ones[i] = (byte) 0xFF;
 264             }
 265             raf.write(ones, 0, ones.length);
 266             raf.close();
 267             return broken;
 268         } catch (IOException ioe) {
 269             throw new Exception("Could not produce a broken file " + valid, ioe);
 270         }
 271     }
 272 
 273     private static Path createBrokenMetadata(Path valid) throws Exception {
 274         try {
 275             Path broken = Utils.createTempFile("broken-metadata", ".jfr");
 276             Files.delete(broken);
 277             Files.copy(valid, broken);
 278             RandomAccessFile raf = new RandomAccessFile(broken.toFile(), "rw");
 279             raf.seek(METADATA_OFFSET);
 280             long metadataOffset = raf.readLong();
 281             raf.seek(metadataOffset);
 282             raf.writeLong(Long.MAX_VALUE);
 283             raf.writeLong(Long.MAX_VALUE);
 284             raf.close();
 285             return broken;
 286         } catch (IOException ioe) {
 287             throw new Exception("Could not produce a broken EventSet from file " + valid, ioe);
 288         }
 289     }
 290 
 291     private static void testReadEventTypes(Path valid, Path broken) throws Exception {
 292         try (RecordingFile validFile = new RecordingFile(valid)) {
 293             List<EventType> types = validFile.readEventTypes();
 294             if (types.size() < EVENT_COUNT) {
 295                 throw new Exception("Expected at least " + EVENT_COUNT + " event type but got " + types.toString());
 296             }
 297             int counter = 0;
 298             for (Class<?> testClass : Arrays.asList(TestEvent1.class, TestEvent2.class, TestEvent3.class)) {
 299                 for (EventType t : types) {
 300                     if (t.getName().equals(testClass.getName())) {
 301                         counter++;
 302                     }
 303                 }
 304             }
 305             if (counter != 3) {
 306                 throw new Exception("Returned incorrect event types");
 307             }
 308         }
 309         try (RecordingFile brokenFile = new RecordingFile(broken)) {
 310             brokenFile.readEventTypes();
 311             throw new Exception("Expected IOException when getting Event Types from broken recording");
 312         } catch (IOException ise) {
 313             // OK
 314         }
 315     }
 316 
 317     private static void testNewRecordingFile(Path valid, Path broken) throws Exception {
 318         try (RecordingFile r = new RecordingFile(null)) {
 319             throw new Exception("Expected NullPointerException");
 320         } catch (NullPointerException npe) {
 321             // OK
 322         }
 323         try (RecordingFile r = new RecordingFile(Paths.get("hjhjsdfhkjshdfkj.jfr"))) {
 324             throw new Exception("Expected FileNotFoundException");
 325         } catch (FileNotFoundException npe) {
 326             // OK
 327         }
 328         Path testFile = Utils.createTempFile("test-empty-file", ".jfr");
 329         try (RecordingFile r = new RecordingFile(testFile)) {
 330             throw new Exception("Expected IOException if file is empty");
 331         } catch (IOException e) {
 332             // OK
 333         }
 334         FileWriter fr = new FileWriter(testFile.toFile());
 335         fr.write("whatever");
 336         fr.close();
 337         try (RecordingFile r = new RecordingFile(Paths.get("hjhjsdfhkjshdfkj.jfr"))) {
 338             throw new Exception("Expected IOException if magic is incorrect");
 339         } catch (IOException e) {
 340             // OK
 341         }
 342 
 343         try (RecordingFile r = new RecordingFile(valid)) {
 344         }
 345     }
 346 
 347     private static void testClose(Path valid) throws Exception {
 348         RecordingFile f = new RecordingFile(valid);
 349         f.close();
 350 
 351         try {
 352             f.readEvent();
 353             throw new Exception("Should not be able to read event from closed recording");
 354         } catch (IOException e) {
 355             if (!e.getMessage().equals("Stream Closed")) {
 356                 throw new Exception("Expected 'Stream Closed' in exception message for a closed stream. Got '" + e.getMessage() +"'.");
 357             }
 358             // OK
 359         }
 360         try {
 361             f.readEventTypes();
 362             throw new Exception("Should not be able to read event from closed recording");
 363         } catch (IOException e) {
 364             if (!e.getMessage().equals("Stream Closed")) {
 365                 throw new Exception("Expected 'Stream Closed' in exception message for a closed stream. Got '" + e.getMessage() +"'.");
 366             }
 367             // OK
 368         }
 369         // close twice
 370         f.close();
 371     }
 372 
 373     private static void testIterate(Path valid, Path broken) throws Exception {
 374         try (RecordingFile validFile = new RecordingFile(valid)) {
 375             for (int i = 0; i < EVENT_COUNT; i++) {
 376                 if (!validFile.hasMoreEvents()) {
 377                     throw new Exception("Not all events available");
 378                 }
 379                 RecordedEvent r = validFile.readEvent();
 380                 if (r == null) {
 381                     throw new Exception("Missing event");
 382                 }
 383                 if (!r.getEventType().getName().contains(TEST_CLASS_BASE)) {
 384                     throw new Exception("Incorrect event in recording file " + r);
 385                 }
 386             }
 387             if (validFile.hasMoreEvents()) {
 388                 throw new Exception("Should not be more than " + EVENT_COUNT + " in recording");
 389             }
 390         }
 391         try (RecordingFile brokenFile = new RecordingFile(broken)) {
 392             brokenFile.readEvent();
 393             throw new Exception("Expected IOException for broken recording");
 394         } catch (IOException ise) {
 395             // OK
 396         }
 397     }
 398 
 399     private static void testReadAllEvents(Path valid, Path broken) throws Exception {
 400         try {
 401             RecordingFile.readAllEvents(broken);
 402             throw new Exception("Expected IOException when reading all events for broken recording");
 403         } catch (IOException ioe) {
 404             // OK as expected
 405         }
 406     }
 407 }