1 /*
   2  * Copyright (c) 2016, 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.internal.tool;
  27 
  28 import java.io.IOException;
  29 import java.io.PrintStream;
  30 import java.io.PrintWriter;
  31 import java.nio.charset.Charset;
  32 import java.nio.file.Path;
  33 import java.util.ArrayList;
  34 import java.util.Deque;
  35 import java.util.HashMap;
  36 import java.util.List;
  37 import java.util.Map;
  38 import java.util.function.Function;
  39 import java.util.function.Predicate;
  40 
  41 import jdk.jfr.EventType;
  42 
  43 final class Print extends Command {
  44     @Override
  45     public String getName() {
  46         return "print";
  47     }
  48 
  49     @Override
  50     public List<String> getOptionSyntax() {
  51         List<String> list = new ArrayList<>();
  52         list.add("[--xml|--json]");
  53         list.add("[--categories <filter>]");
  54         list.add("[--events <filter>]");
  55         list.add("[--stack-depth <depth>]");
  56         list.add("<file>");
  57         return list;
  58     }
  59 
  60     @Override
  61     protected String getTitle() {
  62         return "Print contents of a recording file";
  63     }
  64 
  65     @Override
  66     public String getDescription() {
  67         return getTitle() + ". See 'jfr help print' for details.";
  68     }
  69 
  70     @Override
  71     public void displayOptionUsage(PrintStream stream) {
  72         stream.println("  --xml                   Print recording in XML format");
  73         stream.println();
  74         stream.println("  --json                  Print recording in JSON format");
  75         stream.println();
  76         stream.println("  --categories <filter>   Select events matching a category name.");
  77         stream.println("                          The filter is a comma-separated list of names,");
  78         stream.println("                          simple and/or qualified, and/or quoted glob patterns");
  79         stream.println();
  80         stream.println("  --events <filter>       Select events matching an event name.");
  81         stream.println("                          The filter is a comma-separated list of names,");
  82         stream.println("                          simple and/or qualified, and/or quoted glob patterns");
  83         stream.println();
  84         stream.println("  --stack-depth <depth>   Number of frames in stack traces, by default 5");
  85         stream.println();
  86         stream.println("  <file>                  Location of the recording file (.jfr)");
  87         stream.println();
  88         stream.println();
  89         stream.println("Example usage:");
  90         stream.println();
  91         stream.println(" jfr print --events OldObjectSample recording.jfr");
  92         stream.println();
  93         stream.println(" jfr print --events CPULoad,GarbageCollection recording.jfr");
  94         stream.println();
  95         stream.println(" jfr print --categories \"GC,JVM,Java*\" recording.jfr");
  96         stream.println();
  97         stream.println(" jfr print --events \"jdk.*\" --stack-depth 64 recording.jfr");
  98         stream.println();
  99         stream.println(" jfr print --json --events CPULoad recording.jfr");
 100     }
 101 
 102     @Override
 103     public void execute(Deque<String> options) throws UserSyntaxException, UserDataException {
 104         Path file = getJFRInputFile(options);
 105         PrintWriter pw = new PrintWriter(System.out, false);
 106         Predicate<EventType> eventFilter = null;
 107         int stackDepth = 5;
 108         EventPrintWriter eventWriter = null;
 109         int optionCount = options.size();
 110         while (optionCount > 0) {
 111             if (acceptFilterOption(options, "--events")) {
 112                 String filter = options.remove();
 113                 warnForWildcardExpansion("--events", filter);
 114                 eventFilter = addEventFilter(filter, eventFilter);
 115             }
 116             if (acceptFilterOption(options, "--categories")) {
 117                 String filter = options.remove();
 118                 warnForWildcardExpansion("--categories", filter);
 119                 eventFilter = addCategoryFilter(filter, eventFilter);
 120             }
 121             if (acceptOption(options, "--stack-depth")) {
 122                 String value = options.pop();
 123                 try {
 124                     stackDepth = Integer.parseInt(value);
 125                     if (stackDepth < 0) {
 126                         throw new UserSyntaxException("stack depth must be zero or a positive integer.");
 127                     }
 128                 } catch (NumberFormatException nfe) {
 129                     throw new UserSyntaxException("not a valid value for --stack-depth");
 130                 }
 131             }
 132             if (acceptFormatterOption(options, eventWriter, "--json")) {
 133                 eventWriter = new JSONWriter(pw);
 134             }
 135             if (acceptFormatterOption(options, eventWriter, "--xml")) {
 136                 eventWriter = new XMLWriter(pw);
 137             }
 138             if (optionCount == options.size()) {
 139                 // No progress made
 140                 throw new UserSyntaxException("unknown option " + options.peek());
 141             }
 142             optionCount = options.size();
 143         }
 144         if (eventWriter == null) {
 145             eventWriter = new PrettyWriter(pw); // default to pretty printer
 146         }
 147         eventWriter.setStackDepth(stackDepth);
 148         if (eventFilter != null) {
 149             eventFilter = addCache(eventFilter, eventType -> eventType.getId());
 150             eventWriter.setEventFilter(eventFilter);
 151         }
 152         try {
 153             eventWriter.print(file);
 154         } catch (IOException ioe) {
 155             couldNotReadError(file, ioe);
 156         }
 157         pw.flush();
 158     }
 159 
 160     private static boolean acceptFormatterOption(Deque<String> options, EventPrintWriter eventWriter, String expected) throws UserSyntaxException {
 161         if (expected.equals(options.peek())) {
 162             if (eventWriter != null) {
 163                 throw new UserSyntaxException("only one format can be specified at a time");
 164             }
 165             options.remove();
 166             return true;
 167         }
 168         return false;
 169     }
 170 
 171     private static <T, X> Predicate<T> addCache(final Predicate<T> filter, Function<T, X> cacheFunction) {
 172         Map<X, Boolean> cache = new HashMap<>();
 173         return t -> cache.computeIfAbsent(cacheFunction.apply(t), x -> filter.test(t));
 174     }
 175 
 176     private static <T> Predicate<T> recurseIfPossible(Predicate<T> filter) {
 177         return x -> filter != null && filter.test(x);
 178     }
 179 
 180     private static Predicate<EventType> addCategoryFilter(String filterText, Predicate<EventType> eventFilter) throws UserSyntaxException {
 181         List<String> filters = explodeFilter(filterText);
 182         return recurseIfPossible(eventType -> {
 183             for (String category : eventType.getCategoryNames()) {
 184                 for (String filter : filters) {
 185                     if (match(category, filter)) {
 186                         return true;
 187                     }
 188                     if (category.contains(" ") && acronomify(category).equals(filter)) {
 189                         return true;
 190                     }
 191                 }
 192             }
 193             return false;
 194         });
 195     }
 196 
 197     private static String acronomify(String multipleWords) {
 198         boolean newWord = true;
 199         String acronym = "";
 200         for (char c : multipleWords.toCharArray()) {
 201             if (newWord) {
 202                 if (Character.isAlphabetic(c) && Character.isUpperCase(c)) {
 203                     acronym += c;
 204                 }
 205             }
 206             newWord = Character.isWhitespace(c);
 207         }
 208         return acronym;
 209     }
 210 
 211     private static Predicate<EventType> addEventFilter(String filterText, final Predicate<EventType> eventFilter) throws UserSyntaxException {
 212         List<String> filters = explodeFilter(filterText);
 213         return recurseIfPossible(eventType -> {
 214             for (String filter : filters) {
 215                 String fullEventName = eventType.getName();
 216                 if (match(fullEventName, filter)) {
 217                     return true;
 218                 }
 219                 String eventName = fullEventName.substring(fullEventName.lastIndexOf(".") + 1);
 220                 if (match(eventName, filter)) {
 221                     return true;
 222                 }
 223             }
 224             return false;
 225         });
 226     }
 227 
 228     private static boolean match(String text, String filter) {
 229         if (filter.length() == 0) {
 230             // empty filter string matches if string is empty
 231             return text.length() == 0;
 232         }
 233         if (filter.charAt(0) == '*') { // recursive check
 234             filter = filter.substring(1);
 235             for (int n = 0; n <= text.length(); n++) {
 236                 if (match(text.substring(n), filter))
 237                     return true;
 238             }
 239         } else if (text.length() == 0) {
 240             // empty string and non-empty filter does not match
 241             return false;
 242         } else if (filter.charAt(0) == '?') {
 243             // eat any char and move on
 244             return match(text.substring(1), filter.substring(1));
 245         } else if (filter.charAt(0) == text.charAt(0)) {
 246             // eat chars and move on
 247             return match(text.substring(1), filter.substring(1));
 248         }
 249         return false;
 250     }
 251 
 252     private static List<String> explodeFilter(String filter) throws UserSyntaxException {
 253         List<String> list = new ArrayList<>();
 254         for (String s : filter.split(",")) {
 255             s = s.trim();
 256             if (!s.isEmpty()) {
 257                 list.add(s);
 258             }
 259         }
 260         return list;
 261     }
 262 }