|
| 1 | +/* |
| 2 | + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 3 | + * or more contributor license agreements. Licensed under the Elastic License; |
| 4 | + * you may not use this file except in compliance with the Elastic License. |
| 5 | + */ |
| 6 | +package org.elasticsearch.xpack.ml.job.categorization; |
| 7 | + |
| 8 | +import org.elasticsearch.grok.Grok; |
| 9 | + |
| 10 | +import java.io.BufferedReader; |
| 11 | +import java.io.IOException; |
| 12 | +import java.io.InputStreamReader; |
| 13 | +import java.io.UncheckedIOException; |
| 14 | +import java.nio.charset.StandardCharsets; |
| 15 | +import java.util.ArrayList; |
| 16 | +import java.util.Arrays; |
| 17 | +import java.util.Collection; |
| 18 | +import java.util.Collections; |
| 19 | +import java.util.HashMap; |
| 20 | +import java.util.List; |
| 21 | +import java.util.Map; |
| 22 | +import java.util.regex.Matcher; |
| 23 | +import java.util.regex.Pattern; |
| 24 | + |
| 25 | + |
| 26 | +/** |
| 27 | + * Creates Grok patterns that will match all the examples in a given category_definition. |
| 28 | + * |
| 29 | + * The choice of field names is quite primitive. The intention is that a human will edit these. |
| 30 | + */ |
| 31 | +public final class GrokPatternCreator { |
| 32 | + |
| 33 | + private static String PREFACE = "preface"; |
| 34 | + private static String EPILOGUE = "epilogue"; |
| 35 | + |
| 36 | + /** |
| 37 | + * The first match in this list will be chosen, so it needs to be ordered |
| 38 | + * such that more generic patterns come after more specific patterns. |
| 39 | + */ |
| 40 | + private static final List<GrokPatternCandidate> ORDERED_CANDIDATE_GROK_PATTERNS = Arrays.asList( |
| 41 | + new GrokPatternCandidate("TIMESTAMP_ISO8601", "timestamp"), |
| 42 | + new GrokPatternCandidate("DATESTAMP_RFC822", "timestamp"), |
| 43 | + new GrokPatternCandidate("DATESTAMP_RFC2822", "timestamp"), |
| 44 | + new GrokPatternCandidate("DATESTAMP_OTHER", "timestamp"), |
| 45 | + new GrokPatternCandidate("DATESTAMP_EVENTLOG", "timestamp"), |
| 46 | + new GrokPatternCandidate("SYSLOGTIMESTAMP", "timestamp"), |
| 47 | + new GrokPatternCandidate("HTTPDATE", "timestamp"), |
| 48 | + new GrokPatternCandidate("CATALINA_DATESTAMP", "timestamp"), |
| 49 | + new GrokPatternCandidate("TOMCAT_DATESTAMP", "timestamp"), |
| 50 | + new GrokPatternCandidate("CISCOTIMESTAMP", "timestamp"), |
| 51 | + new GrokPatternCandidate("DATE", "date"), |
| 52 | + new GrokPatternCandidate("TIME", "time"), |
| 53 | + new GrokPatternCandidate("LOGLEVEL", "loglevel"), |
| 54 | + new GrokPatternCandidate("URI", "uri"), |
| 55 | + new GrokPatternCandidate("UUID", "uuid"), |
| 56 | + new GrokPatternCandidate("MAC", "macaddress"), |
| 57 | + // Can't use \b as the breaks, because slashes are not "word" characters |
| 58 | + new GrokPatternCandidate("PATH", "path", "(?<!\\w)", "(?!\\w)"), |
| 59 | + new GrokPatternCandidate("EMAILADDRESS", "email"), |
| 60 | + // TODO: would be nice to have IPORHOST here, but HOST matches almost all words |
| 61 | + new GrokPatternCandidate("IP", "ipaddress"), |
| 62 | + // This already includes pre/post break conditions |
| 63 | + new GrokPatternCandidate("QUOTEDSTRING", "field", "", ""), |
| 64 | + // Can't use \b as the break before, because it doesn't work for negative numbers (the |
| 65 | + // minus sign is not a "word" character) |
| 66 | + new GrokPatternCandidate("NUMBER", "field", "(?<!\\w)"), |
| 67 | + // Disallow +, - and . before hex numbers, otherwise this pattern will pick up base 10 |
| 68 | + // numbers that NUMBER rejected due to preceeding characters |
| 69 | + new GrokPatternCandidate("BASE16NUM", "field", "(?<![\\w.+-])") |
| 70 | + // TODO: also unfortunately can't have USERNAME in the list as it matches too broadly |
| 71 | + // Fixing these problems with overly broad matches would require some extra intelligence |
| 72 | + // to be added to remove inappropriate matches. One idea would be to use a dictionary, |
| 73 | + // but that doesn't necessarily help as "jay" could be a username but is also a dictionary |
| 74 | + // word (plus there's the international headache with relying on dictionaries). Similarly, |
| 75 | + // hostnames could also be dictionary words - I've worked on machines called "hippo" and |
| 76 | + // "scarf" in the past. Another idea would be to look at the adjacent characters and |
| 77 | + // apply some heuristic based on those. |
| 78 | + ); |
| 79 | + |
| 80 | + private GrokPatternCreator() { |
| 81 | + } |
| 82 | + |
| 83 | + /** |
| 84 | + * Given a category definition regex and a collection of examples from the category, return |
| 85 | + * a grok pattern that will match the category and pull out any likely fields. The extracted |
| 86 | + * fields are given pretty generic names, but unique within the grok pattern provided. The |
| 87 | + * expectation is that a user will adjust the extracted field names based on their domain |
| 88 | + * knowledge. |
| 89 | + */ |
| 90 | + public static String findBestGrokMatchFromExamples(String regex, Collection<String> examples) { |
| 91 | + |
| 92 | + // The first string in this array will end up being the empty string, and it doesn't correspond |
| 93 | + // to an "in between" bit. Although it could be removed for "neatness", it actually makes the |
| 94 | + // loops below slightly neater if it's left in. |
| 95 | + // |
| 96 | + // E.g., ".*?cat.+?sat.+?mat.*" -> [ "", "cat", "sat", "mat" ] |
| 97 | + String[] fixedRegexBits = regex.split("\\.[*+]\\??"); |
| 98 | + |
| 99 | + // Create a pattern that will capture the bits in between the fixed parts of the regex |
| 100 | + // |
| 101 | + // E.g., ".*?cat.+?sat.+?mat.*" -> Pattern (.*?)cat(.+?)sat(.+?)mat(.*) |
| 102 | + Pattern exampleProcessor = Pattern.compile(regex.replaceAll("(\\.[*+]\\??)", "($1)"), Pattern.DOTALL); |
| 103 | + |
| 104 | + List<Collection<String>> inBetweenBits = new ArrayList<>(fixedRegexBits.length); |
| 105 | + for (String example : examples) { |
| 106 | + Matcher matcher = exampleProcessor.matcher(example); |
| 107 | + if (matcher.matches()) { |
| 108 | + assert matcher.groupCount() == fixedRegexBits.length; |
| 109 | + // E.g., if the input regex was ".*?cat.+?sat.+?mat.*" then the example |
| 110 | + // "the cat sat on the mat" will result in "the ", " ", " on the ", and "" |
| 111 | + // being added to the 4 "in between" collections in that order |
| 112 | + for (int groupNum = 1; groupNum <= matcher.groupCount(); ++groupNum) { |
| 113 | + if (inBetweenBits.size() < groupNum) { |
| 114 | + inBetweenBits.add(new ArrayList<>(examples.size())); |
| 115 | + } |
| 116 | + inBetweenBits.get(groupNum - 1).add(matcher.group(groupNum)); |
| 117 | + } |
| 118 | + } else { |
| 119 | + // We should never get here. If we do it implies a bug in the original categorization, |
| 120 | + // as it's produced a regex that doesn't match the examples. |
| 121 | + assert matcher.matches() : exampleProcessor.pattern() + " did not match " + example; |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + Map<String, Integer> fieldNameCountStore = new HashMap<>(); |
| 126 | + StringBuilder overallGrokPatternBuilder = new StringBuilder(); |
| 127 | + // Finally, for each collection of "in between" bits we look for the best Grok pattern and incorporate |
| 128 | + // it into the overall Grok pattern that will match the each example in its entirety |
| 129 | + for (int inBetweenBitNum = 0; inBetweenBitNum < inBetweenBits.size(); ++inBetweenBitNum) { |
| 130 | + // Remember (from the first comment in this method) that the first element in this array is |
| 131 | + // always the empty string |
| 132 | + overallGrokPatternBuilder.append(fixedRegexBits[inBetweenBitNum]); |
| 133 | + appendBestGrokMatchForStrings(fieldNameCountStore, overallGrokPatternBuilder, inBetweenBitNum == 0, |
| 134 | + inBetweenBitNum == fixedRegexBits.length - 1, inBetweenBits.get(inBetweenBitNum)); |
| 135 | + } |
| 136 | + return overallGrokPatternBuilder.toString(); |
| 137 | + } |
| 138 | + |
| 139 | + /** |
| 140 | + * Given a collection of strings, work out which (if any) of the grok patterns we're allowed |
| 141 | + * to use matches it best. Then append the appropriate grok language to represent that finding |
| 142 | + * onto the supplied string builder. |
| 143 | + */ |
| 144 | + static void appendBestGrokMatchForStrings(Map<String, Integer> fieldNameCountStore, StringBuilder overallGrokPatternBuilder, |
| 145 | + boolean isFirst, boolean isLast, Collection<String> mustMatchStrings) { |
| 146 | + |
| 147 | + GrokPatternCandidate bestCandidate = null; |
| 148 | + for (GrokPatternCandidate candidate : ORDERED_CANDIDATE_GROK_PATTERNS) { |
| 149 | + if (mustMatchStrings.stream().allMatch(candidate.grok::match)) { |
| 150 | + bestCandidate = candidate; |
| 151 | + break; |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + if (bestCandidate == null) { |
| 156 | + if (isLast) { |
| 157 | + overallGrokPatternBuilder.append(".*"); |
| 158 | + } else if (isFirst || mustMatchStrings.stream().anyMatch(String::isEmpty)) { |
| 159 | + overallGrokPatternBuilder.append(".*?"); |
| 160 | + } else { |
| 161 | + overallGrokPatternBuilder.append(".+?"); |
| 162 | + } |
| 163 | + } else { |
| 164 | + Collection<String> prefaces = new ArrayList<>(); |
| 165 | + Collection<String> epilogues = new ArrayList<>(); |
| 166 | + populatePrefacesAndEpilogues(mustMatchStrings, bestCandidate.grok, prefaces, epilogues); |
| 167 | + appendBestGrokMatchForStrings(fieldNameCountStore, overallGrokPatternBuilder, isFirst, false, prefaces); |
| 168 | + overallGrokPatternBuilder.append("%{").append(bestCandidate.grokPatternName).append(':') |
| 169 | + .append(buildFieldName(fieldNameCountStore, bestCandidate.fieldName)).append('}'); |
| 170 | + appendBestGrokMatchForStrings(fieldNameCountStore, overallGrokPatternBuilder, false, isLast, epilogues); |
| 171 | + } |
| 172 | + } |
| 173 | + |
| 174 | + /** |
| 175 | + * Given a collection of strings, and a grok pattern that matches some part of them all, |
| 176 | + * return collections of the bits that come before (prefaces) and after (epilogues) the |
| 177 | + * bit that matches. |
| 178 | + */ |
| 179 | + static void populatePrefacesAndEpilogues(Collection<String> matchingStrings, Grok grok, Collection<String> prefaces, |
| 180 | + Collection<String> epilogues) { |
| 181 | + for (String s : matchingStrings) { |
| 182 | + Map<String, Object> captures = grok.captures(s); |
| 183 | + // If the pattern doesn't match then captures will be null. But we expect this |
| 184 | + // method to only be called after validating that the pattern does match. |
| 185 | + assert captures != null; |
| 186 | + prefaces.add(captures.getOrDefault(PREFACE, "").toString()); |
| 187 | + epilogues.add(captures.getOrDefault(EPILOGUE, "").toString()); |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + /** |
| 192 | + * The first time a particular field name is passed, simply return it. |
| 193 | + * The second time return it with "2" appended. |
| 194 | + * The third time return it with "3" appended. |
| 195 | + * Etc. |
| 196 | + */ |
| 197 | + static String buildFieldName(Map<String, Integer> fieldNameCountStore, String fieldName) { |
| 198 | + Integer numberSeen = fieldNameCountStore.compute(fieldName, (k, v) -> 1 + ((v == null) ? 0 : v)); |
| 199 | + if (numberSeen > 1) { |
| 200 | + return fieldName + numberSeen; |
| 201 | + } else { |
| 202 | + return fieldName; |
| 203 | + } |
| 204 | + } |
| 205 | + |
| 206 | + static class GrokPatternCandidate { |
| 207 | + |
| 208 | + final String grokPatternName; |
| 209 | + final String fieldName; |
| 210 | + final Grok grok; |
| 211 | + |
| 212 | + /** |
| 213 | + * Pre/post breaks default to \b, but this may not be appropriate for Grok patterns that start or |
| 214 | + * end with a non "word" character (i.e. letter, number or underscore). For such patterns use one |
| 215 | + * of the other constructors. |
| 216 | + * |
| 217 | + * In cases where the Grok pattern defined by Logstash already includes conditions on what must |
| 218 | + * come before and after the match, use one of the other constructors and specify an empty string |
| 219 | + * for the pre and/or post breaks. |
| 220 | + * @param grokPatternName Name of the Grok pattern to try to match - must match one defined in Logstash. |
| 221 | + * @param fieldName Name of the field to extract from the match. |
| 222 | + */ |
| 223 | + GrokPatternCandidate(String grokPatternName, String fieldName) { |
| 224 | + this(grokPatternName, fieldName, "\\b", "\\b"); |
| 225 | + } |
| 226 | + |
| 227 | + GrokPatternCandidate(String grokPatternName, String fieldName, String preBreak) { |
| 228 | + this(grokPatternName, fieldName, preBreak, "\\b"); |
| 229 | + } |
| 230 | + |
| 231 | + /** |
| 232 | + * @param grokPatternName Name of the Grok pattern to try to match - must match one defined in Logstash. |
| 233 | + * @param fieldName Name of the field to extract from the match. |
| 234 | + * @param preBreak Only consider the match if it's broken from the previous text by this. |
| 235 | + * @param postBreak Only consider the match if it's broken from the following text by this. |
| 236 | + */ |
| 237 | + GrokPatternCandidate(String grokPatternName, String fieldName, String preBreak, String postBreak) { |
| 238 | + this.grokPatternName = grokPatternName; |
| 239 | + this.fieldName = fieldName; |
| 240 | + this.grok = new Grok(Grok.getBuiltinPatterns(), "%{DATA:" + PREFACE + "}" + preBreak + "%{" + grokPatternName + ":this}" + |
| 241 | + postBreak + "%{GREEDYDATA:" + EPILOGUE + "}"); |
| 242 | + } |
| 243 | + } |
| 244 | +} |
0 commit comments