-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_alerts.py
196 lines (160 loc) · 7.55 KB
/
create_alerts.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
import requests
import jsons
from xml.dom import minidom
import sys
import logging
from datetime import datetime
from pytz import timezone
import pytz
from pathlib import Path
import time
import json
from jproperties import Properties
alert_list = []
projects_dict = {}
headers = {}
configs = Properties()
script_report = {}
def do_setup():
global configs
global headers
global current_datetime
required_config_keys = ["ORG_NAME", "AUTH_KEY", "CRITICAL", "WARNING", "ALERT_RULE_SUFFIX"]
try:
# Init logger
current_datetime = datetime.now().strftime('%m-%d-%Y_%I:%M:%S %Z').strip()
logging.basicConfig(filename=f'alert_logfile_{current_datetime}.log', format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %I:%M:%S')
logging.getLogger().setLevel(logging.ERROR)
logging.getLogger().setLevel(logging.INFO)
# Read configuration
with open('config.properties', 'rb') as config_file:
configs.load(config_file)
keys = configs.__dict__
keys = keys['_key_order']
diff = [i for i in required_config_keys + keys if i not in required_config_keys or i not in keys]
result = len(diff) == 0
if not result:
#print(diff)
logging.error(f'These config {len(diff)} key(s) are missing from config file: {diff[:5]}')
sys.exit()
for key, value in configs.items():
if(value.data == ''):
logging.error('Value for ' + key + ' is missing.')
sys.exit()
# Init request headers
headers = {'Authorization': "Bearer " + configs.get("AUTH_KEY").data, 'Content-Type' : 'application/json'}
except Exception as e:
print(f'do_setup: failed to setup - {e}')
sys.exit()
def get_alerts():
global alert_list
global configs
global headers
try:
response = requests.get(f'https://sentry.io/api/0/organizations/{configs.get("ORG_NAME").data}/alert-rules/', headers = headers)
store_alerts(response.json())
while response.links["next"]["results"] == "true":
response = requests.get(response.links["next"]["url"], headers = headers)
store_alerts(response.json())
except Exception as e:
print(f'get_alerts: failed to call alert rules api - {e}')
sys.exit()
def store_alerts(json_data):
for alert in json_data:
if "name" in alert:
alert_list.append(alert["name"])
else:
logging.error('store_alerts: could not get existing alert name')
def get_projects():
global headers
try:
response = requests.get(f' https://sentry.io/api/0/organizations/{configs.get("ORG_NAME").data}/projects/', headers = headers)
store_projects(response.json())
while response.links["next"]["results"] == "true":
response = requests.get(response.links["next"]["url"], headers = headers)
store_projects(response.json())
except Exception as e:
logging.error(f'get_project: unable to do get request - {e}')
sys.exit()
def store_projects(json_data):
global projects_dict
for project in json_data:
try:
project_name = project["slug"]
teams = project["teams"]
projects_dict[project_name] = list()
for team in teams:
team_id = team["id"]
projects_dict[project_name].append(team_id)
except Exception as e:
logging.error(f'create_project: could not get existing project names - {e}')
def create_alerts():
global headers
global projects_dict
global alert_list
global script_report
proj_team_list = []
team_list = []
script_report = {"success": 0, "failed": 0, "exists": 0}
alert_rule_suffix = configs.get("ALERT_RULE_SUFFIX").data
print('about to create alerts..this may take some time. Please wait :)')
for proj_name, teams in projects_dict.items():
alert_name = proj_name.lower() + alert_rule_suffix
if len(teams) == 0:
script_report["failed"] += 1
logging.error(f'create_alert: failed to create alert for project: {proj_name} - No teams assigned to project')
elif alert_name not in alert_list:
try:
json_data = build_alert_json(proj_name.lower(), alert_name, teams)
response = requests.post(
f'https://sentry.io/api/0/projects/{configs.get("ORG_NAME").data}/{proj_name}/alert-rules/',
headers = headers,
data=json_data)
if(response.status_code in [200, 201]):
script_report["success"] += 1
logging.info('create_alert: Successfully created the metric alert ' + alert_name + ' for project: ' + proj_name)
elif (response.status_code == 400):
script_report["failed"] += 1
logging.error('create_alert: could not create alert for project: ' + proj_name)
logging.error(str(response.json()) + proj_name)
elif (response.status_code == 403):
logging.error('create_alerts: received the following status code: ' + str(response.status_code) + ' \nYou may be using your user level token without the necessary permissions. \nPlease assign the AUTH_KEY to your org level token and refer to the README on how to create one.')
sys.exit()
else:
script_report["failed"] += 1
logging.error('create_alert: received the following status code: ' + str(response.status_code) + ' for project: ' + proj_name)
except Exception as e:
script_report["failed"] += 1
logging.error(f'create_alert: failed to create alert for project : {proj_name} - {e}')
time.sleep(3) # setting to 3 seconds to prevent a potential 429 response
else:
script_report["exists"] += 1
logging.info('create_alert: alert already exists for project ' + proj_name + '!')
def build_alert_json(proj_name_lower, alert_name, teams):
critical_actions = []
warning_actions = []
alert_payload_json = jsons.dumps({"dataset":"events","eventTypes":["error","default"],"aggregate":"count()","query":"","timeWindow":60,"triggers":[{"label":"critical","alertThreshold":int(configs.get("CRITICAL").data),"actions":[]},{"label":"warning","alertThreshold":int(configs.get("WARNING").data),"actions":[]}],"projects" : [proj_name_lower],"environment": None ,"resolveThreshold": None,"thresholdType":0,"owner": None,"name":alert_name})
json_data = json.loads(alert_payload_json)
for team_id in teams:
action = json.loads(jsons.dumps({"type":"email", "targetType":"team", "targetIdentifier": team_id, "options":None}))
critical_actions.append(action)
warning_actions.append(action)
json_data["triggers"][0]["actions"] = critical_actions
json_data["triggers"][1]["actions"] = warning_actions
json_data = json.dumps(json_data)
return json_data
def main(argv):
global alert_list
global configs
global headers
global script_report
global current_datetime
do_setup()
print(f"Please Note: Check log file alert_logfile_{current_datetime}.log for details.")
get_alerts()
get_projects()
create_alerts()
# Print final script status
print("Script report: ", script_report)
if __name__ == '__main__':
main(sys.argv[1:])