Skip to content

Commit d5be90e

Browse files
authored
Merge pull request #30 from draios/alerts_from_obj_dump
Alerts create/backup/restore with JSON file, & revert Dashboard restore
2 parents 9dbff91 + 2393482 commit d5be90e

File tree

4 files changed

+102
-35
lines changed

4 files changed

+102
-35
lines changed

examples/list_alerts.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,25 @@
11
#!/usr/bin/env python
22
#
33
# Print 'enabled' flag and name for all of the alerts created by the user
4+
# Optionally dump the full Alerts list as a JSON object to a target file.
45
#
56

67
import os
78
import sys
9+
import json
810
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
911
from sdcclient import SdcClient
1012

1113
#
1214
# Parse arguments
1315
#
14-
if len(sys.argv) != 2:
15-
print 'usage: %s <sysdig-token>' % sys.argv[0]
16+
json_dumpfilename = None
17+
if len(sys.argv) < 2 or len(sys.argv) > 3:
18+
print 'usage: %s <sysdig-token> [json-dumpfile]' % sys.argv[0]
1619
print 'You can find your token at https://app.sysdigcloud.com/#/settings/user'
1720
sys.exit(1)
21+
elif len(sys.argv) == 3:
22+
json_dumpfilename = sys.argv[2]
1823

1924
sdc_token = sys.argv[1]
2025

@@ -39,3 +44,7 @@
3944

4045
for alert in data['alerts']:
4146
print 'enabled: %s, name: %s' % (str(alert['enabled']), alert['name'])
47+
48+
if json_dumpfilename:
49+
with open(json_dumpfilename, "w") as f:
50+
json.dump(data, f, sort_keys=True, indent=4)

examples/restore_alerts.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#!/usr/bin/env python
2+
#
3+
# Restore Alerts of the format in a JSON dumpfile from the list_alerts.py example.
4+
#
5+
6+
import os
7+
import sys
8+
import json
9+
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
10+
from sdcclient import SdcClient
11+
12+
#
13+
# Parse arguments
14+
#
15+
if len(sys.argv) != 3:
16+
print 'usage: %s <sysdig-token> <file-name>' % sys.argv[0]
17+
print 'You can find your token at https://app.sysdigcloud.com/#/settings/user'
18+
sys.exit(1)
19+
20+
sdc_token = sys.argv[1]
21+
alerts_dump_file = sys.argv[2]
22+
23+
#
24+
# Instantiate the SDC client
25+
#
26+
sdclient = SdcClient(sdc_token)
27+
28+
with open(alerts_dump_file, 'r') as f:
29+
j = json.load(f)
30+
for a in j['alerts']:
31+
a['description'] += ' (created via restore_alerts.py)'
32+
res = sdclient.create_alert(alert_obj=a)
33+
if not res[0]:
34+
print res[1]
35+
sys.exit(1)
36+
37+
print 'All Alerts in ' + alerts_dump_file + ' created successfully.'

examples/restore_dashboards.py

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,23 @@
2828

2929
zipf = zipfile.ZipFile(dashboard_state_file, 'r')
3030

31+
32+
dashboard_conf_items = ['showAsType', 'filterRoot', 'linkMetrics',
33+
'singleTimeNavigation', 'gridConfiguration', 'responsive',
34+
'nodesNoiseFilter', 'compareWith', 'format', 'linksNoiseFilter',
35+
'filterProcesses', 'isLegendExpanded', 'inhertitTimeNavigation',
36+
'schema', 'sortAscending', 'mapDataLimit', 'metrics', 'filterExtNodes',
37+
'sorting', 'name', 'sourceExploreView', 'items', 'showAs', 'eventsFilter',
38+
'timeMode', 'isShared', 'sourceDrilldownView']
39+
3140
for info in zipf.infolist():
3241
data = zipf.read(info.filename)
33-
dboard = json.loads(data)
34-
35-
dboard['timeMode'] = {'mode' : 1}
36-
dboard['time'] = {'last' : 2 * 60 * 60 * 1000000, 'sampling' : 2 * 60 * 60 * 1000000}
37-
38-
# Single filter support for all restored dashboards
39-
# TODO: add support to get filter from saved dashboard
40-
dashboardFilter = "proc.name = cassandra"
41-
res = sdclient.create_dashboard_from_template(dboard['name'] + '-restored', dboard, dashboardFilter)
42+
j = json.loads(data)
43+
k = {}
44+
for item in j.keys():
45+
if item in dashboard_conf_items:
46+
k[item] = j[item]
47+
48+
res = sdclient.create_dashboard_with_configuration(k)
4249
if res[0] == False:
4350
print "Dashboard creation failed for dashboard name %s with error %s" % (j['name'], res[1])

sdcclient/_client.py

Lines changed: 38 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -238,8 +238,9 @@ def get_notification_ids(self, channels):
238238

239239
return [True, ids]
240240

241-
def create_alert(self, name, description, severity, for_atleast_s, condition, segmentby=[],
242-
segment_condition='ANY', user_filter='', notify=None, enabled=True, annotations={}):
241+
def create_alert(self, name=None, description=None, severity=None, for_atleast_s=None, condition=None,
242+
segmentby=[], segment_condition='ANY', user_filter='', notify=None, enabled=True,
243+
annotations={}, alert_obj=None):
243244
'''**Description**
244245
Create a threshold-based alert.
245246
@@ -255,6 +256,7 @@ def create_alert(self, name, description, severity, for_atleast_s, condition, se
255256
- **notify**: the type of notification you want this alert to generate. Options are *EMAIL*, *SNS*, *PAGER_DUTY*, *SYSDIG_DUMP*.
256257
- **enabled**: if True, the alert will be enabled when created.
257258
- **annotations**: an optional dictionary of custom properties that you can associate to this alert for automation or management reasons
259+
- **alert_obj**: an optional fully-formed Alert object of the format returned in an "alerts" list by :func:`~SdcClient.get_alerts` This is an alternative to creating the Alert using the individual parameters listed above.
258260
259261
**Success Return Value**
260262
A dictionary describing the just created alert, with the format described at `this link <https://app.sysdigcloud.com/apidocs/#!/Alerts/post_api_alerts>`__
@@ -270,31 +272,43 @@ def create_alert(self, name, description, severity, for_atleast_s, condition, se
270272
return [False, self.lasterr]
271273
j = res.json()
272274

273-
#
274-
# Populate the alert information
275-
#
276-
alert_json = {
277-
'alert' : {
278-
'type' : 'MANUAL',
279-
'name' : name,
280-
'description' : description,
281-
'enabled' : enabled,
282-
'severity' : severity,
283-
'timespan' : for_atleast_s * 1000000,
284-
'condition' : condition,
285-
'filter': user_filter
286-
}
287-
}
275+
if alert_obj is None:
276+
if None in (name, description, severity, for_atleast_s, condition):
277+
return [False, 'Must specify a full Alert object or all parameters: name, description, severity, for_atleast_s, condition']
278+
else:
279+
#
280+
# Populate the alert information
281+
#
282+
alert_json = {
283+
'alert' : {
284+
'type' : 'MANUAL',
285+
'name' : name,
286+
'description' : description,
287+
'enabled' : enabled,
288+
'severity' : severity,
289+
'timespan' : for_atleast_s * 1000000,
290+
'condition' : condition,
291+
'filter': user_filter
292+
}
293+
}
288294

289-
if segmentby != None and segmentby != []:
290-
alert_json['alert']['segmentBy'] = segmentby
291-
alert_json['alert']['segmentCondition'] = {'type' : segment_condition}
295+
if segmentby != None and segmentby != []:
296+
alert_json['alert']['segmentBy'] = segmentby
297+
alert_json['alert']['segmentCondition'] = {'type' : segment_condition}
292298

293-
if annotations != None and annotations != {}:
294-
alert_json['alert']['annotations'] = annotations
299+
if annotations != None and annotations != {}:
300+
alert_json['alert']['annotations'] = annotations
295301

296-
if notify != None:
297-
alert_json['alert']['notificationChannelIds'] = notify
302+
if notify != None:
303+
alert_json['alert']['notificationChannelIds'] = notify
304+
else:
305+
# The REST API enforces "Alert ID and version must be null", so remove them if present,
306+
# since these would have been there in a dump from the list_alerts.py example.
307+
alert_obj.pop('id', None)
308+
alert_obj.pop('version', None)
309+
alert_json = {
310+
'alert' : alert_obj
311+
}
298312

299313
#
300314
# Create the new alert

0 commit comments

Comments
 (0)