-
Notifications
You must be signed in to change notification settings - Fork 5
/
MicrosoftTeamsAnomalyFunction.java
151 lines (111 loc) · 5.2 KB
/
MicrosoftTeamsAnomalyFunction.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
package com.takipi.udf.microsoftteams;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.takipi.api.client.ApiClient;
import com.takipi.api.client.data.view.SummarizedView;
import com.takipi.api.client.request.event.EventsVolumeRequest;
import com.takipi.api.client.result.event.EventsResult;
import com.takipi.api.client.util.validation.ValidationUtil;
import com.takipi.api.core.url.UrlClient;
import com.takipi.udf.ContextArgs;
import com.takipi.udf.microsoftteams.MicrosoftTeamsUtil.TimeSlot;
import com.takipi.udf.util.TestUtil;
public class MicrosoftTeamsAnomalyFunction {
public static String validateInput(String rawInput) {
return getInput(rawInput).toString();
}
public static void execute(String rawContextArgs, String rawInput) {
try {
executeImplementation(rawContextArgs, rawInput);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void executeImplementation(String rawContextArgs, String rawInput) {
MicrosoftTeamsUtil.logUDFInput(rawContextArgs, rawInput);
MicrosoftTeamsAnomalyInput input = getInput(rawInput);
ContextArgs args = (new Gson()).fromJson(rawContextArgs, ContextArgs.class);
if (!args.validate()) {
throw new IllegalArgumentException("Bad context args: " + rawContextArgs);
}
ApiClient apiClient = args.apiClient();
TimeSlot timeSlot = MicrosoftTeamsUtil.getTimeSlot(input.timespan);
DateTimeFormatter fmt = ISODateTimeFormat.dateTime().withZoneUTC();
SummarizedView view = MicrosoftTeamsUtil.getSummarizedView(rawContextArgs, args, apiClient);
System.out.println("Got viewId");
EventsVolumeRequest eventsVolumeRequest = EventsVolumeRequest.newBuilder().setServiceId(args.serviceId)
.setViewId(view.id).setFrom(timeSlot.from.toString(fmt)).setTo(timeSlot.to.toString(fmt))
.setVolumeType(ValidationUtil.VolumeType.all).build();
UrlClient.Response<EventsResult> volumeResponse = apiClient.get(eventsVolumeRequest);
System.out.println("Got events volume data ");
String viewErrorsLink = getViewLink(args, view.name);
System.out.println("Got View link");
long hitSum = getHitSum(volumeResponse);
if ((input.threshold != 0) && (input.threshold > hitSum)) {
return;
}
MicrosoftTeamsAnomalyRequest microsoftTeamsAnomalyRequest = MicrosoftTeamsAnomalyRequest.newBuilder()
.setUrl(input.url).setEnvironmentsName(MicrosoftTeamsUtil.getEnvironmentName(apiClient, args.serviceId))
.setManageSettingsLink(getManageSettingsLink(args)).setViewErrorsLink(viewErrorsLink)
.setThresholdCount(String.valueOf(input.threshold))
.setEventsVolume(volumeResponse.data.events, apiClient, args, timeSlot).setTimeSlot(timeSlot.toString())
.setTotalEventsOccurred(String.valueOf(hitSum)).setViewName(view.name).build();
UrlClient.Response<String> post = SimpleUrlClient.newBuilder().build().post(microsoftTeamsAnomalyRequest);
System.out.println("Post Microsoft Teams Webhook Anomaly request");
if (post.isBadResponse()) {
throw new IllegalStateException("Can't send anomaly card to " + input.url);
}
}
private static String getManageSettingsLink(ContextArgs args) {
return args.appHost + "/index.html?key=" + args.serviceId + "&nav=alertset";
}
private static String getViewLink(ContextArgs args, String viewName) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(args.appHost).append("/index.html?key=").append(args.serviceId)
.append("&timeframe=last-24-hours");
try {
stringBuilder.append("&view=").append(URLEncoder.encode(viewName, StandardCharsets.UTF_8.toString()));
} catch (Exception e) {
System.out.println("Couldn't encode " + viewName);
}
return stringBuilder.toString();
}
private static long getHitSum(UrlClient.Response<EventsResult> volumeResponse) {
long hitSum = 0;
if ((volumeResponse.data) != null && (volumeResponse.data.events != null)) {
hitSum = volumeResponse.data.events.stream().map(v -> v.stats.hits).reduce(0L, (sum, c) -> sum + c);
}
return hitSum;
}
private static MicrosoftTeamsAnomalyInput getInput(String rawInput) {
System.out.println("rawInput:" + rawInput);
if (Strings.isNullOrEmpty(rawInput))
throw new IllegalArgumentException("Input is empty");
MicrosoftTeamsAnomalyInput input;
try {
input = MicrosoftTeamsAnomalyInput.of(rawInput);
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
if (input.timespan <= 0) {
throw new IllegalArgumentException("'timespan' must be positive");
}
if (input.threshold < 0) {
throw new IllegalArgumentException("'threshold' must be positive or zero");
}
input.checkUrl();
return input;
}
// A sample program on how to programmatically activate
public static void main(String[] args) {
ContextArgs contextArgs = TestUtil.getDefaultContextArgsBuilder().setApiKey("api_token").setServiceId("SXXXXX")
.build();
String rawContextArgs = new Gson().toJson(contextArgs);
String rawInput = "url=https://outlook.office.com/webhook/..." + "\n" + "timespan=5" + "\n" + "threshold = 1";
MicrosoftTeamsAnomalyFunction.execute(rawContextArgs, rawInput);
}
}