-
Notifications
You must be signed in to change notification settings - Fork 5
/
SeverityFunction.java
318 lines (244 loc) · 11.4 KB
/
SeverityFunction.java
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
package com.takipi.udf.severity;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.takipi.api.client.ApiClient;
import com.takipi.api.client.data.category.Category;
import com.takipi.api.client.data.event.Action;
import com.takipi.api.client.data.view.SummarizedView;
import com.takipi.api.client.request.event.EventActionsRequest;
import com.takipi.api.client.request.label.BatchModifyLabelsRequest;
import com.takipi.api.client.result.EmptyResult;
import com.takipi.api.client.result.event.EventActionsResult;
import com.takipi.api.client.result.event.EventResult;
import com.takipi.api.client.result.event.EventsResult;
import com.takipi.api.client.util.category.CategoryUtil;
import com.takipi.api.client.util.label.LabelUtil;
import com.takipi.api.client.util.regression.RateRegression;
import com.takipi.api.client.util.regression.RegressionInput;
import com.takipi.api.client.util.regression.RegressionResult;
import com.takipi.api.client.util.regression.RegressionUtil;
import com.takipi.api.client.util.view.ViewUtil;
import com.takipi.api.core.url.UrlClient.Response;
import com.takipi.common.util.Pair;
import com.takipi.udf.ContextArgs;
import com.takipi.udf.input.Input;
public class SeverityFunction {
public static String validateInput(String rawInput) {
return parseSeverityInput(rawInput).toString();
}
static SeverityInput parseSeverityInput(String rawInput) {
System.out.println("validateInput rawInput:" + rawInput);
if (Strings.isNullOrEmpty(rawInput)) {
throw new IllegalArgumentException("Input is empty");
}
SeverityInput input;
try {
input = SeverityInput.of(rawInput);
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
if (input.activeTimespan <= 0) {
throw new IllegalArgumentException("'activeTimespan' must be positive'");
}
if (input.baseTimespan <= 0) {
throw new IllegalArgumentException("'timespan' must be positive");
}
if (input.regressionDelta <= 0) {
throw new IllegalArgumentException("'regressionDelta' must be positive");
}
if (input.criticalRegressionDelta < 0) {
throw new IllegalArgumentException("'criticalRegressionDelta' can't be negative");
}
if (input.newEventslabel == null) {
throw new IllegalArgumentException("'newEventslabel' must exist");
}
if (input.regressedEventsLabel == null) {
throw new IllegalArgumentException("'regressedEventsLabel' must exist");
}
return input;
}
public static void execute(String rawContextArgs, String rawInput) {
System.out.println("execute:" + rawContextArgs);
ContextArgs args = (new Gson()).fromJson(rawContextArgs, ContextArgs.class);
if (!args.viewValidate()) {
throw new IllegalArgumentException("Invalid context args - " + rawContextArgs);
}
SeverityInput input = parseSeverityInput(rawInput);
setupSeverityViews(args, input);
System.out.println("Calculating regressions\n");
RegressionInput regressionInput = new RegressionInput();
regressionInput.serviceId = args.serviceId;
regressionInput.viewId = args.viewId;
regressionInput.activeTimespan = input.activeTimespan;
regressionInput.baselineTimespan = input.baseTimespan;
regressionInput.minVolumeThreshold = input.minVolumeThreshold;
regressionInput.minErrorRateThreshold = input.minErrorRateThreshold;
regressionInput.regressionDelta = input.regressionDelta;
regressionInput.criticalRegressionDelta = input.criticalRegressionDelta;
regressionInput.applySeasonality = input.applySeasonality;
regressionInput.criticalExceptionTypes = input.criticalExceptionTypes;
RateRegression rateRegression = RegressionUtil.calculateRateRegressions(args.apiClient(), regressionInput,
System.out, false);
Map<String, EventResult> allNewAndCritical = Maps.newHashMap();
if (input.newEventsView != null) {
allNewAndCritical.putAll(rateRegression.getExceededNewEvents());
allNewAndCritical.putAll(rateRegression.getCriticalNewEvents());
applySeverityLabels(args, input.newEventslabel, input.newEventsView, input.labelRetention,
Lists.newArrayList(allNewAndCritical.values()));
}
if (input.regressedEventsView != null) {
Collection<RegressionResult> activeRegressions = rateRegression.getAllRegressions().values();
Collection<EventResult> activeRegressionEvents = Lists.newArrayListWithCapacity(activeRegressions.size());
for (RegressionResult activeRegression : activeRegressions) {
activeRegressionEvents.add(activeRegression.getEvent());
}
applySeverityLabels(args, input.regressedEventsLabel, input.regressedEventsView, input.labelRetention,
activeRegressionEvents);
}
}
private static void setupSeverityViews(ContextArgs args, SeverityInput input) {
String categoryId = createSeverityCategory(args, input);
LabelUtil.createLabelsIfNotExists(args.apiClient(), args.serviceId,
new String[] { input.newEventslabel, input.regressedEventsLabel });
Collection<Pair<String, String>> views = Lists.newArrayList();
if (input.newEventsView != null) {
views.add(Pair.of(input.newEventsView, input.newEventslabel));
}
if (input.regressedEventsView != null) {
views.add(Pair.of(input.regressedEventsView, input.regressedEventsLabel));
}
if (views.size() > 0) {
ViewUtil.createLabelViewsIfNotExists(args.apiClient(), args.serviceId, views, true, categoryId);
}
}
private static String createSeverityCategory(ContextArgs args, SeverityInput input) {
String result;
Category category = CategoryUtil.getServiceCategoryByName(args.apiClient(), args.serviceId, input.category);
if (category == null) {
result = CategoryUtil.createCategory(input.category, args.serviceId, args.apiClient());
System.out.println("Created category " + result + " for " + input.category);
} else {
result = category.id;
}
return result;
}
private static void applySeverityLabels(ContextArgs args, String label, String viewName, int labelRetention,
Collection<EventResult> targetEvents) {
ApiClient apiClient = args.apiClient();
Map<String, EventResult> newlyLabeledEvents = Maps.newHashMap();
boolean modified = false;
BatchModifyLabelsRequest.Builder builder = BatchModifyLabelsRequest.newBuilder().setServiceId(args.serviceId)
.setHandleSimilarEvents(false);
for (EventResult event : targetEvents) {
boolean hasLabel = (event.labels != null) && (event.labels.contains(label));
if (!hasLabel) {
modified = true;
newlyLabeledEvents.put(event.id, event);
builder.addLabelModifications(event.id, Collections.singleton(label), Collections.emptyList());
System.out.println("Applying label " + label + " to " + event.id);
} else {
System.out.println("Event " + event.id + " already has label " + label);
}
}
DateTime now = DateTime.now();
DateTime retentionTime = now.minusMinutes(labelRetention * 2);
SummarizedView view = ViewUtil.getServiceViewByName(apiClient, args.serviceId, viewName);
if (view == null) {
System.out.println("Could not get view " + viewName);
return;
}
EventsResult previousEvents = ViewUtil.getEventsVolume(apiClient, args.serviceId, view.id, retentionTime,
now);
DateTime retentionWindow = DateTime.now().minusMinutes(labelRetention);
if ((previousEvents != null) && (previousEvents.events != null)) {
for (int i = 0; i < previousEvents.events.size(); i++) {
EventResult event = previousEvents.events.get(i);
if (targetEvents.contains(event)) {
continue;
}
// if this is a new severe issue, no need to cleanup its label
if (newlyLabeledEvents.containsKey(event.id)) {
continue;
}
// if this event wasn't prev marked as severe - skip
if ((event.labels == null) || (!event.labels.contains(label))) {
continue;
}
// get the actions for this event. Let's see when was that event marked severe
EventActionsRequest eventActionsRequest = EventActionsRequest.newBuilder().setServiceId(args.serviceId)
.setEventId(event.id).build();
Response<EventActionsResult> eventsActionsResponse = apiClient.get(eventActionsRequest);
if (eventsActionsResponse.isBadResponse()) {
System.err.println("Can't create events actions for event " + event.id);
}
if (eventsActionsResponse.data.event_actions == null) {
continue;
}
boolean keepLabel = false;
for (Action action : eventsActionsResponse.data.event_actions) {
if (!label.equals(action.data)) {
continue;
}
// we should add a constant for this in the Java API wrapper
if (!"ADD_LABEL".equals(action.action.toUpperCase())) {
continue;
}
DateTime labelAddTime = ISODateTimeFormat.dateTimeParser().parseDateTime(action.timestamp);
// lets see if the label was added after the retention window, is so - keep
if (labelAddTime.isAfter(retentionWindow)) {
keepLabel = true;
System.out.println("Keeping label " + label + " on " + event.id);
break;
}
}
if (!keepLabel) {
modified = true;
System.out.println("Removing label " + label + " from " + event.id);
builder.addLabelModifications(event.id, Collections.emptyList(), Collections.singleton(label));
}
}
}
if (!modified) {
return;
}
Response<EmptyResult> response = apiClient.post(builder.build());
if (!response.isOK()) {
System.out.println("Error adding / removing labels " + response.responseCode);
}
}
static class SeverityInput extends Input {
public int activeTimespan; // the time window (min) that we compare the baseline to
public int baseTimespan; // the time window (min) to compare the last <activeTimespan> against
public double regressionDelta; // a change in % that would be considered a regression
public double criticalRegressionDelta; // a change in % that would be considered a critical regression
public boolean applySeasonality; // whether or not to apply a seasonality algorithm.
public List<String> criticalExceptionTypes; // comma delimited list of exception types that are severe by def
public double minErrorRateThreshold; // min ER that a regression, new + non-critical event must exceed
public int minVolumeThreshold; // min volume that a regression, new + non-critical event must exceed
public String category; // The category in which to place views
public String newEventslabel; // how to label new issues
public String regressedEventsLabel; // how to label regressions
public String newEventsView; // view containing new issues
public String regressedEventsView; // view containing regressions
public int labelRetention; // how long (min) should thse labels "stick" to an event
private SeverityInput(String raw) {
super(raw);
}
static SeverityInput of(String raw) {
return new SeverityInput(raw);
}
@Override
public String toString() {
return String.format("Severe(Window = %d, Baseline = %d, Thresh = %d, Rate = %.2f)", activeTimespan,
baseTimespan, minVolumeThreshold, minErrorRateThreshold);
}
}
}