-
Notifications
You must be signed in to change notification settings - Fork 183
/
appdynamics_provider.py
339 lines (300 loc) · 11.2 KB
/
appdynamics_provider.py
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
"""
AppDynamics Provider is a class that allows to install webhooks in AppDynamics.
"""
import dataclasses
import json
import tempfile
from pathlib import Path
from typing import List, Optional
from urllib.parse import urlencode, urljoin
import pydantic
import requests
from keep.api.models.alert import AlertDto, AlertSeverity
from keep.contextmanager.contextmanager import ContextManager
from keep.providers.base.base_provider import BaseProvider
from keep.providers.models.provider_config import ProviderConfig, ProviderScope
class ResourceAlreadyExists(Exception):
def __init__(self, *args):
super().__init__(*args)
@pydantic.dataclasses.dataclass
class AppdynamicsProviderAuthConfig:
"""
AppDynamics authentication configuration.
"""
appDynamicsUsername: str = dataclasses.field(
metadata={
"required": True,
"description": "AppDynamics Username",
"hint": "Your Username",
},
)
appDynamicsAccountName: str = dataclasses.field(
metadata={
"required": True,
"description": "AppDynamics Account Name",
"hint": "AppDynamics Account Name",
},
)
appDynamicsPassword: str = dataclasses.field(
metadata={
"required": True,
"description": "Password",
"hint": "Password associated with yur account",
"sensitive": True,
},
)
appId: str = dataclasses.field(
metadata={
"required": True,
"description": "AppDynamics appId",
"hint": "the app instance in which the webhook should be installed",
},
)
host: str = dataclasses.field(
metadata={
"required": True,
"description": "AppDynamics host",
"hint": "e.g. https://baseball202404101029219.saas.appdynamics.com",
},
)
class AppdynamicsProvider(BaseProvider):
"""Install Webhooks and receive alerts from AppDynamics."""
PROVIDER_DISPLAY_NAME = "AppDynamics"
PROVIDER_SCOPES = [
ProviderScope(
name="authenticated",
description="User is Authorized",
mandatory=True,
mandatory_for_webhook=True,
alias="Rules Reader",
),
ProviderScope(
name="administrator",
description="Administrator privileges",
mandatory=True,
mandatory_for_webhook=True,
alias="Rules Reader",
),
]
SEVERITIES_MAP = {
"ERROR": AlertSeverity.CRITICAL,
"WARN": AlertSeverity.WARNING,
"INFO": AlertSeverity.INFO,
}
def __init__(
self, context_manager: ContextManager, provider_id: str, config: ProviderConfig
):
super().__init__(context_manager, provider_id, config)
def dispose(self):
"""
Dispose the provider.
"""
pass
def validate_config(self):
"""
Validates required configuration for AppDynamics provider.
"""
self.authentication_config = AppdynamicsProviderAuthConfig(
**self.config.authentication
)
if not self.authentication_config.host.startswith(
"https://"
) and not self.authentication_config.host.startswith("http://"):
self.authentication_config.host = (
f"https://{self.authentication_config.host}"
)
def __get_url(self, paths: List[str] = [], query_params: dict = None, **kwargs):
"""
Helper method to build the url for AppDynamics api requests.
Example:
paths = ["issue", "createmeta"]
query_params = {"projectKeys": "key1"}
url = __get_url("test", paths, query_params)
# url = https://baseballxyz.saas.appdynamics.com/rest/api/2/issue/createmeta?projectKeys=key1
"""
url = urljoin(
f"{self.authentication_config.host}/controller",
"/".join(str(path) for path in paths),
)
# add query params
if query_params:
url = f"{url}?{urlencode(query_params)}"
return url
def validate_scopes(self) -> dict[str, bool | str]:
authenticated = False
administrator = "Missing Administrator Privileges"
self.logger.info("Validating AppDynamics Scopes")
response = requests.get(
url=self.__get_url(
paths=[
"controller/api/rbac/v1/users/name",
self.authentication_config.appDynamicsUsername,
]
),
auth=self.__get_auth(),
)
if response.ok:
authenticated = True
response = response.json()
for role in response["roles"]:
if (
role["name"] == "Account Administrator"
or role["name"] == "Administrator"
):
administrator = True
self.logger.info(
"All scopes validated successfully for AppDynamics"
)
break
else:
self.logger.error(
"Error while validating scopes for AppDynamics", extra=response.json()
)
return {"authenticated": authenticated, "administrator": administrator}
def __get_auth(self) -> tuple[str, str]:
return (
f"{self.authentication_config.appDynamicsUsername}@{self.authentication_config.appDynamicsAccountName}",
self.authentication_config.appDynamicsPassword,
)
def __create_http_response_template(self, keep_api_url: str, api_key: str):
keep_api_host, keep_api_path = keep_api_url.rsplit("/", 1)
# The httpactiontemplate.json is a template/skeleton for creating a new HTTP Request Action in AppDynamics
temp = tempfile.NamedTemporaryFile(mode="w+t", delete=True)
template = json.load(open(rf"{Path(__file__).parent}/httpactiontemplate.json"))
template[0]["host"] = keep_api_host.lstrip("http://").lstrip("https://")
template[0]["path"], template[0]["query"] = keep_api_path.split("?")
template[0]["path"] = "/" + template[0]["path"].rstrip("/")
template[0]["headers"][0]["value"] = api_key
temp.write(json.dumps(template))
temp.seek(0)
res = requests.post(
self.__get_url(paths=["controller/actiontemplate/httprequest"]),
files={"template": temp},
auth=self.__get_auth(),
)
res = res.json()
temp.close()
if res["success"] == "True":
self.logger.info("HTTP Response template Successfully Created")
else:
self.logger.info("HTTP Response template creation failed", extra=res)
if "already exists" in res["errors"][0]:
self.logger.info(
"HTTP Response template creation failed as it already exists",
extra=res,
)
raise ResourceAlreadyExists()
raise Exception(res["errors"])
def __create_action(self):
response = requests.post(
url=self.__get_url(
paths=[
"alerting/rest/v1/applications",
self.authentication_config.appId,
"actions",
]
),
auth=self.__get_auth(),
json={
"actionType": "HTTP_REQUEST",
"name": "KeepAction",
"httpRequestTemplateName": "KeepWebhook",
"customTemplateVariables": [],
},
)
if response.ok:
self.logger.info("Action Created")
else:
response = response.json()
self.logger.info("Action Creation failed")
if "already exists" in response["message"]:
raise ResourceAlreadyExists()
raise Exception(response["message"])
def setup_webhook(
self, tenant_id: str, keep_api_url: str, api_key: str, setup_alerts: bool = True
):
try:
self.__create_http_response_template(
keep_api_url=keep_api_url, api_key=api_key
)
except ResourceAlreadyExists:
self.logger.info("Template already exists, proceeding with webhook setup")
except Exception as e:
raise e
try:
self.__create_action()
except ResourceAlreadyExists:
self.logger.info("Template already exists, proceeding with webhook setup")
except Exception as e:
raise e
# Listing all policies in the specified app
policies_response = requests.get(
url=self.__get_url(
paths=[
"alerting/rest/v1/applications",
self.authentication_config.appId,
"policies",
]
),
auth=self.__get_auth(),
)
policies = policies_response.json()
policy_config = {
"actionName": "KeepAction",
"actionType": "HTTP_REQUEST",
}
for policy in policies:
curr_policy = requests.get(
url=self.__get_url(
paths=[
"alerting/rest/v1/applications",
self.authentication_config.appId,
"policies",
policy["id"],
]
),
auth=self.__get_auth(),
).json()
if policy_config not in curr_policy["actions"]:
curr_policy["actions"].append(policy_config)
if "executeActionsInBatch" not in curr_policy:
curr_policy["executeActionsInBatch"] = True
new_events_dictionary = {}
for event_key, event_value in curr_policy["events"].items():
if event_value is None or len(event_value) == 0:
continue
else:
new_events_dictionary[event_key] = event_value
curr_policy["events"] = new_events_dictionary
request = requests.put(
url=self.__get_url(
paths=[
"/alerting/rest/v1/applications",
self.authentication_config.appId,
"policies",
policy["id"],
]
),
auth=self.__get_auth(),
json=curr_policy,
)
if not request.ok:
self.logger.info("Failed to add Webhook")
raise Exception("Could not create webhook")
self.logger.info("Webhook created")
@staticmethod
def _format_alert(
event: dict,
provider_instance: Optional["AppdynamicsProvider"] = None,
) -> AlertDto:
return AlertDto(
id=event["id"],
name=event["name"],
severity=AppdynamicsProvider.SEVERITIES_MAP.get(event["severity"]),
lastReceived=event["lastReceived"],
message=event["message"],
description=event["description"],
event_id=event["event_id"],
url=event["url"],
source=["appdynamics"],
)