-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathmodel.py
More file actions
544 lines (424 loc) · 19.8 KB
/
Copy pathmodel.py
File metadata and controls
544 lines (424 loc) · 19.8 KB
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
"""
Module containing the classes that model the Argus base objects.
"""
#
# Copyright (c) 2016, salesforce.com, inc.
# All rights reserved.
# Licensed under the BSD 3-Clause license.
# For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
#
import json
from six import string_types, iteritems
class BaseEncodable(object):
def __init__(self, **kwargs):
for k, v in iteritems(kwargs):
setattr(self, k, v)
def to_dict(self):
D = dict((k, v) for k, v in iteritems(self.__dict__) if not k.startswith("_"))
return D
@classmethod
def from_dict(cls, D):
for f in cls.id_fields:
if isinstance(f, tuple):
if any(alias in D for alias in f):
continue
else:
return None
elif f not in D:
return None
else:
return cls(**D)
@property
def argus_id(self):
"""
The property that gives access to the Argus ID. This is ``None`` for new objects.
"""
return hasattr(self, "id") and int(self.id) or None
@argus_id.setter
def argus_id(self, value):
self.id = value
@property
def owner_id(self):
"""
The ID of the object that owns this object or ``None``. Only applicable to a few types that are not first-class objects.
"""
return hasattr(self, "owner_id_field") and hasattr(self, self.owner_id_field) and int(
getattr(self, self.owner_id_field)) or None
def __str__(self):
return str(self.to_dict())
def __repr__(self):
return str(self)
def __hash__(self):
return hash(self.__dict__)
def __eq__(self, other):
if not isinstance(other, type(self)):
return False
return self.__dict__ == other.__dict__
class AddListResult(BaseEncodable):
"""
Represents the result of metric or annotation collection add request.
Ex: {"Error Messages":[],"Error":"0 metrics","Success":"1 metrics"}
"""
id_fields = ("Error", "Success")
def error_messages(self):
""" Return any error messsages from the result. """
return self.__dict__["Error Messages"]
def error_count(self):
""" Return error count from the result. """
numEnd = self.Error.index(" ")
return int(self.Error[0:numEnd])
def success_count(self):
""" Return success count from the result. """
numEnd = self.Success.index(" ")
return int(self.Success[0:numEnd])
class User(BaseEncodable):
"""
Represents a User object in Argus.
**Required parameters to the constructor:**
:param userName: The username of the Argus user
:type userName: str
**Optional parameters to the constructor:**
:param email: The email address of the Argus user
:type email: str
"""
id_fields = ("userName", "email")
def __init__(self, userName, **kwargs):
super(User, self).__init__(userName=userName, **kwargs)
class Metric(BaseEncodable):
"""
Represents a Metric object in Argus.
**Required parameters to the constructor:**
:param scope: The scope for the annotation
:type scope: str
:param metric: The metric name of the annotation
:type metric: str
**Optional parameters to the constructor:**
:param namespace: The namespace for the metric
:type namespace: str
:param displayName: The display name of the metric
:type displayName: str
:param unitType: The unit type of the metric value
:type unitType: str
:param datapoints: The actual metric data points as a dictionary of values with epoc timestamp as the keys.
:type datapoints: dict of int:object
:param tags: A dictionary of tags. Both keys and values should be valid strings.
:type tags: dict of str:str
"""
id_fields = ("datapoints",)
def __init__(self, scope, metric, **kwargs):
super(Metric, self).__init__(scope=scope, metric=metric, **kwargs)
if not hasattr(self, "datapoints") or self.datapoints is None:
self.datapoints = {}
if not hasattr(self, "tags") or self.tags is None:
self.tags = {}
def __str__(self):
"""
Return a string representation of the metric that can be directly used as the metric expressoin in a metric query and has the format:
``scope:metric[{tagk=tagv,...}][:namespace]``
"""
tags = hasattr(self, "tags") and self.tags or None
metricWithTags = tags and "%s{%s}" % (
self.metric, ",".join("%s=%s" % (k, v) for k, v in iteritems(self.tags))) or self.metric
return ":".join(
str(q) for q in (self.scope, metricWithTags, hasattr(self, "namespace") and self.namespace or None) if q)
class Annotation(BaseEncodable):
"""
Represents an Annotation object in Argus.
**Required parameters to the constructor:**
:param source: The source of the annotation
:type source: str
:param scope: The scope for the annotation
:type scope: str
:param metric: The metric name of the annotation
:type metric: str
:param timestamp: The timestamp of the annotation
:type timestamp: int
:param id: An external id for the annotation
:type id: int
**Optional parameters to the constructor:**
:param tags: A dictionary of tags. Both keys and values should be valid strings.
:type tags: dict of str:str
:param fields: A dictionary of fields. Both keys and values should be valid strings.
:type fields: dict of str:str
"""
id_fields = ("source", "timestamp",)
def __init__(self, source, scope, metric, id, timestamp, type, **kwargs):
super(Annotation, self).__init__(source=source, scope=scope, metric=metric, id=id, timestamp=timestamp,
type=type, **kwargs)
if not hasattr(self, "fields") or self.fields is None:
self.fields = {}
if not hasattr(self, "tags") or self.tags is None:
self.tags = {}
def __str__(self):
"""
Return a string representation of the annotation that can be directly used as the annotation expresson in an annotation query and has the format:
``scope:metric[{tagk=tagv,...}]:source``
"""
tags = hasattr(self, "tags") and self.tags or None
metricWithTags = tags and "%s{%s}" % (self.metric, ",".join("%s=%s" % (k, v) for k, v in iteritems(self.tags))) \
or self.metric
return ":".join(str(q) for q in (self.scope, metricWithTags, self.source) if q)
class Dashboard(BaseEncodable):
"""
Represents a Dashboard object in Argus.
Dashboard name has to be unique across the dashboards owned by the current user.
**Required parameters to the constructor:**
:param name: The name of the dashboard
:type name: str
:param content: The XML content
:type content: str
**Optional parameters to the constructor:**
:param description: A description for the dashboard
:type description: str
:param shared: The shared state of the dashboard.
:type shared: bool
:param id: The Argus id of the dashboard
:type id: int
"""
id_fields = ("content",)
def __init__(self, name, content, **kwargs):
super(Dashboard, self).__init__(name=name, content=content, **kwargs)
class Permission(BaseEncodable):
"""
Represents a Permission object in Argus.
**Required parameters to the constructor:**
:param type: the type of permission - "user" or "group"
:type type: str
:param permissionNames: List of permissions that this user or group
has on the associated entity (id is put in the entityId field).
Permissions in this list are in the form of strings: like "VIEW", "EDIT", and "DELETE".
:type permissionNames: list of str
**Optional parameters to the constructor:**
:param groupId: id of the group that has the associated permissions
:type groupId: str
:param username: name of the user that has the associated permissions
:type username: str
:param permissionIds: List of permissions that this user or group
has on the associated entity (id is put in the entityId field).
Permissions in this list are in the form of integers: like 0, 1, and 2.
0, 1, and 2 correspond to "VIEW", "EDIT", and "DELETE" respectively.
:type permissionIds: list of int
:param entityId: id of the associated entity
:type entityId: int
"""
id_fields = ("type",)
VALID_TYPES = frozenset(("user", "group"))
def __init__(self, type, **kwargs):
assert type in Permission.VALID_TYPES, "Permission type %s is not valid" % type
super(Permission, self).__init__(type=type, **kwargs)
class Namespace(BaseEncodable):
"""
Represents a Namespace object in Argus.
**Required parameters to the constructor:**
:param qualifier: The namespace qualifier
:type qualifier: str
**Optional parameters to the constructor:**
:param usernames: The list of usernames that are authorized to post metrics to the namespace.
:type usernames: list of str
:param id: The Argus id of this namespace
:type id: int
"""
id_fields = ("qualifier",)
def __init__(self, qualifier, **kwargs):
assert qualifier and isinstance(qualifier, string_types), "A string qualifier is required for namespace"
super(Namespace, self).__init__(qualifier=qualifier, **kwargs)
class Alert(BaseEncodable):
"""
Represents an Alert object in Argus.
Alert name has to be unique across the alerts owned by the current user.
**Required parameters to the constructor:**
:param name: The name of the alert
:type name: str
:param expression: The metric query expression
:type expression: str
:param cronEntry: The cron expression
:type cronEntry: str
**Optional parameters to the constructor:**
:param enabled: The enabled state of the alert
:type enabled: bool
:param missingDataNotificationEnabled: The enabled state of missing data notification
:type missingDataNotificationEnabled: bool
:param triggerIds: The list of IDs for the triggers owned by this alert.
:type triggerIds: list of int
:param notificationIds: The list of IDs for the notifications owned by this alert.
:type notificationIds: list of int
:param shared: The shared state of the alert
:type enabled: bool
"""
id_fields = ("expression", "cronEntry",)
def __init__(self, name, expression, cronEntry, **kwargs):
self._triggers = None
self._notifications = None
super(Alert, self).__init__(name=name, expression=expression, cronEntry=cronEntry, **kwargs)
@property
def trigger(self):
""" A convenience property to be used when :attr:`triggers` contains a single :class:`argusclient.model.Trigger`. """
return self._triggers and len(self._triggers) == 1 and self._triggers[0] or None
@trigger.setter
def trigger(self, value):
if not isinstance(value, Trigger):
raise ValueError( "argument should be of Trigger type, but is: %s" % type(value))
if not ((
value.owner_id is None and self.argus_id is None) or value.owner_id == self.argus_id): raise ValueError(
"trigger owned by alert id: %s not by %s" % (value.owner_id, self.argus_id))
self._triggers = [value]
@property
def triggers(self):
""" Property to get and set triggers on the alert. """
return self._triggers
@triggers.setter
def triggers(self, value):
if not isinstance(value, list): raise ValueError("value should be of list type, but is: %s" % type(value))
# This is a special case allowed only while adding new alerts, so ensure that argus_id of self and the objects is None.
# TODO Check for item type also
self._triggers = value
@property
def notification(self):
""" A convenience property to be used when :attr:`notifications` contains a single :class:`argusclient.model.Notification`. """
return self._notifications and len(self._notifications) == 1 and self._notifications[0] or None
@notification.setter
def notification(self, value):
if not isinstance(value, Notification):
raise ValueError("value should be of Notification type, but is: %s" % type(value))
if not ((
value.owner_id is None and self.argus_id is None) or value.owner_id == self.argus_id): raise ValueError(
"notification owned by alert id: %s not by %s" % (value.owner_id, self.argus_id))
self._notifications = [value]
@property
def notifications(self):
""" Property to get and set notifications on the alert. """
return self._notifications
@notifications.setter
def notifications(self, value):
if not isinstance(value, list): raise ValueError("value should be of list type, but is: %s" % type(value))
# This is a special case allowed only while adding new alerts, so ensure that argus_id of self and the objects is None.
# TODO Check for item type also
self._notifications = value
class Trigger(BaseEncodable):
"""
Represents a Trigger object in Argus.
**Required parameters to the constructor:**
:param name: Name of the trigger
:type name: str
:param type: Type of the trigger. Must be one of these: :attr:`GREATER_THAN`, :attr:`GREATER_THAN_OR_EQ`, :attr:`LESS_THAN`, :attr:`LESS_THAN_OR_EQ`, :attr:`EQUAL`, :attr:`NOT_EQUAL`, :attr:`BETWEEN`, :attr:`NOT_BETWEEN`, :attr:`NO_DATA`.
:type type: str
:param threshold: Threshold for the trigger
:type threshold: float
:param inertia: Inertia for the trigger
:type inertia: int
**Optional parameters to the constructor:**
:param secondaryThreshold: Secondary threshold.
:type secondaryThreshold: float
:param notificationIds: List of IDs of notifications that this trigger is associated with.
:type notificationIds: list of int
:param alertId: ID of the alert that this trigger belongs to.
:type alertId: int
"""
id_fields = ("threshold",)
owner_id_field = "alertId"
GREATER_THAN = "GREATER_THAN"
GREATER_THAN_OR_EQ = "GREATER_THAN_OR_EQ"
LESS_THAN = "LESS_THAN"
LESS_THAN_OR_EQ = "LESS_THAN_OR_EQ"
EQUAL = "EQUAL"
NOT_EQUAL = "NOT_EQUAL"
BETWEEN = "BETWEEN"
NOT_BETWEEN = "NOT_BETWEEN"
NO_DATA = "NO_DATA"
#: Set of all valid trigger types.
VALID_TYPES = frozenset(
(GREATER_THAN, GREATER_THAN_OR_EQ, LESS_THAN, LESS_THAN_OR_EQ, EQUAL, NOT_EQUAL, BETWEEN, NOT_BETWEEN, NO_DATA))
def __init__(self, name, type, threshold, inertia, **kwargs):
assert type in Trigger.VALID_TYPES, "type is not valid: %s" % type
super(Trigger, self).__init__(name=name, type=type, threshold=threshold, inertia=inertia, **kwargs)
class Notification(BaseEncodable):
"""
Represents a Notification object in Argus.
**Required parameters to the constructor:**
:param name: The name of the notification
:type name: str
:param notifierName: The name of the notifier implementation. Must be one of :attr:`EMAIL`, :attr:`AUDIT`,
:attr:`GOC`, :attr:`GUS`, :attr:`CALLBACK`, :attr:`PAGER_DUTY`, :attr:`REFOCUS_BOOLEAN`,
:attr:`REFOCUS_VALUE`, :attr:`SLACK`, :attr:`ALERT_ROUTER`, :attr:`ADVANCE_SLACK`
:type notifierName or notifier: str
**Optional parameters to the constructor:**
:param subscriptions: The subscriptions for the notifier implementation, such as email ids in case of :attr:`EMAIL`.
:type subscriptions: list of str
:param cooldownPeriod: The cooldown period
:type cooldownPeriod: float
:param cooldownExpiration: The cooldown expiration
:type cooldownExpiration: float
:param triggerIds: List of IDs of triggers that this notification is associated with.
:type triggerIds: list of int
:param alertId: ID of the alert that this trigger belongs to.
:type alertId: int
"""
id_fields = (("notifierName", "notifier"),)
owner_id_field = "alertId"
EMAIL = "com.salesforce.dva.argus.service.alert.notifier.EmailNotifier"
AUDIT = "com.salesforce.dva.argus.service.alert.notifier.AuditNotifier"
GOC = "com.salesforce.dva.argus.service.alert.notifier.GOCNotifier"
GUS = "com.salesforce.dva.argus.service.alert.notifier.GusNotifier"
CALLBACK = "com.salesforce.dva.argus.service.alert.notifier.CallbackNotifier"
PAGER_DUTY = "com.salesforce.dva.argus.service.alert.notifier.PagerDutyNotifier"
REFOCUS_BOOLEAN = "com.salesforce.dva.argus.service.alert.notifier.RefocusBooleanNotifier"
REFOCUS_VALUE = "com.salesforce.dva.argus.service.alert.notifier.RefocusValueNotifier"
SLACK = "com.salesforce.dva.argus.service.alert.notifier.SlackNotifier"
ALERT_ROUTER = "com.salesforce.dva.argus.service.alert.notifier.AlertRouterNotifier"
ADVANCE_SLACK = "com.salesforce.dva.argus.service.alert.notifier.AdvanceSlackNotifier"
#: Set of all valid notifier implementation names.
VALID_NOTIFIERS = frozenset((EMAIL, AUDIT, GOC, GUS, CALLBACK, PAGER_DUTY,
REFOCUS_BOOLEAN, REFOCUS_VALUE, SLACK, ALERT_ROUTER, ADVANCE_SLACK))
def __init__(self, name, notifierName=None, metricsToAnnotate=None, **kwargs):
notifierName = notifierName or kwargs.get('notifier')
assert notifierName in Notification.VALID_NOTIFIERS, "notifierName is not valid: %s" % notifierName
super(Notification, self).__init__(name=name, notifierName=notifierName,
metricsToAnnotate=metricsToAnnotate or [],
**kwargs)
class Derivative(BaseEncodable):
"""
Represents a Derivative object in Argus.
** Required parameteres to the connstructor:**
:param name: The name of the derivative
:type name: str
:param sourceExpression: The argus query for source metric
:type sourceExpression: str
:param derivedScope: The scope for derived metric
:type derivedScope: str
:param derivativeInterval: Interval at which derivative job needs to run
:type derivativeInterval: str
** Optional parameteres to the connstructor:**
:param derivedMetric: The metric name for derived metric
:type derivedMetric: str
:param derivativeTagOptions: The tag modifiers for derived metric
:type derivativeTagOptions: str
:param enabled: Denotes whether job is enabled or not
:type enabled: bool
:param alertIfNoData: Denotes whether to alert user on no data or not.
:type alertIfNoData: str
"""
id_fields = ("sourceExpression", "derivedScope", "derivativeInterval",)
def __init__(self, name, sourceExpression, derivedScope, derivativeInterval, **kwargs):
super(Derivative, self).__init__(name=name, sourceExpression = sourceExpression, derivedScope = derivedScope,
derivativeInterval = derivativeInterval, **kwargs)
class JsonEncoder(json.JSONEncoder):
def default(self, obj):
return self.to_json(obj)
def to_json(self, obj):
if isinstance(obj, BaseEncodable):
return obj.to_dict()
return json.JSONEncoder.default(self, obj)
class JsonDecoder(json.JSONDecoder):
def __init__(self, *args, **kwargs):
kwargs['object_hook'] = self.from_json
super(JsonDecoder, self).__init__(*args, **kwargs)
def from_json(self, jsonObj):
if not jsonObj or not isinstance(jsonObj, dict):
return jsonObj
for cls in (Metric, Dashboard, AddListResult, User, Namespace, Annotation,
Alert, Trigger, Notification, Permission, Derivative):
obj = cls.from_dict(jsonObj)
if obj:
return obj
else:
return jsonObj