1 /*
  2  * Copyright (c) 2018, 2020, 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.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  */
 23 package jdk.jfr.event.metadata;
 24 
 25 import java.io.IOException;
 26 import java.lang.reflect.Field;
 27 import java.nio.file.Files;
 28 import java.nio.file.Path;
 29 import java.nio.file.Paths;
 30 import java.util.Arrays;
 31 import java.util.HashSet;
 32 import java.util.List;
 33 import java.util.Set;
 34 import java.util.stream.Collectors;
 35 import java.util.stream.Stream;
 36 
 37 import jdk.jfr.EventType;
 38 import jdk.jfr.Experimental;
 39 import jdk.jfr.FlightRecorder;
 40 import jdk.test.lib.Utils;
 41 import jdk.test.lib.jfr.EventNames;
 42 
 43 /**
 44  * @test Check for JFR events not covered by tests
 45  * @key jfr
 46  * @requires vm.hasJFR
 47  * @library /test/lib /test/jdk
 48  * @run main jdk.jfr.event.metadata.TestLookForUntestedEvents
 49  */
 50 public class TestLookForUntestedEvents {
 51     private static final Path jfrTestRoot = Paths.get(Utils.TEST_SRC).getParent().getParent();
 52     private static final String MSG_SEPARATOR = "==========================";
 53     private static Set<String> jfrEventTypes = new HashSet<>();
 54 
 55     private static final Set<String> hardToTestEvents = new HashSet<>(
 56         Arrays.asList(
 57             "DataLoss", "IntFlag", "ReservedStackActivation",
 58             "DoubleFlag", "UnsignedLongFlagChanged", "IntFlagChanged",
 59             "UnsignedIntFlag", "UnsignedIntFlagChanged", "DoubleFlagChanged")
 60     );
 61 
 62     // GC uses specific framework to test the events, instead of using event names literally.
 63     // GC tests were inspected, as well as runtime output of GC tests.
 64     // The following events below are know to be covered based on that inspection.
 65     private static final Set<String> coveredGcEvents = new HashSet<>(
 66         Arrays.asList(
 67             "MetaspaceGCThreshold", "MetaspaceAllocationFailure", "MetaspaceOOM",
 68             "MetaspaceChunkFreeListSummary", "G1HeapSummary", "ParallelOldGarbageCollection",
 69             "OldGarbageCollection", "G1GarbageCollection", "GCPhasePause",
 70             "GCPhasePauseLevel1", "GCPhasePauseLevel2", "GCPhasePauseLevel3",
 71             "GCPhasePauseLevel4")
 72     );
 73 
 74     // Container events are tested in hotspot/jtreg/containers/docker/TestJFREvents.java
 75     private static final Set<String> coveredContainerEvents = new HashSet<>(
 76         Arrays.asList(
 77             "ContainerConfiguration", "ContainerCPUUsage", "ContainerCPUThrottling",
 78             "ContainerMemoryUsage", "ContainerIOUsage")
 79     );
 80 
 81     // This is a "known failure list" for this test.
 82     // NOTE: if the event is not covered, a bug should be open, and bug number
 83     // noted in the comments for this set.
 84     private static final Set<String> knownNotCoveredEvents = new HashSet<>(
 85     );
 86 
 87     // Experimental events
 88     private static final Set<String> experimentalEvents = new HashSet<>(
 89         Arrays.asList(
 90             "Flush", "SyncOnValueBasedClass")
 91     );
 92 
 93 
 94     public static void main(String[] args) throws Exception {
 95         for (EventType type : FlightRecorder.getFlightRecorder().getEventTypes()) {
 96             if (type.getAnnotation(Experimental.class) == null) {
 97                 jfrEventTypes.add(type.getName().replace("jdk.", ""));
 98             }
 99         }
100 
101         checkEventNamesClass();
102         lookForEventsNotCoveredByTests();
103     }
104 
105     // Look thru JFR tests to make sure JFR events are referenced in the tests
106     private static void lookForEventsNotCoveredByTests() throws Exception {
107         List<Path> paths = Files.walk(jfrTestRoot)
108             .filter(Files::isRegularFile)
109             .filter(path -> isJavaFile(path))
110             .collect(Collectors.toList());
111 
112         Set<String> eventsNotCoveredByTest = new HashSet<>(jfrEventTypes);
113         for (String event : jfrEventTypes) {
114             for (Path p : paths) {
115                 if (findStringInFile(p, event)) {
116                     eventsNotCoveredByTest.remove(event);
117                     break;
118                 }
119             }
120         }
121 
122         // Account for hard-to-test, experimental and GC tested events
123         eventsNotCoveredByTest.removeAll(hardToTestEvents);
124         eventsNotCoveredByTest.removeAll(coveredGcEvents);
125         eventsNotCoveredByTest.removeAll(coveredContainerEvents);
126         eventsNotCoveredByTest.removeAll(knownNotCoveredEvents);
127 
128         if (!eventsNotCoveredByTest.isEmpty()) {
129             print(MSG_SEPARATOR + " Events not covered by test");
130             for (String event: eventsNotCoveredByTest) {
131                 print(event);
132             }
133             print(MSG_SEPARATOR);
134             throw new RuntimeException("Found JFR events not covered by tests");
135         }
136     }
137 
138     // Make sure all the JFR events are accounted for in jdk.test.lib.jfr.EventNames
139     private static void checkEventNamesClass() throws Exception {
140         // jdk.test.lib.jfr.EventNames
141         Set<String> eventsFromEventNamesClass = new HashSet<>();
142         for (Field f : EventNames.class.getFields()) {
143             String name = f.getName();
144             if (!name.equals("PREFIX")) {
145                 String eventName = (String) f.get(null);
146                 eventName = eventName.replace(EventNames.PREFIX, "");
147                 eventsFromEventNamesClass.add(eventName);
148             }
149         }
150 
151         // remove experimental events from eventsFromEventNamesClass since jfrEventTypes
152         // excludes experimental events
153         eventsFromEventNamesClass.removeAll(experimentalEvents);
154 
155         if (!jfrEventTypes.equals(eventsFromEventNamesClass)) {
156             String exceptionMsg = "Events declared in jdk.test.lib.jfr.EventNames differ " +
157                          "from events returned by FlightRecorder.getEventTypes()";
158             print(MSG_SEPARATOR);
159             print(exceptionMsg);
160             print("");
161             printSetDiff(jfrEventTypes, eventsFromEventNamesClass,
162                         "jfrEventTypes", "eventsFromEventNamesClass");
163             print("");
164 
165             print("This could be because:");
166             print("1) You forgot to write a unit test. Please do so in test/jdk/jdk/jfr/event/");
167             print("2) You wrote a unit test, but you didn't reference the event in");
168             print("   test/lib/jdk/test/lib/jfr/EventNames.java. ");
169             print("3) It is not feasible to test the event, not even a sanity test. ");
170             print("   Add the event name to test/lib/jdk/test/lib/jfr/EventNames.java ");
171             print("   and a short comment why it can't be tested");
172             print("4) The event is experimental. Please add 'experimental=\"true\"' to <Event> ");
173             print("   element in metadata.xml if it is a native event, or @Experimental if it is a ");
174             print("   Java event. The event will now not show up in JMC");
175             System.out.println(MSG_SEPARATOR);
176             throw new RuntimeException(exceptionMsg);
177         }
178     }
179 
180     // ================ Helper methods
181     private static boolean isJavaFile(Path p) {
182         String fileName = p.getFileName().toString();
183         int i = fileName.lastIndexOf('.');
184         if ( (i < 0) || (i > fileName.length()) ) {
185             return false;
186         }
187         return "java".equals(fileName.substring(i+1));
188     }
189 
190     private static boolean findStringInFile(Path p, String searchTerm) throws IOException {
191         long c = 0;
192         try (Stream<String> stream = Files.lines(p)) {
193             c = stream
194                 .filter(line -> line.contains(searchTerm))
195                 .count();
196         }
197         return (c != 0);
198     }
199 
200     private static void printSetDiff(Set<String> a, Set<String> b,
201         String setAName, String setBName) {
202         if (a.size() > b.size()) {
203             a.removeAll(b);
204             System.out.printf("Set %s has more elements than set %s:", setAName, setBName);
205             System.out.println();
206             printSet(a);
207         } else {
208             b.removeAll(a);
209             System.out.printf("Set %s has more elements than set %s:", setBName, setAName);
210             System.out.println();
211             printSet(b);
212         }
213     }
214 
215     private static void printSet(Set<String> set) {
216         for (String e : set) {
217             System.out.println(e);
218         }
219     }
220 
221     private static void print(String s) {
222         System.out.println(s);
223     }
224 }