/
handler.py
674 lines (525 loc) · 22.7 KB
/
handler.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
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
__author__ = 'abdul'
import logging
import smtplib
import traceback
from email.mime.text import MIMEText
from sendgrid import Sendgrid, Message
from .message import get_messages
from ..utils import listify
import hipchat
import pypd
from carbonio_client.client import CarbonIOClient
from robustify.robustify import robustify
from ..errors import raise_exception, raise_if_not_retriable
from zdesk import Zendesk
DEFAULT_NOTIFICATION_SUBJECT = "Backup System Notification"
###############################################################################
# LOGGER
###############################################################################
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
###############################################################################
# NotificationPriority class
class NotificationPriority(object):
NORMAL = "normal"
CRITICAL = "critical"
###############################################################################
# NotificationPriority class
class NotificationType(object):
DEFAULT = "default"
ERROR = "error"
EVENT = "event"
###############################################################################
# Notifications class
###############################################################################
class Notifications(object):
def __init__(self):
self._handlers = {}
self._handler_mapping = {}
###########################################################################
@property
def handlers(self):
return self._handlers
@handlers.setter
def handlers(self, val):
self._handlers = val
###########################################################################
@property
def handler_mapping(self):
return self._handler_mapping
@handler_mapping.setter
def handler_mapping(self, val):
self._handler_mapping = val
###########################################################################
def send_notification(self, subject, message, recipient=None,
notification_type=NotificationType.DEFAULT,
priority=None):
handlers = self.get_handlers_for(notification_type, priority=priority) or []
for handler in handlers:
try:
handler.send_notification(subject, message, recipient)
except Exception, ex:
logger.exception("Exception while sending notification")
###########################################################################
def send_error_notification(self, subject, message):
self.send_notification(subject, message, notification_type=NotificationType.ERROR)
###########################################################################
def send_event_notification(self, subject, message, priority=None):
self.send_notification(subject, message, notification_type=NotificationType.EVENT,
priority=priority)
###########################################################################
def notify_on_task_failure(self, task, exception, trace):
self.send_notification(
"Task failed",
get_messages()['TaskFailureNotification'].get_message({
'id': task.id,
'task': task,
'exception': exception,
'trace': trace}))
###########################################################################
def notify_task_reschedule_failed(self, task):
self.send_notification(
'Task Reschedule Failed',
get_messages()['TaskRescheduleFailed'].get_message({
'task': task}))
###########################################################################
def get_handlers_for(self, notification_type, priority=NotificationPriority.NORMAL):
handler_names = self.get_handler_names_for(notification_type, priority=priority)
return map(self.get_handler_by_name, handler_names)
###########################################################################
def get_handler_names_for(self, notification_type, priority=NotificationPriority.NORMAL):
handlers_conf = self.handler_mapping.get(notification_type)
if not handlers_conf:
handle_names = NotificationType.DEFAULT
else:
if isinstance(handlers_conf, dict):
handle_names = handlers_conf.get(priority)
else:
handle_names = listify(str(handlers_conf))
return listify(handle_names)
###########################################################################
def get_default_handler(self):
return self.handler_mapping.get(NotificationType.DEFAULT)
###########################################################################
def get_handler_by_name(self, name):
return self._handlers.get(name)
###############################################################################
################################# ##################################
################################# handlers ##################################
################################# ##################################
###############################################################################
###############################################################################
# NotificationHandler
###############################################################################
class NotificationHandler(object):
###########################################################################
def __init__(self):
self._error_recipient_mapping = {}
###########################################################################
def send_notification(self, subject, message, recipient=None):
pass
###############################################################################
# LoggerNotificationHandler
###############################################################################
class LoggerNotificationHandler(NotificationHandler):
###########################################################################
def __init__(self, level=logging.INFO):
super(LoggerNotificationHandler, self).__init__()
self._level = level
###########################################################################
@property
def level(self):
return self._level
@level.setter
def level(self, level):
self._level = level
###########################################################################
def send_notification(self, subject, message, recipient=None):
msg = "\n---- LoggerNotificationHandler ------ \n%s\n\n%s\n-------------" % (subject, message)
logger.log(self.level, msg)
###########################################################################
# Default notifications
DEFAULT_NOTIFICATIONS = Notifications()
DEFAULT_NOTIFICATIONS.handlers = {
"logError": LoggerNotificationHandler(level=logging.ERROR),
"logInfo": LoggerNotificationHandler(level=logging.INFO)
}
DEFAULT_NOTIFICATIONS.handler_mapping = {
"default": "logInfo",
"error": "logInfo"
}
###############################################################################
# EmailNotificationHandler
###############################################################################
class EmailNotificationHandler(NotificationHandler):
###########################################################################
def __init__(self):
NotificationHandler.__init__(self)
self._from_address = None
self._to_address = None
###########################################################################
@property
def from_address(self):
return self._from_address
@from_address.setter
def from_address(self, from_address):
self._from_address = from_address
###########################################################################
@property
def to_address(self):
return self._to_address
@to_address.setter
def to_address(self, to_address):
self._to_address = to_address
###############################################################################
# SendgridNotificationHandler
###############################################################################
class SendgridNotificationHandler(EmailNotificationHandler):
###########################################################################
def __init__(self):
EmailNotificationHandler.__init__(self)
self._sendgrid = None
self._sendgrid_username = None
self._sendgrid_password = None
###########################################################################
# PROPERTIES
###########################################################################
@property
def sendgrid_username(self):
return self._sendgrid_username
@sendgrid_username.setter
def sendgrid_username(self, sendgrid_username):
self._sendgrid_username = sendgrid_username
###########################################################################
@property
def sendgrid_password(self):
return self._sendgrid_password
@sendgrid_password.setter
def sendgrid_password(self, sendgrid_password):
self._sendgrid_password = sendgrid_password
###########################################################################
def _ensure_sg_initialized(self):
if self._sendgrid is None:
self._sendgrid = Sendgrid(self.sendgrid_username,
self.sendgrid_password,
secure=True)
###########################################################################
def send_notification(self, subject, message, recipient=None):
subject = subject or DEFAULT_NOTIFICATION_SUBJECT
try:
self._ensure_sg_initialized()
logger.info("Sending notification email...")
s_message = Message(self.from_address, subject=subject,
text=message)
to_address = listify(recipient or self.to_address)
for address in to_address:
s_message.add_to(address)
self._sendgrid.web.send(s_message)
logger.info("Email sent successfully!")
except Exception, e:
print e
print traceback.format_exc()
logger.error("Error while sending email:\n%s" %
traceback.format_exc())
###############################################################################
# SmtpNotificationHandler
###############################################################################
class SmtpNotificationHandler(EmailNotificationHandler):
###########################################################################
def __init__(self):
NotificationHandler.__init__(self)
self._smtp_host = None
self._smtp_username = None
self._smtp_password = None
###########################################################################
def send_notification(self, subject, message, recipient=None):
try:
logger.info("Sending notification email...")
msg = MIMEText(message.encode('utf-8'), 'plain', 'UTF-8')
to_address = listify(recipient or self._to_address)
msg['From'] = self.from_address
msg['To'] = ",".join(to_address)
if subject:
msg['Subject'] = subject
smtp = smtplib.SMTP(self.smtp_host)
if (self.smtp_username is not None or
self.smtp_password is not None):
smtp.login(self.smtp_username, self.smtp_password)
smtp.sendmail(self.from_address, to_address, msg.as_string())
smtp.quit()
logger.info("Email sent successfully!")
except Exception, e:
logger.error("Error while sending email:\n%s" %
traceback.format_exc())
###########################################################################
# PROPERTIES
###########################################################################
@property
def smtp_host(self):
return self._smtp_host
@smtp_host.setter
def smtp_host(self, smtp_host):
self._smtp_host = smtp_host
###########################################################################
@property
def smtp_username(self):
return self._smtp_username
@smtp_username.setter
def smtp_username(self, smtp_username):
self._smtp_username = smtp_username
###########################################################################
@property
def smtp_password(self):
return self._smtp_password
@smtp_password.setter
def smtp_password(self, smtp_password):
self._smtp_password = smtp_password
###############################################################################
# HipchatNotificationHandler
###############################################################################
class HipchatNotificationHandler(NotificationHandler):
###########################################################################
def __init__(self):
NotificationHandler.__init__(self)
self._api_token = None
self._room_id = None
self._from_name = None
self._color = None
###########################################################################
@property
def api_token(self):
return self._api_token
@api_token.setter
def api_token(self, val):
self._api_token = val
###########################################################################
@property
def room_id(self):
return self._room_id
@room_id.setter
def room_id(self, val):
self._room_id = val
###########################################################################
@property
def from_name(self):
return self._from_name
@from_name.setter
def from_name(self, val):
self._from_name = val
###########################################################################
@property
def color(self):
return self._color
@color.setter
def color(self, val):
self._color = val
###########################################################################
def send_notification(self, subject, message, recipient=None):
try:
room_id = recipient or self.room_id
logger.info("Sending notification hipchat '%s'..." % subject)
hipster = hipchat.HipChat(token=self.api_token)
hipchat_message = "%s\n\n%s" % (subject, message)
# limit message to 9000 chars
if len(hipchat_message) > 9000:
hipchat_message = hipchat_message[:9000] + "..."
hipster.message_room(room_id, self.from_name, hipchat_message, color=self.color)
logger.info("Hipchat sent successfully!")
except Exception, e:
logger.error("Error while sending hipchat message:\n%s" %
traceback.format_exc())
###############################################################################
def raise_if_not_pd_retriable(e):
if "Forbidden" in str(e):
logger.warn("Caught a retriable PD exception: %s" % e)
else:
raise_if_not_retriable(e)
###############################################################################
# PagerDutyNotificationHandler
###############################################################################
class PagerDutyNotificationHandler(NotificationHandler):
###########################################################################
def __init__(self):
NotificationHandler.__init__(self)
self._api_key = None
self._service_key = None
self._sub_domain = None
self._client_name = None
###########################################################################
@property
def api_key(self):
return self._api_key
@api_key.setter
def api_key(self, val):
self._api_key = val
###########################################################################
@property
def service_key(self):
return self._service_key
@service_key.setter
def service_key(self, val):
self._service_key = val
pypd.api_key = val
###########################################################################
@property
def sub_domain(self):
return self._sub_domain
@sub_domain.setter
def sub_domain(self, val):
self._sub_domain = val
###########################################################################
@property
def client_name(self):
return self._client_name
@client_name.setter
def client_name(self, val):
self._client_name = val
###########################################################################
def send_notification(self, subject, message, recipient=None):
try:
kwargs = {}
if self.client_name:
kwargs["client"] = self.client_name
logger.info("PagerDuty: Sending notification: %s..." % subject)
response = pypd.EventV2.create(data={
'routing_key': self.service_key,
'event_action': 'trigger',
'dedup_key': subject,
'payload': {
'summary': subject,
'severity': 'error',
'source': 'test',
'custom_details': {'details': message},
}
})
return response["dedup_key"]
except Exception, e:
logger.error("Error while creating PagerDuty event:\n%s" %
traceback.format_exc())
###########################################################################
@robustify(max_attempts=5, retry_interval=5,
do_on_exception=raise_if_not_pd_retriable,
do_on_failure=raise_exception)
def resolve_incident(self, incident_key):
try:
logger.info("PagerDutyNotificationHandler: Resolving incident '%s'" % incident_key)
response = pypd.EventV2.create(data={
'routing_key': self.service_key,
'event_action': 'resolve',
'dedup_key': incident_key,
'payload': {
'summary': 'Resolving incident %s' % incident_key,
'severity': 'error',
'source': self.client_name,
}
})
return response["dedup_key"]
except Exception, e:
logger.error("Error while trying to resolve PagerDuty event:\n%s" %
traceback.format_exc())
###########################################################################
def list_incidents(self, **kwargs):
all_incidents = pypd.Incident.find(api_key=self.api_key, fetch_all=True, **kwargs)
return all_incidents
###############################################################################
# SlackNotificationHandler
###############################################################################
class SlackNotificationHandler(NotificationHandler):
###########################################################################
def __init__(self):
NotificationHandler.__init__(self)
self._webhook_url = None
###########################################################################
@property
def webhook_url(self):
return self._webhook_url
@webhook_url.setter
def webhook_url(self, val):
self._webhook_url = val
###########################################################################
def send_notification(self, subject, message, recipient=None):
try:
logger.info("Sending slack notification '%s'..." % subject)
sc_client = CarbonIOClient(url=self.webhook_url)
text = "*%s*: %s" % (subject, message)
result = sc_client.post({
"text": text,
"mrkdwn": True
})
if result.text == "ok":
logger.info("Slack message sent successfully!")
else:
logger.error("Failed to send slack message. Result: %s" % result.text)
except Exception, e:
logger.error("Error while sending slack notification:\n%s" %
traceback.format_exc())
class ZendeskNotificationHandler(NotificationHandler):
###########################################################################
def __init__(self):
NotificationHandler.__init__(self)
self._auth_token = None
self._auth_email = None
self._auth_org_url = None
self._requester_name = None
self._requester_email = None
self._assignee_id = None
@property
def auth_token(self):
return self._auth_token
@auth_token.setter
def auth_token(self, val):
self._auth_token = val
@property
def auth_email(self):
return self._auth_email
@auth_email.setter
def auth_email(self, val):
self._auth_email = val
@property
def auth_org_url(self):
return self._auth_org_url
@auth_org_url.setter
def auth_org_url(self, val):
self._auth_org_url = val
@property
def requester_name(self):
return self._requester_name
@requester_name.setter
def requester_name(self, val):
self._requester_name = val
@property
def requester_email(self):
return self._requester_email
@requester_email.setter
def requester_email(self, val):
self._requester_email = val
@property
def assignee_id(self):
return self._assignee_id
@assignee_id.setter
def assignee_id(self, val):
self._assignee_id = val
###########################################################################
def send_notification(self, subject, message, recipient=None):
try:
logger.info("Sending zendesk notification '%s'..." % subject)
zendesk = Zendesk(self.auth_org_url, self.auth_email, self.auth_token, True)
new_ticket = {
'ticket': {
'requester': {
'name': self.requester_name,
'email': self.requester_email,
},
'subject': subject,
'description': message,
'assignee_id': self.assignee_id
}
}
zendesk.ticket_create(data=new_ticket)
except Exception, e:
logger.error("Error while sending zendesk notification:\n%s" %
traceback.format_exc())
###############################################################################
def get_class_full_name(clazz):
return (clazz.__module__ + "." +
clazz.__name__)