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     // Virtual thread events, covered by a different test
 82     private static final Set<String> virtualThreadEvents = Set.of(
 83             "jdk.VirtualThreadStart",
 84             "jdk.VirtualThreadEnd",
 85             "jdk.VirtualThreadPinned",
 86             "jdk.VirtualThreadSubmitFailed"
 87     );
 88 
 89     // This is a "known failure list" for this test.
 90     // NOTE: if the event is not covered, a bug should be open, and bug number
 91     // noted in the comments for this set.
 92     private static final Set<String> knownNotCoveredEvents = new HashSet<>(
 93     );
 94 
 95     // Experimental events
 96     private static final Set<String> experimentalEvents = new HashSet<>(
 97         Arrays.asList(
 98             "Flush", "SyncOnValueBasedClass")
 99     );
100 
101 
102     public static void main(String[] args) throws Exception {
103         for (EventType type : FlightRecorder.getFlightRecorder().getEventTypes()) {
104             if (type.getAnnotation(Experimental.class) == null) {
105                 jfrEventTypes.add(type.getName().replace("jdk.", ""));
106             }
107         }
108 
109         checkEventNamesClass();
110         lookForEventsNotCoveredByTests();
111     }
112 
113     // Look thru JFR tests to make sure JFR events are referenced in the tests
114     private static void lookForEventsNotCoveredByTests() throws Exception {
115         List<Path> paths = Files.walk(jfrTestRoot)
116             .filter(Files::isRegularFile)
117             .filter(path -> isJavaFile(path))
118             .collect(Collectors.toList());
119 
120         Set<String> eventsNotCoveredByTest = new HashSet<>(jfrEventTypes);
121         for (String event : jfrEventTypes) {
122             for (Path p : paths) {
123                 if (findStringInFile(p, event)) {
124                     eventsNotCoveredByTest.remove(event);
125                     break;
126                 }
127             }
128         }
129 
130         // Account for hard-to-test, experimental and GC tested events
131         eventsNotCoveredByTest.removeAll(hardToTestEvents);
132         eventsNotCoveredByTest.removeAll(coveredGcEvents);
133         eventsNotCoveredByTest.removeAll(coveredContainerEvents);
134         eventsNotCoveredByTest.removeAll(knownNotCoveredEvents);
135         eventsNotCoveredByTest.removeAll(virtualThreadEvents);
136 
137         if (!eventsNotCoveredByTest.isEmpty()) {
138             print(MSG_SEPARATOR + " Events not covered by test");
139             for (String event: eventsNotCoveredByTest) {
140                 print(event);
141             }
142             print(MSG_SEPARATOR);
143             throw new RuntimeException("Found JFR events not covered by tests");
144         }
145     }
146 
147     // Make sure all the JFR events are accounted for in jdk.test.lib.jfr.EventNames
148     private static void checkEventNamesClass() throws Exception {
149         // jdk.test.lib.jfr.EventNames
150         Set<String> eventsFromEventNamesClass = new HashSet<>();
151         for (Field f : EventNames.class.getFields()) {
152             String name = f.getName();
153             if (!name.equals("PREFIX")) {
154                 String eventName = (String) f.get(null);
155                 eventName = eventName.replace(EventNames.PREFIX, "");
156                 eventsFromEventNamesClass.add(eventName);
157             }
158         }
159 
160         // remove experimental events from eventsFromEventNamesClass since jfrEventTypes
161         // excludes experimental events
162         eventsFromEventNamesClass.removeAll(experimentalEvents);
163 
164         if (!jfrEventTypes.equals(eventsFromEventNamesClass)) {
165             String exceptionMsg = "Events declared in jdk.test.lib.jfr.EventNames differ " +
166                          "from events returned by FlightRecorder.getEventTypes()";
167             print(MSG_SEPARATOR);
168             print(exceptionMsg);
169             print("");
170             printSetDiff(jfrEventTypes, eventsFromEventNamesClass,
171                         "jfrEventTypes", "eventsFromEventNamesClass");
172             print("");
173 
174             print("This could be because:");
175             print("1) You forgot to write a unit test. Please do so in test/jdk/jdk/jfr/event/");
176             print("2) You wrote a unit test, but you didn't reference the event in");
177             print("   test/lib/jdk/test/lib/jfr/EventNames.java. ");
178             print("3) It is not feasible to test the event, not even a sanity test. ");
179             print("   Add the event name to test/lib/jdk/test/lib/jfr/EventNames.java ");
180             print("   and a short comment why it can't be tested");
181             print("4) The event is experimental. Please add 'experimental=\"true\"' to <Event> ");
182             print("   element in metadata.xml if it is a native event, or @Experimental if it is a ");
183             print("   Java event. The event will now not show up in JMC");
184             System.out.println(MSG_SEPARATOR);
185             throw new RuntimeException(exceptionMsg);
186         }
187     }
188 
189     // ================ Helper methods
190     private static boolean isJavaFile(Path p) {
191         String fileName = p.getFileName().toString();
192         int i = fileName.lastIndexOf('.');
193         if ( (i < 0) || (i > fileName.length()) ) {
194             return false;
195         }
196         return "java".equals(fileName.substring(i+1));
197     }
198 
199     private static boolean findStringInFile(Path p, String searchTerm) throws IOException {
200         long c = 0;
201         try (Stream<String> stream = Files.lines(p)) {
202             c = stream
203                 .filter(line -> line.contains(searchTerm))
204                 .count();
205         }
206         return (c != 0);
207     }
208 
209     private static void printSetDiff(Set<String> a, Set<String> b,
210         String setAName, String setBName) {
211         if (a.size() > b.size()) {
212             a.removeAll(b);
213             System.out.printf("Set %s has more elements than set %s:", setAName, setBName);
214             System.out.println();
215             printSet(a);
216         } else {
217             b.removeAll(a);
218             System.out.printf("Set %s has more elements than set %s:", setBName, setAName);
219             System.out.println();
220             printSet(b);
221         }
222     }
223 
224     private static void printSet(Set<String> set) {
225         for (String e : set) {
226             System.out.println(e);
227         }
228     }
229 
230     private static void print(String s) {
231         System.out.println(s);
232     }
233 }