-
Notifications
You must be signed in to change notification settings - Fork 138
/
sender.py
1642 lines (1373 loc) · 64.2 KB
/
sender.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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license.
# See LICENSE in the project root for license information.
from gevent import monkey, sleep, spawn, queue
monkey.patch_all() # NOQA
import logging
import time
import ujson
import os
import socket
import gevent
import signal
import setproctitle
import copy
from collections import defaultdict
from iris.plugins import init_plugins
from iris.vendors import IrisVendorManager, iris_smtp
from iris.sender import auditlog
from iris import metrics
from uuid import uuid4
from iris.gmail import Gmail
from iris import db
from iris.api import load_config
from iris.utils import sanitize_unicode_dict
from iris.sender import rpc, cache
from iris.sender.message import update_message_mode
from iris.sender.oneclick import oneclick_email_markup, generate_oneclick_url
from iris import cache as api_cache
from iris.sender.quota import ApplicationQuota
from iris.role_lookup import IrisRoleLookupException
from pymysql import DataError, IntegrityError, InternalError
# queue for sending messages
from iris.sender.shared import per_mode_send_queues, add_mode_stat
# sql
NEW_INCIDENTS = '''SELECT
`incident`.`id` as `id`,
`incident`.`created` as `created`,
`incident`.`plan_id` as `plan_id`,
`incident`.`context` as `context`,
`application`.`name` as `application`
FROM `incident`
JOIN `application`
ON `incident`.`application_id`=`application`.`id`
WHERE `current_step`=0 AND `active`=1'''
INACTIVE_SQL = '''UPDATE
`incident`
SET `active`=0
WHERE `id` IN %s'''
GET_INACTIVE_IDS_SQL = '''SELECT
distinct `incident_id`
FROM (
SELECT
`incident_id`,
`max`,
`age`,
MAX(`count`) as max_count
FROM (
SELECT
`message`.`incident_id` as `incident_id`,
`message`.`plan_notification_id` as `plan_notification_id`,
count(`message`.`id`) as `count`,
`plan_notification`.`repeat` + 1 as `max`,
TIMESTAMPDIFF(SECOND, MAX(`message`.`sent`), NOW()) as `age`,
`plan_notification`.`wait` as `wait`,
`plan_notification`.`step` as `step`,
`incident`.`current_step`,
`plan`.`step_count`,
`message`.`plan_id`,
`message`.`application_id`,
`incident`.`context`
FROM `message`
JOIN `incident` ON `message`.`incident_id` = `incident`.`id`
JOIN `plan_notification` ON `message`.`plan_notification_id` = `plan_notification`.`id`
JOIN `plan` ON `message`.`plan_id` = `plan`.`id`
WHERE `incident`.`active` = 1
AND `incident`.`current_step`=`plan`.`step_count`
AND `step` = `incident`.`current_step`
GROUP BY `incident`.`id`, `message`.`plan_notification_id`, `message`.`target_id`
) as `inner`
GROUP BY `incident_id`, `plan_notification_id`
HAVING `max_count` = `max` AND BIT_AND(`age` > `wait`) = 1
) as `exhausted_incidents`'''
QUEUE_SQL = '''SELECT
`incident_id`,
`plan_id`,
`plan_notification_id`,
max(`count`) as `count`,
`max`,
`age`,
`wait`,
`step`,
`current_step`,
`step_count`
FROM (
SELECT
`message`.`incident_id` as `incident_id`,
`message`.`plan_notification_id` as `plan_notification_id`,
count(`message`.`id`) as `count`,
`plan_notification`.`repeat` + 1 as `max`,
TIMESTAMPDIFF(SECOND, max(`message`.`created`), NOW()) as `age`,
`plan_notification`.`wait` as `wait`,
`plan_notification`.`step` as `step`,
`incident`.`current_step`,
`plan`.`step_count`,
`message`.`plan_id`,
`message`.`application_id`,
`incident`.`context`
FROM `message`
JOIN `incident` ON `message`.`incident_id` = `incident`.`id`
JOIN `plan_notification` ON `message`.`plan_notification_id` = `plan_notification`.`id`
JOIN `plan` ON `message`.`plan_id` = `plan`.`id`
WHERE `incident`.`active` = 1
GROUP BY `incident`.`id`, `message`.`plan_notification_id`, `message`.`target_id`
) as `inner`
GROUP BY `incident_id`, `plan_notification_id`
HAVING `age` > `wait` AND (`count` < `max`
OR (`count` = `max` AND `step` = `current_step`
AND `step` < `step_count`))'''
UPDATE_INCIDENT_SQL = '''UPDATE `incident` SET `current_step`=%s WHERE `id`=%s'''
INVALIDATE_INCIDENT = '''UPDATE `incident` SET `active`=0 WHERE `id`=%s'''
INSERT_MESSAGE_SQL = '''INSERT INTO `message`
(`created`, `plan_id`, `plan_notification_id`, `incident_id`, `application_id`, `target_id`, `priority_id`, `body`)
VALUES (NOW(), %s,%s,%s,%s,%s,%s,%s)'''
UNSENT_MESSAGES_SQL = '''SELECT
`message`.`body`,
`message`.`id` as `message_id`,
`target`.`name` as `target`,
`priority`.`name` as `priority`,
`priority`.`id` as `priority_id`,
`application`.`name` as `application`,
`plan`.`name` as `plan`,
`plan`.`id` as `plan_id`,
`incident`.`id` as `incident_id`,
`incident`.`context` as `context`,
`incident`.`created` as `incident_created`,
`plan_notification`.`template` as `template`,
`dynamic_target`.`name` as `dynamic_target`
FROM `message`
JOIN `application` ON `message`.`application_id`=`application`.`id`
JOIN `priority` ON `message`.`priority_id`=`priority`.`id`
LEFT OUTER JOIN `target` ON `message`.`target_id`=`target`.`id`
LEFT OUTER JOIN `plan` ON `message`.`plan_id`=`plan`.`id`
LEFT OUTER JOIN `plan_notification` ON `message`.`plan_notification_id`=`plan_notification`.`id`
LEFT OUTER JOIN `incident` ON `message`.`incident_id`=`incident`.`id`
LEFT OUTER JOIN `dynamic_plan_map` ON `incident`.`id` = `dynamic_plan_map`.`incident_id`
AND `plan_notification`.`dynamic_index` = `dynamic_plan_map`.`dynamic_index`
LEFT OUTER JOIN `target` `dynamic_target` ON `dynamic_target`.`id` = `dynamic_plan_map`.`target_id`
WHERE `message`.`active`=1'''
SENT_MESSAGE_BATCH_SQL = '''UPDATE `message`
SET `destination`=%%s,
`mode_id`=%%s,
`template_id`=%%s,
`batch`=%%s,
`active`=FALSE,
`sent`=NOW()
WHERE `id` IN %s'''
SENT_MESSAGE_SQL = '''UPDATE `message`
SET `destination`=%s,
`mode_id`=%s,
`template_id`=%s,
`active`=FALSE,
`sent`=NOW()
WHERE `id`=%s'''
UPDATE_MESSAGE_BODY_SQL = '''UPDATE `message`
SET `body`=%s,
`subject`=%s
WHERE `id` IN %s'''
PRUNE_OLD_AUDIT_LOGS_SQL = '''DELETE FROM `message_changelog` WHERE `date` < DATE_SUB(CURDATE(), INTERVAL 3 MONTH)'''
# When a rendered message body is longer than this number of characters, drop it.
MAX_MESSAGE_BODY_LENGTH = 40000
MAX_MESSAGE_RETRIES = 2
# logging
logger = logging.getLogger()
formatter = logging.Formatter('%(asctime)s %(levelname)s %(name)s %(message)s')
log_file = os.environ.get('SENDER_LOG_FILE')
if log_file:
ch = logging.handlers.RotatingFileHandler(log_file, mode='a', maxBytes=10485760, backupCount=10)
else:
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger.setLevel(logging.INFO)
logger.addHandler(ch)
pidfile = os.environ.get('SENDER_PIDFILE')
if pidfile:
try:
pid = os.getpid()
with open(pidfile, 'w') as h:
h.write('%s\n' % pid)
logger.info('Wrote pid %s to %s', pid, pidfile)
except IOError:
logger.exception('Failed writing pid to %s', pidfile)
# rate limiting data structure message key -> minute -> count
# used to calcuate if a new message exceeds the rate limit
# and needs to be queued
plan_aggregate_windows = {}
# all messages waiting to be queue across all keys
messages = {}
# queue of message_ids waiting to be sent for a given key
queues = {}
# time last message was queued while in aggregation mode for a given key
# used to determine if a new message should be aggregated or if aggregation should end
aggregation = {}
# last time a batch was sent for a given key
# used to determine if it's time to send the next batch
sent = {}
# queue for messages entering the system
# this sets the ground work for not having to poll the DB for messages
message_queue = queue.Queue()
# Quota object used for rate limiting
quota = None
# Coordinator object for sender master election
coordinator = None
# Mode -> [{'greenlet': greenlet, 'kill_set': gevent.Event}]
worker_tasks = defaultdict(list)
# MX -> [{'greenlet': greenlet, 'kill_set': gevent.Event}]
autoscale_email_worker_tasks = defaultdict(list)
# support the 2nd control+c force exiting sender without waiting for tasks to finish
shutdown_started = False
# Set of active message IDs currently being sent, to avoid re-sending messages that are currently
# just blocked on a downstream such as smtp
message_ids_being_sent = set()
default_sender_metrics = {
'email_cnt': 0, 'email_total': 0, 'email_fail': 0, 'email_sent': 0, 'email_max': 0,
'email_min': 0, 'email_avg': 0, 'im_cnt': 0, 'im_total': 0, 'im_fail': 0, 'im_sent': 0,
'im_max': 0, 'im_min': 0, 'im_avg': 0, 'slack_cnt': 0, 'slack_total': 0, 'slack_fail': 0,
'slack_sent': 0, 'slack_max': 0, 'slack_min': 0, 'slack_avg': 0, 'drop_cnt': 0,
'drop_total': 0, 'drop_fail': 0, 'drop_sent': 0, 'drop_max': 0, 'drop_min': 0, 'drop_avg': 0,
'sms_cnt': 0, 'sms_total': 0, 'sms_fail': 0, 'sms_sent': 0, 'sms_max': 0,
'sms_min': 0, 'sms_avg': 0, 'call_cnt': 0, 'call_total': 0,
'call_fail': 0, 'call_sent': 0, 'call_max': 0, 'call_min': 0, 'call_avg': 0, 'task_failure': 0,
'oncall_error': 0, 'role_target_lookup_error': 0, 'target_not_found': 0, 'message_send_cnt': 0,
'notification_cnt': 0, 'api_request_cnt': 0, 'api_request_timeout_cnt': 0,
'rpc_message_pass_success_cnt': 0, 'rpc_message_pass_fail_cnt': 0,
'slave_message_send_success_cnt': 0, 'slave_message_send_fail_cnt': 0,
'msg_drop_length_cnt': 0, 'send_queue_gets_cnt': 0, 'send_queue_puts_cnt': 0,
'send_queue_email_size': 0, 'send_queue_im_size': 0, 'send_queue_slack_size': 0, 'send_queue_call_size': 0,
'send_queue_sms_size': 0, 'send_queue_drop_size': 0, 'new_incidents_cnt': 0, 'workers_respawn_cnt': 0,
'message_retry_cnt': 0, 'message_ids_being_sent_cnt': 0, 'notifications': 0, 'deactivation': 0,
'new_msg_count': 0, 'poll': 0, 'queue': 0, 'aggregations': 0, 'hipchat_cnt': 0, 'hipchat_fail': 0,
'hipchat_total': 0, 'hipchat_sent': 0, 'hipchat_max': 0, 'hipchat_min': 0
}
# TODO: make this configurable
target_fallback_mode = 'email'
should_mock_gwatch_renewer = False
config = None
def create_messages(incident_id, plan_notification_id):
application_id = cache.incidents[incident_id]['application_id']
plan_notification = cache.plan_notifications[plan_notification_id]
if plan_notification['role_id'] is None and plan_notification['target_id'] is None:
dynamic_info = cache.dynamic_plan_map[incident_id][plan_notification['dynamic_index']]
role = cache.roles[dynamic_info['role_id']]['name']
target = cache.targets[dynamic_info['target_id']]['name']
else:
role = cache.roles[plan_notification['role_id']]['name']
target = cache.targets[plan_notification['target_id']]['name']
# find role/priority from plan_notification_id
try:
names = cache.targets_for_role(role, target)
except IrisRoleLookupException as e:
names = None
metrics.incr('role_target_lookup_error')
lookup_fail_reason = str(e)
else:
lookup_fail_reason = None
priority_id = plan_notification['priority_id']
redirect_to_plan_owner = False
body = ''
if not names:
# if message is optional don't bother the creator, simply return true instead
if plan_notification['optional']:
return True
# Try to get creator of the plan and nag them instead
name = None
try:
name = cache.plans[plan_notification['plan_id']]['creator']
except (KeyError, TypeError):
pass
if not name:
logger.error(('Failed to find targets for incident %s, plan_notification_id: %s, '
'role: %s, target: %s, result: %s and failed looking '
'up the plan\'s creator'),
incident_id, plan_notification_id, role, target, names)
return False
try:
priority_id = api_cache.priorities['low']['id']
except KeyError:
logger.error(('Failed to find targets for incident %s, plan_notification_id: %s, '
'role: %s, target: %s, result: %s and failed looking '
'up ID for low priority'),
incident_id, plan_notification_id, role, target, names)
return False
logger.error(('Failed to find targets for incident %s, plan_notification_id: %s, '
'role: %s, target: %s, result: %s. '
'Reaching out to %s instead and lowering priority to low (%s)'),
incident_id, plan_notification_id, role, target, names, name, priority_id)
body = ('You are receiving this as you created this plan and we can\'t resolve'
' %s of %s at this time%s.\n\n') % (role, target, ': %s' % lookup_fail_reason if lookup_fail_reason else '')
names = [name]
redirect_to_plan_owner = True
connection = db.engine.raw_connection()
cursor = connection.cursor()
for name in names:
t = cache.target_names[name]
if t:
target_id = t['id']
cursor.execute(INSERT_MESSAGE_SQL,
(plan_notification['plan_id'], plan_notification_id, incident_id,
application_id, target_id, priority_id, body))
if redirect_to_plan_owner:
# needed for the lastrowid to exist in the DB to satisfy the constraint
connection.commit()
auditlog.message_change(
cursor.lastrowid,
auditlog.TARGET_CHANGE,
role + '|' + target,
name,
lookup_fail_reason or 'Changing target to plan owner as we failed resolving original target')
else:
metrics.incr('target_not_found')
logger.warn('Failed to notify plan creator; no active target found: %s', name)
connection.commit()
cursor.close()
connection.close()
return True
def deactivate():
# deactivate incidents that have expired
logger.info('[-] start deactivate task...')
start_deactivation = time.time()
connection = db.engine.raw_connection()
cursor = connection.cursor()
max_retries = 3
# this deadlocks sometimes. try until it doesn't.
for i in xrange(1, max_retries + 1):
try:
cursor.execute(GET_INACTIVE_IDS_SQL)
ids = tuple(r[0] for r in cursor)
if ids:
cursor.execute(INACTIVE_SQL, (ids,))
connection.commit()
break
except Exception:
if i == max_retries:
logger.exception('Failed running deactivate query. (Try %s/%s)', i, max_retries)
else:
logger.warn('Deadlocked running deactivate query. (Try %s/%s)', i, max_retries)
sleep(.2)
cursor.close()
connection.close()
metrics.set('deactivation', time.time() - start_deactivation)
logger.info('[*] deactivate task finished')
def escalate():
# make notifications for things that should repeat or escalate
logger.info('[-] start escalate task...')
# first, handle new incidents
start_notifications = time.time()
connection = db.engine.raw_connection()
cursor = connection.cursor()
cursor.execute(NEW_INCIDENTS)
escalations = {}
for incident_id, created, plan_id, context, application in cursor:
escalations[incident_id] = (plan_id, 1)
# create tracking message if configured
plan = cache.plans[plan_id]
tracking_type = plan['tracking_type']
tracking_key = plan['tracking_key']
tracking_template = plan['tracking_template']
app_tracking_template = tracking_template.get(application) if tracking_template else None
if tracking_type and tracking_key and app_tracking_template:
# plan defines tracking notifications
context = ujson.loads(context)
context['iris'] = {
'incident_id': incident_id,
'plan': plan['name'],
'plan_id': plan_id,
'application': application,
'incident_created': created,
}
if tracking_type == 'email':
tracking_message = {
'noreply': True,
'destination': tracking_key,
'mode': tracking_type
}
try:
subject = app_tracking_template['email_subject'].render(**context)
except Exception as e:
subject = 'plan %s - tracking notification subject failed to render: %s' % (plan['name'], e)
logger.exception(subject)
tracking_message['email_subject'] = subject
try:
body = app_tracking_template['email_text'].render(**context)
except Exception as e:
body = 'plan %s - tracking notification body failed to render: %s' % (plan['name'], e)
logger.exception(body)
tracking_message['email_text'] = body
email_html_tpl = app_tracking_template.get('email_html')
if email_html_tpl:
try:
html_body = email_html_tpl.render(**context)
except Exception as e:
html_body = 'plan %s - tracking notification html body failed to render: %s' % (plan['name'], e)
logger.exception(html_body)
tracking_message['email_html'] = html_body
else:
tracking_message = {
'noreply': True,
'destination': tracking_key,
'mode': tracking_type
}
try:
body = app_tracking_template['body'].render(**context)
except Exception as e:
body = 'plan %s - tracking notification body failed to render: %s' % (plan['name'], e)
logger.exception(body)
tracking_message['body'] = body
message_send_enqueue(tracking_message)
cursor.close()
new_incidents_count = len(escalations)
metrics.set('new_incidents_cnt', new_incidents_count)
logger.info('[*] %s new incidents', new_incidents_count)
# then, fetch message count for current incidents
msg_count = 0
cursor = connection.cursor(db.dict_cursor)
cursor.execute(QUEUE_SQL)
for n in cursor.fetchall():
if n['count'] < n['max']:
if create_messages(n['incident_id'], n['plan_notification_id']):
msg_count += 1
else:
escalations[n['incident_id']] = (n['plan_id'], n['current_step'] + 1)
for incident_id, (plan_id, step) in escalations.iteritems():
plan = cache.plans[plan_id]
steps = plan['steps'].get(step, [])
if steps:
step_msg_cnt = 0
for plan_notification_id in steps:
if create_messages(incident_id, plan_notification_id):
step_msg_cnt += 1
if step == 1 and step_msg_cnt == 0:
# no message created due to role look up failure, reset step to
# 0 for retry
step = 0
cursor.execute(UPDATE_INCIDENT_SQL, (step, incident_id))
msg_count += step_msg_cnt
else:
logger.error('plan id %d has no steps, incident id %d is invalid', plan_id, incident_id)
cursor.execute(INVALIDATE_INCIDENT, incident_id)
connection.commit()
cursor.close()
connection.close()
logger.info('[*] %s new messages', msg_count)
logger.info('[*] escalate task finished')
metrics.set('notifications', time.time() - start_notifications)
def aggregate(now):
# see if it's time to send the batches
logger.info('[-] start aggregate task - queued: %s', len(messages))
start_aggregations = time.time()
connection = db.engine.raw_connection()
cursor = connection.cursor()
cursor.execute('SELECT `id` FROM `message` WHERE active=1')
all_actives = {r[0] for r in cursor}
cursor.close()
connection.close()
for key in queues.keys():
aggregation_window = cache.plans[key[0]]['aggregation_window']
if now - sent.get(key, 0) >= aggregation_window:
aggregated_message_ids = queues[key]
active_message_ids = aggregated_message_ids & all_actives
l = len(active_message_ids)
if l == 1:
m = messages.pop(next(iter(active_message_ids)))
logger.info('aggregate - %(message_id)s pushing to send queue', m)
message_send_enqueue(m)
elif l > 1:
uuid = uuid4().hex
m = messages[next(iter(active_message_ids))]
logger.info('aggregate - %s pushing to send queue', uuid)
m['batch_id'] = uuid
# Cast from set to list, as sets are not msgpack serializable
m['aggregated_ids'] = list(active_message_ids)
message_send_enqueue(m)
for message_id in aggregated_message_ids:
messages.pop(message_id, None)
logger.info('[-] purged %s from messages %s remaining', active_message_ids, len(messages))
del queues[key]
sent[key] = now
inactive_message_ids = messages.viewkeys() - all_actives
logger.info('[x] dropped %s inactive messages from claimed incidents, %s remain',
len(inactive_message_ids), len(messages))
# remove inactive message from the queue
for message_id in inactive_message_ids:
messages.pop(message_id, None)
metrics.set('aggregations', time.time() - start_aggregations)
logger.info('[*] aggregate task finished - queued: %s', len(messages))
def poll():
# poll unsent messages
logger.info('[-] start send task...')
start_send = time.time()
connection = db.engine.raw_connection()
cursor = connection.cursor(db.dict_cursor)
if messages:
cursor.execute(UNSENT_MESSAGES_SQL + ' AND `message`.`id` NOT IN %s', [tuple(messages)])
else:
cursor.execute(UNSENT_MESSAGES_SQL)
new_msg_count = cursor.rowcount
queued_msg_cnt = len(messages)
metrics.set('new_msg_count', new_msg_count)
logger.info('%d new messages waiting in database - queued: %d', new_msg_count, queued_msg_cnt)
for m in cursor:
# Set dynamic target as target if applicable
if m.get('dynamic_target') and m.get('target') is None:
m['target'] = m['dynamic_target']
# iris's own email response does not have context since content and
# subject are already set
if m.get('context'):
context = ujson.loads(m['context'])
# inject meta variables
context['iris'] = {k: m[k] for k in m if k != 'context'}
m['context'] = context
message_queue.put(m)
metrics.set('poll', time.time() - start_send)
metrics.set('queue', len(messages))
logger.info('[*] send task finished')
cursor.close()
connection.close()
def fetch_and_prepare_message():
now = time.time()
m = message_queue.get()
message_id = m['message_id']
plan_id = m['plan_id']
if plan_id is None:
message_send_enqueue(m)
return
plan = cache.plans[plan_id]
# queue key
key = (m['plan_id'], m['application'], m['priority'], m['target'])
# should this message be aggregated?
aggregate = False
last_aggregation = aggregation.get(key)
if last_aggregation:
if now - last_aggregation > plan['aggregation_reset']:
# it's been long enough since the last message
# return to immediate sending mode and clear aggregations
del aggregation[key]
try:
# if we have sent batches before delete the entry for last sent
del sent[key]
except KeyError:
pass
else:
# still getting enough messages fast enough to remain in aggregation
aggregation[key] = now
aggregate = True
if aggregate:
# we are still in a previous aggregation mode
queues.setdefault(key, set()).add(message_id)
messages[message_id] = m
else:
# does this message trigger aggregation?
window = plan_aggregate_windows.setdefault(key, defaultdict(int))
for bucket in window.keys():
if now - bucket > plan['threshold_window']:
del window[bucket]
window[now] += 1
if sum(window.itervalues()) > plan['threshold_count']:
# too many messages for the aggregation key - enqueue
# add message id to aggregation queue
queues.setdefault(key, set()).add(message_id)
# add message id to queue for deduping
messages[message_id] = m
# initialize last sent tracker
sent[key] = now
# initialize aggregation indicator
aggregation[key] = now
# TODO: also render message content here?
audit_msg = 'Aggregated with key (%s, %s, %s, %s)' % key
spawn(auditlog.message_change, m['message_id'], auditlog.SENT_CHANGE, '', '', audit_msg)
else:
# cleared for immediate sending
message_send_enqueue(m)
def send():
logger.info('[-] start send loop...')
while True:
fetch_and_prepare_message()
logger.info('[*] send loop finished...')
def set_target_fallback_mode(message):
try:
connection = db.engine.raw_connection()
cursor = connection.cursor()
cursor.execute('''SELECT `destination`, `mode`.`name`, `mode`.`id`
FROM `target`
JOIN `target_contact` ON `target_contact`.`target_id` = `target`.`id`
JOIN `mode` ON `mode`.`id` = `target_contact`.`mode_id`
WHERE `target`.`name` = %s AND `mode`.`name` = %s''',
(message['target'], target_fallback_mode))
[(destination, mode, mode_id)] = cursor
cursor.close()
connection.close()
old_mode = message.get('mode', '')
message['destination'] = destination
message['mode'] = mode
message['mode_id'] = mode_id
update_message_mode(message)
message_id = message.get('message_id')
if message_id:
auditlog.message_change(
message_id, auditlog.MODE_CHANGE, old_mode, message['mode'],
'Changing mode due to original mode failure')
return True
# target doesn't have email either - bail
except ValueError:
logger.exception('target does not have mode(%s) %r', target_fallback_mode, message)
message['destination'] = message['mode'] = message['mode_id'] = None
return False
def set_target_contact_by_priority(message):
session = db.Session()
result = session.execute('''
SELECT `target_contact`.`destination` AS dest, `mode`.`name` AS mode_name, `mode`.`id` AS mode_id
FROM `mode`
JOIN `target` ON `target`.`name` = :target
JOIN `target_type` ON `target_type`.`id` = `target`.`type_id`
JOIN `application` ON `application`.`name` = :application
-- left join because the "drop" mode isn't going to have a target_contact entry
LEFT JOIN `target_contact` ON `target_contact`.`mode_id` = `mode`.`id` AND `target_contact`.`target_id` = `target`.`id`
WHERE mode.id = IFNULL((
SELECT `target_application_mode`.`mode_id`
FROM `target_application_mode`
WHERE `target_application_mode`.`target_id` = target.id AND
`target_application_mode`.`application_id` = `application`.`id` AND
`target_application_mode`.`priority_id` = :priority_id
), IFNULL(
-- 2. Lookup default setting for this app
(
SELECT `default_application_mode`.`mode_id`
FROM `default_application_mode`
WHERE `default_application_mode`.`priority_id` = :priority_id AND
`default_application_mode`.`application_id` = `application`.`id`
), IFNULL(
-- 3. lookup default user setting
(
SELECT `target_mode`.`mode_id`
FROM `target_mode`
WHERE `target_mode`.`target_id` = target.id AND
`target_mode`.`priority_id` = :priority_id
), (
-- 4. lookup default iris setting
SELECT `mode_id`
FROM `priority`
WHERE `id` = :priority_id
)
)
)
)
-- Make sure this mode is allowed for this application. Eg important apps can't drop.
AND EXISTS (SELECT 1 FROM `application_mode`
WHERE `application_mode`.`mode_id` = `mode`.`id`
AND `application_mode`.`application_id` = `application`.`id`)
-- And ensure this only works for users
AND `target_type`.`name` = 'user'
''', message)
try:
[(destination, mode, mode_id)] = result
except ValueError:
raise
finally:
session.close()
if not destination and mode != 'drop':
logger.error('Did not find destination for message %s and mode is not drop', message)
return False
message['destination'] = destination
message['mode'] = mode
message['mode_id'] = mode_id
return True
def set_target_contact(message):
# If we already have a destination set (eg incident tracking emails or literal_target notifications) no-op this
if 'destination' in message:
return True
# returns True if contact has been set (even if it has been changed to the fallback). Otherwise, returns False
try:
if 'mode' in message or 'mode_id' in message:
# for out of band notification, we already have the mode *OR*
# mode_id set by API
connection = db.engine.raw_connection()
cursor = connection.cursor()
cursor.execute('''
SELECT `destination` FROM `target_contact`
JOIN `target` ON `target`.`id` = `target_contact`.`target_id`
JOIN `target_type` on `target_type`.`id` = `target`.`type_id`
WHERE `target`.`name` = %(target)s
AND `target_type`.`name` = 'user'
AND (`target_contact`.`mode_id` = %(mode_id)s OR `target_contact`.`mode_id` = (SELECT `id` FROM `mode` WHERE `name` = %(mode)s))
LIMIT 1
''', {'target': message['target'], 'mode_id': message.get('mode_id'), 'mode': message.get('mode')})
message['destination'] = cursor.fetchone()[0]
cursor.close()
connection.close()
result = True
else:
# message triggered by incident will only have priority
result = set_target_contact_by_priority(message)
if result:
cache.target_reprioritization(message)
else:
logger.warn('target does not have mode %r', message)
result = set_target_fallback_mode(message)
return result
except (ValueError, TypeError):
logger.exception('target does not have mode %r', message)
return set_target_fallback_mode(message)
def render(message):
if not message.get('template'):
if message.get('message_id'):
# email response from iris does not use template this means the
# message content is already in DB
connection = db.engine.raw_connection()
cursor = connection.cursor()
cursor.execute('SELECT `body`, `subject` FROM `message` WHERE `id` = %s',
message['message_id'])
msg_content = cursor.fetchone()
message['body'], message['subject'] = msg_content[0], msg_content[1]
cursor.close()
connection.close()
else:
# out of band message does not have id and should already have the
# content populated
return
elif 'aggregated_ids' in message:
message['subject'] = '[%%(application)s] %s messages from plan %%(plan)s' % len(message['aggregated_ids']) % message
message['body'] = 'Batch ID: %(batch_id)s' % message
message['template_id'] = None
else:
if message.get('body') is None:
message['body'] = ''
error = None
try:
template = cache.templates[message['template']]
try:
application_template = template[message['application']]
try:
# When we want to "render" a dropped message, treat it as if it's an email
mode_template = application_template['email' if message['mode'] == 'drop' else message['mode']]
try:
message['subject'] = mode_template['subject'].render(**message['context'])
except Exception as e:
error = 'template %(template)s - %(application)s - %(mode)s - subject failed to render: ' + str(e)
try:
message['body'] += mode_template['body'].render(**message['context'])
except Exception as e:
error = 'template %(template)s - %(application)s - %(mode)s - body failed to render: ' + str(e)
message['template_id'] = template['id']
except KeyError:
error = 'template %(template)s - %(application)s does not have mode %(mode)s'
except KeyError:
error = 'template %(template)s does not have application %(application)s'
except KeyError:
error = 'template %(template)s does not exist'
if error:
# TODO:
# define application default template here
# additionally, instead of repr() as the final message render
# format define a generic template that will work for all contexts
# - even those that are invalid as a final final format maybe repr or pprint
logger.error(error, message)
message['subject'] = '%(message_id)s Iris failed to render your message' % message
message['body'] = 'Failed rendering message.\n\nContext: %s\n\nError: %s' % (repr(message), error % message)
message['template_id'] = None
else:
if config.get('enable_gmail_oneclick') and message['mode'] == 'email' and 'incident_id' in message:
oneclick_url = generate_oneclick_url(config, {
'msg_id': message['message_id'],
'email_address': message['destination'],
'cmd': 'claim'
})
additional_body = oneclick_email_markup % {
'url': oneclick_url,
'incident_id': message['incident_id']
}
message['extra_html'] = additional_body
def mark_message_as_sent(message):
connection = db.engine.raw_connection()
params = [
message['destination'],
message['mode_id'],
message.get('template_id'),
]
if 'aggregated_ids' in message:
sql = SENT_MESSAGE_BATCH_SQL % connection.escape(message['aggregated_ids'])
params.append(message['batch_id'])
message_ids = message['aggregated_ids']
else:
sql = SENT_MESSAGE_SQL
params.append(message['message_id'])
message_ids = [message['message_id']]
cursor = connection.cursor()
if not message['subject']:
message['subject'] = ''
logger.warn('Message id %s has blank subject', message.get('message_id', '?'))
max_retries = 3
# this deadlocks sometimes. try until it doesn't.
for i in xrange(1, max_retries + 1):
try:
cursor.execute(sql, params)
connection.commit()
break
except DataError:
logger.exception('Failed updating message metadata status (message ID %s) (application %s)', message.get('message_id', '?'), message.get('application', '?'))
break
except Exception:
if i == max_retries:
logger.exception('Failed running sent message update query. (Try %s/%s)', i, max_retries)
else:
logger.warn('Failed running sent message update query. (Try %s/%s)', i, max_retries)
sleep(.2)
# Clean messages cache
for message_id in message_ids:
messages.pop(message_id, None)
# Update subject and body separately, as they may fail and we don't necessarily care if they do
if len(message['subject']) > 255:
message['subject'] = message['subject'][:255]
if len(message['body']) > MAX_MESSAGE_BODY_LENGTH:
logger.warn('Message id %s has a ridiculously long body (%s chars). Truncating it.',
message.get('message_id', '?'), len(message['body']))
message['body'] = message['body'][:MAX_MESSAGE_BODY_LENGTH]
if 'aggregated_ids' in message:
update_ids = tuple(message['aggregated_ids'])
else:
update_ids = tuple([message['message_id']])
max_retries = 3
# this deadlocks sometimes. try until it doesn't.
for i in xrange(1, max_retries + 1):
try:
cursor.execute(UPDATE_MESSAGE_BODY_SQL, (message['body'], message['subject'], update_ids))
connection.commit()
break
except DataError:
logger.exception('Failed updating message body+subject (message IDs %s) (application %s)', update_ids, message.get('application', '?'))
break
except Exception:
if i == max_retries:
logger.exception('Failed updating message body+subject (message IDs %s) (application %s) (Try %s/%s)', update_ids, message.get('application', '?'), i, max_retries)
else:
logger.warn('Failed updating message body+subject (message IDs %s) (application %s) (Try %s/%s)', update_ids, message.get('application', '?'), i, max_retries)
sleep(.2)
cursor.close()
connection.close()
def update_message_sent_status(message, status):
message_id = message.get('message_id')
if not message_id:
return
mode = message.get('mode')
if not mode:
return
# Don't track this for twilio as those are kept track of separately. Make
# use of this for email, and, as a side effect of that for slack
if mode in ('sms', 'call'):
return
session = db.Session()
try:
session.execute('''INSERT INTO `generic_message_sent_status` (`message_id`, `status`)
VALUES (:message_id, :status)
ON DUPLICATE KEY UPDATE `status` = :status''',
{'message_id': message_id, 'status': status})
session.commit()
except (DataError, IntegrityError, InternalError):
logger.exception('Failed setting message sent status for message %s', message)
finally: