/
monitor.py
366 lines (320 loc) · 14.8 KB
/
monitor.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# stdlib
import argparse
import json
# 3p
from datadog.util.format import pretty_json
# datadog
from datadog import api
from datadog.dogshell.common import report_errors, report_warnings, print_err
class MonitorClient(object):
@classmethod
def setup_parser(cls, subparsers):
parser = subparsers.add_parser('monitor', help="Create, edit, and delete monitors")
parser.add_argument('--string_ids', action='store_true', dest='string_ids',
help="Represent monitor IDs as strings instead of ints in JSON")
verb_parsers = parser.add_subparsers(title='Verbs', dest='verb')
verb_parsers.required = True
post_parser = verb_parsers.add_parser('post', help="Create a monitor")
post_parser.add_argument('type', help="type of the monitor, e.g."
"'metric alert' 'service check'")
post_parser.add_argument('query', help="query to notify on with syntax varying "
"depending on what type of monitor you are creating")
post_parser.add_argument('--name', help="name of the alert", default=None)
post_parser.add_argument('--message', help="message to include with notifications"
" for this monitor", default=None)
post_parser.add_argument('--tags', help="comma-separated list of tags", default=None)
post_parser.add_argument('--options', help="json options for the monitor", default=None)
post_parser.set_defaults(func=cls._post)
file_post_parser = verb_parsers.add_parser('fpost', help="Create a monitor from file")
file_post_parser.add_argument('file', help='json file holding all details',
type=argparse.FileType('r'))
file_post_parser.set_defaults(func=cls._file_post)
update_parser = verb_parsers.add_parser('update', help="Update existing monitor")
update_parser.add_argument('monitor_id', help="monitor to replace with the new definition")
update_parser.add_argument(
'type',
nargs='?',
help="[Deprecated] optional argument preferred"
"type of the monitor, e.g. 'metric alert' 'service check'",
default=None
)
update_parser.add_argument(
'query',
nargs='?',
help="[Deprecated] optional argument preferred"
"query to notify on with syntax varying depending on monitor type",
default=None
)
update_parser.add_argument('--type', help="type of the monitor, e.g. "
"'metric alert' 'service check'", default=None, dest='type_opt')
update_parser.add_argument('--query', help="query to notify on with syntax varying"
" depending on monitor type", default=None, dest='query_opt')
update_parser.add_argument('--name', help="name of the alert", default=None)
update_parser.add_argument('--message', help="message to include with "
"notifications for this monitor", default=None)
update_parser.add_argument('--options', help="json options for the monitor", default=None)
update_parser.set_defaults(func=cls._update)
file_update_parser = verb_parsers.add_parser('fupdate', help="Update existing"
" monitor from file")
file_update_parser.add_argument('file', help='json file holding all details',
type=argparse.FileType('r'))
file_update_parser.set_defaults(func=cls._file_update)
show_parser = verb_parsers.add_parser('show', help="Show a monitor definition")
show_parser.add_argument('monitor_id', help="monitor to show")
show_parser.set_defaults(func=cls._show)
show_all_parser = verb_parsers.add_parser('show_all', help="Show a list of all monitors")
show_all_parser.add_argument(
'--group_states', help="comma separated list of group states to filter by"
"(choose one or more from 'all', 'alert', 'warn', or 'no data')"
)
show_all_parser.add_argument('--name', help="string to filter monitors by name")
show_all_parser.add_argument(
'--tags', help="comma separated list indicating what tags, if any, "
"should be used to filter the list of monitors by scope (e.g. 'host:host0')"
)
show_all_parser.add_argument(
'--monitor_tags', help="comma separated list indicating what service "
"and/or custom tags, if any, should be used to filter the list of monitors"
)
show_all_parser.set_defaults(func=cls._show_all)
delete_parser = verb_parsers.add_parser('delete', help="Delete a monitor")
delete_parser.add_argument('monitor_id', help="monitor to delete")
delete_parser.set_defaults(func=cls._delete)
mute_all_parser = verb_parsers.add_parser('mute_all', help="Globally mute "
"monitors (downtime over *)")
mute_all_parser.set_defaults(func=cls._mute_all)
unmute_all_parser = verb_parsers.add_parser('unmute_all', help="Globally unmute "
"monitors (cancel downtime over *)")
unmute_all_parser.set_defaults(func=cls._unmute_all)
mute_parser = verb_parsers.add_parser('mute', help="Mute a monitor")
mute_parser.add_argument('monitor_id', help="monitor to mute")
mute_parser.add_argument('--scope', help="scope to apply the mute to,"
" e.g. role:db (optional)", default=[])
mute_parser.add_argument('--end', help="POSIX timestamp for when"
" the mute should end (optional)", default=None)
mute_parser.set_defaults(func=cls._mute)
unmute_parser = verb_parsers.add_parser('unmute', help="Unmute a monitor")
unmute_parser.add_argument('monitor_id', help="monitor to unmute")
unmute_parser.add_argument('--scope', help="scope to unmute (must be muted), "
"e.g. role:db", default=[])
unmute_parser.add_argument('--all_scopes', help="clear muting across all scopes",
action='store_true')
unmute_parser.set_defaults(func=cls._unmute)
can_delete_parser = verb_parsers.add_parser('can_delete',
help="Check if you can delete some monitors")
can_delete_parser.add_argument('monitor_ids',
help="monitors to check if they can be deleted")
can_delete_parser.set_defaults(func=cls._can_delete)
validate_parser = verb_parsers.add_parser('validate',
help="Validates if a monitor definition is correct")
validate_parser.add_argument('type', help="type of the monitor, e.g."
"'metric alert' 'service check'")
validate_parser.add_argument('query', help="the monitor query")
validate_parser.add_argument('--name', help="name of the alert", default=None)
validate_parser.add_argument('--message', help="message to include with notifications"
" for this monitor", default=None)
validate_parser.add_argument('--tags', help="comma-separated list of tags", default=None)
validate_parser.add_argument('--options', help="json options for the monitor", default=None)
validate_parser.set_defaults(func=cls._validate)
@classmethod
def _post(cls, args):
api._timeout = args.timeout
format = args.format
options = None
if args.options is not None:
options = json.loads(args.options)
if args.tags:
tags = sorted(set([t.strip() for t in args.tags.split(',') if t.strip()]))
else:
tags = None
res = api.Monitor.create(type=args.type, query=args.query, name=args.name,
message=args.message, tags=tags, options=options)
report_warnings(res)
report_errors(res)
if format == 'pretty':
print(pretty_json(res))
else:
print(json.dumps(res))
@classmethod
def _file_post(cls, args):
api._timeout = args.timeout
format = args.format
monitor = json.load(args.file)
res = api.Monitor.create(type=monitor['type'], query=monitor['query'],
name=monitor['name'], message=monitor['message'],
options=monitor['options'])
report_warnings(res)
report_errors(res)
if format == 'pretty':
print(pretty_json(res))
else:
print(json.dumps(res))
@classmethod
def _update(cls, args):
api._timeout = args.timeout
format = args.format
to_update = {}
if args.type:
if args.type_opt:
msg = 'Duplicate arguments for `type`. Using optional value --type'
print_err("WARNING: {}".format(msg))
else:
to_update['type'] = args.type
msg = "[DEPRECATION] `type` is no longer required to `update` and may be omitted"
print_err("WARNING: {}".format(msg))
if args.query:
if args.query_opt:
msg = 'Duplicate arguments for `query`. Using optional value --query'
print_err("WARNING: {}".format(msg))
else:
to_update['query'] = args.query
msg = "[DEPRECATION] `query` is no longer required to `update` and may be omitted"
print_err("WARNING: {}".format(msg))
if args.name:
to_update['name'] = args.name
if args.message:
to_update['message'] = args.message
if args.type_opt:
to_update['type'] = args.type_opt
if args.query_opt:
to_update['query'] = args.query_opt
if args.options is not None:
to_update['options'] = json.loads(args.options)
res = api.Monitor.update(args.monitor_id, **to_update)
report_warnings(res)
report_errors(res)
if format == 'pretty':
print(pretty_json(res))
else:
print(json.dumps(res))
@classmethod
def _file_update(cls, args):
api._timeout = args.timeout
format = args.format
monitor = json.load(args.file)
res = api.Monitor.update(monitor['id'], type=monitor['type'], query=monitor['query'],
name=monitor['name'], message=monitor['message'],
options=monitor['options'])
report_warnings(res)
report_errors(res)
if format == 'pretty':
print(pretty_json(res))
else:
print(json.dumps(res))
@classmethod
def _show(cls, args):
api._timeout = args.timeout
format = args.format
res = api.Monitor.get(args.monitor_id)
report_warnings(res)
report_errors(res)
if args.string_ids:
res["id"] = str(res["id"])
if format == 'pretty':
print(pretty_json(res))
else:
print(json.dumps(res))
@classmethod
def _show_all(cls, args):
api._timeout = args.timeout
format = args.format
res = api.Monitor.get_all(
group_states=args.group_states, name=args.name,
tags=args.tags, monitor_tags=args.monitor_tags
)
report_warnings(res)
report_errors(res)
if args.string_ids:
for d in res:
d["id"] = str(d["id"])
if format == 'pretty':
print(pretty_json(res))
elif format == 'raw':
print(json.dumps(res))
else:
for d in res:
print("\t".join([(str(d["id"])),
(cls._escape(d["message"])),
(cls._escape(d["name"])),
(str(d["options"])),
(str(d["org_id"])),
(d["query"]),
(d["type"])]))
@classmethod
def _delete(cls, args):
api._timeout = args.timeout
# TODO CHECK
res = api.Monitor.delete(args.monitor_id)
if res is not None:
report_warnings(res)
report_errors(res)
@classmethod
def _escape(cls, s):
return s.replace("\r", "\\r").replace("\n", "\\n").replace("\t", "\\t")
@classmethod
def _mute_all(cls, args):
api._timeout = args.timeout
format = args.format
res = api.Monitor.mute_all()
report_warnings(res)
report_errors(res)
if format == 'pretty':
print(pretty_json(res))
else:
print(json.dumps(res))
@classmethod
def _unmute_all(cls, args):
api._timeout = args.timeout
res = api.Monitor.unmute_all()
if res is not None:
report_warnings(res)
report_errors(res)
@classmethod
def _mute(cls, args):
api._timeout = args.timeout
format = args.format
res = api.Monitor.mute(args.monitor_id, scope=args.scope, end=args.end)
report_warnings(res)
report_errors(res)
if format == 'pretty':
print(pretty_json(res))
else:
print(json.dumps(res))
@classmethod
def _unmute(cls, args):
api._timeout = args.timeout
res = api.Monitor.unmute(args.monitor_id, scope=args.scope, all_scopes=args.all_scopes)
report_warnings(res)
report_errors(res)
if format == 'pretty':
print(pretty_json(res))
else:
print(json.dumps(res))
@classmethod
def _can_delete(cls, args):
api._timeout = args.timeout
monitor_ids = [i.strip() for i in args.monitor_ids.split(',') if i.strip()]
res = api.Monitor.can_delete(monitor_ids=monitor_ids)
if format == 'pretty':
print(pretty_json(res))
else:
print(json.dumps(res))
@classmethod
def _validate(cls, args):
api._timeout = args.timeout
format = args.format
options = None
if args.options is not None:
options = json.loads(args.options)
if args.tags:
tags = sorted(set([t.strip() for t in args.tags.split(',') if t.strip()]))
else:
tags = None
res = api.Monitor.validate(type=args.type, query=args.query, name=args.name,
message=args.message, tags=tags, options=options)
# report_warnings(res)
# report_errors(res)
if format == 'pretty':
print(pretty_json(res))
else:
print(json.dumps(res))