This repository was archived by the owner on Jul 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathDatadogExpressionBuilder.java
More file actions
354 lines (289 loc) · 11.9 KB
/
DatadogExpressionBuilder.java
File metadata and controls
354 lines (289 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package com.wavefront.labs.convert.converter.datadog;
import com.wavefront.labs.convert.DefaultExpressionBuilder;
import com.wavefront.labs.convert.converter.datadog.models.DatadogTemplateVariable;
import com.wavefront.labs.convert.converter.datadog.query.DatadogFunction;
import com.wavefront.labs.convert.converter.datadog.query.DatadogQuery;
import com.wavefront.labs.convert.converter.datadog.query.Variable;
import com.wavefront.labs.convert.converter.datadog.query.functions.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class DatadogExpressionBuilder extends DefaultExpressionBuilder {
public static final String QUERY_SEPARATOR = " \"\"\" "; //should never seen 3 consecutive double quotes in any query
public static final String QUERY_SEPARATOR_SPLIT = " \\\"\\\"\\\" ";
private static final Logger logger = LogManager.getLogger(DatadogExpressionBuilder.class);
private static final Pattern expressionListPattern = Pattern.compile("\\{.*?\\}|(\\+|-|\\*|\\/|;)");
private static final Pattern topConveniencePattern = Pattern.compile("^(top|bottom)(5|10|15|20)_?(mean|min|max|last|area|l2norm|norm)?$");
// NOTE: Including '(',')' as operators so they get added back to the query after parsing
private static final Pattern operatorNumberPattern = Pattern.compile("(\\(|\\)|\\+|-|\\*|/)|(-?\\d+([.]\\d+)?)");
private static final HashMap<String, Function<DatadogFunction, String>> functionMap = new HashMap();
static {
functionMap.put("avg", AggregationFunctions::avg);
functionMap.put("sum", AggregationFunctions::sum);
functionMap.put("min", AggregationFunctions::min);
functionMap.put("max", AggregationFunctions::max);
functionMap.put("count", AggregationFunctions::count);
functionMap.put("first", AggregationFunctions::first);
functionMap.put("last", AggregationFunctions::last);
functionMap.put("as_rate", TimeFunctions::asRate);
functionMap.put("as_count", NotSupported::allow);
functionMap.put("abs", MathFunctions::abs);
functionMap.put("log2", MathFunctions::log);
functionMap.put("log10", MathFunctions::log10);
functionMap.put("cumsum", MathFunctions::cumsum); //TODO: investigate
functionMap.put("integral", MathFunctions::integral); //TODO: investigate
functionMap.put("fill", MissingDataFunctions::fill); //TODO: linear with time?
functionMap.put("hour_before", TimeFunctions::hourBefore);
functionMap.put("day_before", TimeFunctions::dayBefore);
functionMap.put("week_before", TimeFunctions::weekBefore);
functionMap.put("month_before", TimeFunctions::monthBefore);
functionMap.put("per_second", TimeFunctions::perSecond);
functionMap.put("per_minute", TimeFunctions::perMinute);
functionMap.put("per_hour", TimeFunctions::perHour);
functionMap.put("dt", NotSupported::warning);
functionMap.put("diff", TimeFunctions::diff);
functionMap.put("forecast", PredictiveFunctions::forecast);
functionMap.put("derivative", NotSupported::warning);
functionMap.put("ewma_3", MovingFunctions::ewma3);
functionMap.put("ewma_5", MovingFunctions::ewma5);
functionMap.put("ewma_10", MovingFunctions::ewma10);
functionMap.put("ewma_20", MovingFunctions::ewma20);
functionMap.put("median_3", MovingFunctions::median3);
functionMap.put("median_5", MovingFunctions::median5);
functionMap.put("median_7", MovingFunctions::median7);
functionMap.put("median_9", MovingFunctions::median9);
functionMap.put("rollup", FilteringFunctions::rollup);
functionMap.put("count_nonzero", MissingDataFunctions::countNonzero);
functionMap.put("count_not_null", MissingDataFunctions::countNotNull);
functionMap.put("top", RankingFunctions::top);
functionMap.put("top_offset", RankingFunctions::topOffset);
functionMap.put("TOP_CONVENIENCE", RankingFunctions::topConvenience);
functionMap.put("robust_trend", NotSupported::warning);
functionMap.put("trend_line", NotSupported::warning);
functionMap.put("piecewise_constant", NotSupported::warning);
functionMap.put("anomalies", NotSupported::warning);
functionMap.put("outliers", NotSupported::warning);
functionMap.put("NOT_FOUND", NotSupported::notFound);
}
private String underscoreReplace;
private HashMap<String, com.wavefront.labs.convert.converter.datadog.query.Variable> variablesMap;
private Set<String> dropTags;
@Override
public void init(Properties properties) {
super.init(properties);
underscoreReplace = properties.getProperty("datadog.underscoreReplace", ".");
dropTags = Arrays.stream(properties.getProperty("datadog.dropTags", "").split(",")).collect(Collectors.toSet());
variablesMap = new HashMap();
}
public String buildMetricName(DatadogQuery datadogQuery) {
String orig = datadogQuery.getMetric();
List<String> scopes = datadogQuery.getScopes();
if (scopes != null && scopes.size() > 0) {
for (String scope : scopes) {
String[] scopeParts = scope.split(":");
if (scopeParts.length > 1 && scopeParts[0].equals("origin")) {
String origin = scopeParts[1];
String matcher = "^datadog\\.nozzle\\.(.*)$";
String replace = "datadog.nozzle." + origin + ".$1";
orig = orig.replaceAll(matcher,replace);
}
}
}
String metricName = buildName(orig, "metric");
//metricName = metricName.replaceAll("_", underscoreReplace);
return super.buildMetricName(metricName);
}
@Override
public String buildExpression(Object data) {
String origQuery = data.toString().trim();
if (origQuery.equals("")) {
return "";
}
ArrayList<String> queryList = createQueryList(origQuery);
StringBuilder ts = new StringBuilder();
for (String query : queryList) {
query = query.trim();
if (operatorNumberPattern.matcher(query).matches()) {
ts.append(" ").append(query).append(" ");
} else if (query.equals(";")) {
ts.append(QUERY_SEPARATOR);
} else {
DatadogQuery datadogQuery = new DatadogQuery(query);
ts.append(convertDatadogQuery(datadogQuery));
}
}
return ts.toString();
}
private String convertDatadogQuery(DatadogQuery datadogQuery) {
try {
String query = makeMetricQuery(datadogQuery);
query = makeAggregateQuery(datadogQuery, query);
query = makeFunctionQuery(datadogQuery, query);
return query;
} catch (Exception e) {
logger.error("Could not convert Datadog query: " + datadogQuery.getQuery(), e);
return "";
}
}
private String makeFunctionQuery(DatadogQuery datadogQuery, String query) {
for (DatadogFunction function : datadogQuery.getFunctions()) {
Function<DatadogFunction, String> convertFunction;
if (functionMap.containsKey(function.getName())) {
convertFunction = functionMap.get(function.getName());
} else if (topConveniencePattern.matcher(function.getName()).matches()) {
convertFunction = functionMap.get("TOP_CONVENIENCE");
} else {
convertFunction = functionMap.get("NOT_FOUND");
}
function.setQuery(query);
query = convertFunction.apply(function);
}
return query;
}
private String makeAggregateQuery(DatadogQuery datadogQuery, String query) {
String aggregator = datadogQuery.getAggregator();
if (aggregator != null) {
query = datadogQuery.getAggregator() + "(" + query;
List<String> groups = datadogQuery.getGroups();
if (groups != null && groups.size() > 0) {
StringJoiner aggGroups = new StringJoiner(", ", ", ", "");
for (String group : groups) {
if (group.equals("host")) {
aggGroups.add("sources");
} else {
if (!dropTags.contains(group)) {
group = buildName(group, "tagName");
aggGroups.add(group);
}
}
}
query = query + aggGroups;
}
query = query + ")";
}
return query;
}
private String makeMetricQuery(DatadogQuery datadogQuery) {
String query = datadogQuery.getNumeral();
if (datadogQuery.getMetric() != null && !"".equals(datadogQuery.getMetric())) {
query = "ts(\"" + buildMetricName(datadogQuery) + "\"";
List<String> scopes = datadogQuery.getScopes();
if (scopes != null && scopes.size() > 0) {
if (!scopes.get(0).equals("*")) {
StringJoiner filters = new StringJoiner(" and ", ", ", "");
for (String scope : scopes) {
boolean notFilter = false;
String filterValue = null;
if (scope.startsWith("!")) {
scope = scope.substring(1);
notFilter = true;
}
if (scope.startsWith("$")) {
String name = scope.substring(1);
if (variablesMap.containsKey(name)) {
Variable variable = variablesMap.get(name);
if (variable.isGeneric()) {
filterValue = "${" + variable.getName() + "}";
} else if (!dropTags.contains(variable.getTagName())) {
filterValue = variable.getTagName() + "=\"${" + variable.getName() + "}\"";
if (variable.getMetric() == null) {
variable.setMetric(datadogQuery.getMetric());
}
}
}
com.wavefront.labs.convert.utils.Tracker.increment("\"Ignored Filters In Chart Count\"");
} else {
String[] scopeParts = scope.split(":");
if (scopeParts.length > 1) {
if (!dropTags.contains(scopeParts[0])) {
String tagName = buildName(scopeParts[0], "tagName");
String tagValue = buildName(scopeParts[1], "tagValue");
filterValue = tagName + "=\"" + tagValue + "\"";
}
} else if (!dropTags.contains(scope)) {
String tagName = buildName(scope, "tagName");
filterValue = "tag=\"" + tagName + "\"";
}
}
if (filterValue != null) {
if (notFilter) {
filterValue = "not " + filterValue;
}
filters.add(filterValue);
}
}
if (filters.length() > 2) {
query = query + filters;
}
}
}
query = query + ")";
}
return query;
}
private ArrayList<String> createQueryList(String expression) {
ArrayList<String> expressionList = new ArrayList();
Matcher matcher = expressionListPattern.matcher(expression);
Pattern lParenMatcher = Pattern.compile("^\\(");
Pattern rParenMatcher = Pattern.compile("\\)$");
int lastPos = 0;
while (matcher.find()) {
if (matcher.group(1) != null) {
String subexpression = expression.substring(lastPos, matcher.start()).trim();
if (lParenMatcher.matcher(subexpression).find()) {
// Strip left parenthesis off expression, to be added back later (similar to how operators are handled)
expressionList.add("(");
expressionList.add(subexpression.substring(1,subexpression.length()));
}
else if (rParenMatcher.matcher(subexpression).find()) {
// Strip right parenthesis off expression, to be added back later (similar to how operators are handled)
expressionList.add(subexpression.substring(0, subexpression.length() - 1));
expressionList.add(")");
}
else {
expressionList.add(subexpression);
}
expressionList.add(matcher.group(1));
lastPos = matcher.end();
}
}
expressionList.add(expression.substring(lastPos).trim());
return expressionList;
}
public void initVariablesMap(List<DatadogTemplateVariable> templateVariables) {
variablesMap = new HashMap();
if (templateVariables != null) {
for (DatadogTemplateVariable templateVariable : templateVariables) {
String name = templateVariable.getName();
String prefix = templateVariable.getPrefix();
String _default = templateVariable.get_default();
if (_default == null) {
_default = "";
}
if (!_default.startsWith(":")) {
Variable variable = new Variable();
variable.setName(name);
if (prefix == null || prefix.equals("")) {
variable.setGeneric(true);
if (_default.equals("*")) {
_default = "";
}
} else if (dropTags.contains(prefix)) {
continue;
} else {
variable.setTagName(prefix);
}
variable.setValue(_default.replace(":", "="));
variablesMap.put(name, variable);
}
}
}
}
public HashMap<String, Variable> getVariablesMap() {
return variablesMap;
}
}