forked from tableau/VizAlerts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vizalerts.py
1660 lines (1369 loc) · 78.5 KB
/
vizalerts.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
#! python
# -*- coding: utf-8 -*-
# Script to generate conditional automation against published views from a Tableau Server instance
__author__ = 'Matt Coles'
__credits__ = 'Jonathan Drummey'
# generic modules
import logging
import sys
import os
import traceback
import shutil
import csv
import datetime
import re
import time
import smtplib
import fileinput
from os.path import abspath, basename, expanduser
from operator import itemgetter
import posixpath
from PyPDF2 import PdfFileReader, PdfFileMerger
from collections import OrderedDict
# Tableau modules
import tabUtil
from tabUtil import tabhttp
# PostgreSQL module
import psycopg2
import psycopg2.extras
import psycopg2.extensions
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
# added for MIME handling
from itertools import chain
from errno import ECONNREFUSED
from mimetypes import guess_type
from subprocess import Popen, PIPE
import email.encoders
from email.encoders import encode_base64
from cStringIO import StringIO
from email.header import Header
from email import Charset
from email.generator import Generator
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from socket import error as SocketError
import codecs
from codecs import decode
from codecs import encode
# Global Variable Definitions
valid_conf_keys = \
['db.database',
'db.host',
'db.port',
'db.pw',
'db.query',
'db.user',
'log.dir',
'log.dir.file_retention_seconds',
'log.level',
'schedule.state.dir',
'server',
'server.version',
'server.user',
'smtp.address.from',
'smtp.notify_subscriber_on_failure',
'smtp.address.to',
'smtp.alloweddomains',
'smtp.serv',
'server.ssl',
'server.certcheck',
'smtp.subject',
'temp.dir',
'temp.dir.file_retention_seconds',
'trusted.clientip',
'trusted.useclientip',
'viz.data.maxrows',
'viz.data.timeout',
'viz.png.height',
'viz.png.width']
required_email_fields =\
[' Email To *',
' Email Subject *',
' Email Body *']
# appended to the bottom of all user-facing emails
# expecting bodyfooter.format(subscriberemail, vizurl, viewname)
bodyfooter = u'<br><br><font size="2"><i>This VizAlerts email generated on behalf of {}, from view <a href="{}">' \
u'{}</a></i></font>'
# appended under the bodyfooter, but only for Simple Alerts
# expecting unsubscribe_footer.format(subscriptionsurl)
unsubscribe_footer = u'<br><font size="2"><i><a href="{}">Manage my subscription settings</a></i></font>'
# regular expression used to split recipient address strings into separate email addresses
EMAIL_RECIP_SPLIT_REGEX = u'[; ,]*'
# name of the file used for maintaining subscriptions state in schedule.state.dir
SCHEDULE_STATE_FILENAME = u'vizalerts.state'
# reserved strings for Advanced Alerts embedding
IMAGE_PLACEHOLDER = u'VIZ_IMAGE()'
PDF_PLACEHOLDER = u'VIZ_PDF()'
CSV_PLACEHOLDER = u'VIZ_CSV()'
TWB_PLACEHOLDER = u'VIZ_TWB()'
DEFAULT_FOOTER = u'VIZALERTS_FOOTER()' # special string for embedding the default footer in an Advanced Alert
VIZLINK_PLACEHOLDER = u'VIZ_LINK()' # special string for embedding HTML links in Advanced Alert
# reserved strings for Advanced Alerts arguments
EXPORTFILENAME_ARGUMENT = u'filename'
EXPORTFILEPATH_ARGUMENT = u'exportfilepath'
MERGEPDF_ARGUMENT = u'mergepdf'
VIZLINK_ARGUMENT = u'vizlink'
RAWLINK_ARGUMENT = u'rawlink'
ARGUMENT_DELIMITER = u'|'
# code from https://github.com/mitsuhiko/flask/blob/50dc2403526c5c5c67577767b05eb81e8fab0877/flask/helpers.py#L80
# what separators does this operating system provide that are not a slash?
# used in VizAlerts for verifying custom filenames and paths for appended attachments and exported attachments
_os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep]
if sep not in (None, '/'))
class UnicodeCsvReader(object):
"""Code from http://stackoverflow.com/questions/1846135/general-unicode-utf-8-support-for-csv-files-in-python-2-6"""
def __init__(self, f, encoding="utf-8", **kwargs):
self.csv_reader = csv.reader(f, **kwargs)
self.encoding = encoding
def __iter__(self):
return self
def next(self):
# read and split the csv row into fields
row = self.csv_reader.next()
# now decode
return [unicode(cell, self.encoding) for cell in row]
@property
def line_num(self):
return self.csv_reader.line_num
class UnicodeDictReader(csv.DictReader):
"""Returns a DictReader that supports Unicode"""
"""Code from http://stackoverflow.com/questions/1846135/general-unicode-utf-8-support-for-csv-files-in-python-2-6"""
def __init__(self, f, encoding="utf-8", fieldnames=None, **kwds):
csv.DictReader.__init__(self, f, fieldnames=fieldnames, **kwds)
self.reader = UnicodeCsvReader(f, encoding=encoding, **kwds)
def main(configfile=u'.\\config\\vizalerts.yaml',
logfile=u'.\\logs\\vizalerts.log'):
# initialize logging
global logger
logger = logging.getLogger()
if not len(logger.handlers):
logger = tabUtil.LoggerQuickSetup(logfile, log_level=logging.DEBUG)
# load configs from yaml file
global configs
configs = validate_conf(configfile, logger)
# set the log level based on the config file
logger.setLevel(configs["log.level"])
# cleanup old temp files
try:
cleanup_dir(configs["temp.dir"], configs["temp.dir.file_retention_seconds"])
except OSError as e:
# Send mail to the admin informing them of the problem, but don't quit
errormessage = u'OSError: Unable to cleanup temp directory {}, error: {}'.format(configs["temp.dir"], e)
logger.error(errormessage)
send_email(configs["smtp.address.from"], configs["smtp.address.to"], configs["smtp.subject"], errormessage)
except Exception as e:
errormessage = u'Unable to cleanup temp directory {}, error: {}'.format(configs["temp.dir"], e)
logger.error(errormessage)
send_email(configs["smtp.address.from"], configs["smtp.address.to"], configs["smtp.subject"], errormessage)
# cleanup old log files
try:
cleanup_dir(configs["log.dir"], configs["log.dir.file_retention_seconds"])
except OSError as e:
# Send mail to the admin informing them of the problem, but don't quit
errormessage = u'OSError: Unable to cleanup log directory {}, error: {}'.format(configs["temp.dir"], e)
logger.error(errormessage)
send_email(configs["smtp.address.from"], configs["smtp.address.to"], configs["smtp.subject"], errormessage)
except Exception as e:
errormessage = u'Unable to cleanup log directory {}, error: {}'.format(configs["temp.dir"], e)
logger.error(errormessage)
send_email(configs["smtp.address.from"], configs["smtp.address.to"], configs["smtp.subject"], errormessage)
# test ability to connect to Tableau Server and obtain a trusted ticket
trusted_ticket_test()
# get the views to process
try:
views = get_views()
logger.info(u'Processing a total of {} views'.format(len(views)))
except Exception as e:
errormessage = u'Unable to get views to process, error: {}'.format(e.message)
logger.error(errormessage)
quit_script(errormessage)
process_views(views)
def process_views(views):
"""Iterate through the list of applicable views, and process each"""
for view in views:
logger.debug(u'Processing subscription_id {}, view_id {}, site_name {}, customized view id {}, '
'view_name {}'.format(
view["subscription_id"],
view["view_id"],
view["site_name"],
view["customized_view_id"],
view["view_name"]))
sitename = unicode(view["site_name"]).replace('Default', '')
viewurlsuffix = view['view_url_suffix']
viewname = unicode(view['view_name'])
timeout_s = view['timeout_s']
subscribersysname = unicode(view['subscriber_sysname'].decode('utf-8'))
subscriberemail = view['subscriber_email']
# get the domain of the subscriber's user
subscriberdomain = None
if view['subscriber_domain'] != 'local': # leave it as None if Server uses local authentication
subscriberdomain = view['subscriber_domain']
# check for invalid email domains
subscriberemailerror = address_is_invalid(subscriberemail)
if subscriberemailerror:
errormessage = u'VizAlerts was unable to process this alert, because it was unable to send email to address {}: {}'.format(subscriberemail, subscriberemailerror)
logger.error(errormessage)
view_failure(view, errormessage)
continue
# check for unlicensed user
if view['subscriber_license'] == 'Unlicensed':
errormessage = u'VizAlerts was unable to process this alert: User {} is unlicensed.'.format(subscribersysname)
logger.error(errormessage)
view_failure(view, errormessage)
continue
# set our clientip properly if Server is validating it
if configs["trusted.useclientip"]:
clientip = configs["trusted.clientip"]
else:
clientip = None
# get the raw csv data from the view
try:
filepath = tabhttp.export_view(configs, view, tabhttp.Format.CSV, logger)
except Exception as e:
errormessage = u'Unable to export viewname {} as {}, error: {}'.format(viewname, tabhttp.Format.CSV, e)
logger.error(errormessage)
view_failure(view, u'VizAlerts was unable to export data for this view. Error message: {}'.format(errormessage))
continue
# We now have the CSV, so process it
try:
process_csv(filepath, view, sitename, viewname, subscriberemail, subscribersysname, subscriberdomain,
viewurlsuffix, timeout_s)
except Exception as e:
errormessage = u'Unable to process data from viewname {}, error:<br> {}'.format(viewname, e)
logger.error(errormessage)
view_failure(view, u'VizAlerts was unable to process this view due to the following error:<br>{}'.format(e))
continue
def validate_conf(configfile, logger):
"""Import config values and do some basic validations"""
try:
localconfigs = tabUtil.load_yaml_file(configfile)
except:
errormessage = u'An exception was raised loading the config file {}: {} Stacktrace: {}'.format(configfile, sys.exc_info(),
sys.exc_info()[2])
print errormessage
logger.error(errormessage)
sys.exit(1)
# test for missing config values
missingkeys = set(valid_conf_keys).difference(localconfigs.keys())
if len(missingkeys) != 0:
errormessage = u'Missing config values {}'.format(missingkeys)
print errormessage
logger.error(errormessage)
sys.exit(1)
# test specific conf values and prep if possible
for dir in [localconfigs["schedule.state.dir"], localconfigs["log.dir"], localconfigs["temp.dir"]]:
if not os.path.exists(os.path.dirname(dir)):
try:
os.makedirs(os.path.dirname(dir))
except OSError:
errormessage = u'Unable to create missing directory {}, error: {}'.format(os.path.dirname(dir),
OSError.message)
logger.error(errormessage)
quit_script(errormessage)
# test for password files and override with contents
localconfigs["smtp.password"] = get_password_from_file(localconfigs["smtp.password"])
localconfigs["db.pw"] = get_password_from_file(localconfigs["db.pw"])
# check for valid viz.png heigh/width settings
if not type(localconfigs["viz.png.width"]) is int or not type(localconfigs["viz.png.height"]) is int:
errormessage = u'viz.png height/width values are invalid {},{}'.format(localconfigs["viz.png.width"],
localconfigs["viz.png.height"])
print errormessage
logger.error(errormessage)
sys.exit(1)
# check for valid viz.data.timeout setting
for rule in localconfigs["viz.data.timeout"]:
if len(rule) > 3:
errormessage = u'viz.data.timeout values are invalid--only three entries per rule allowed'
print errormessage
logger.error(errormessage)
sys.exit(1)
# check for valid viz.data.timeout setting
for rule in localconfigs["viz.data.retrieval_tries"]:
if len(rule) > 3:
errormessage = u'viz.data.retrieval_tries values are invalid--only three entries per rule allowed'
print errormessage
logger.error(errormessage)
sys.exit(1)
# check for valid server.version setting
if not localconfigs["server.version"] in {8,9}:
errormessage = u'server.version value is invalid--only version 8 or version 9 allowed'
print errormessage
logger.error(errormessage)
sys.exit(1)
return localconfigs
def trusted_ticket_test():
"""Test ability to generate a trusted ticket from Tableau Server"""
# test for ability to generate a trusted ticket with the general username provided
if configs["trusted.useclientip"]:
clientip = configs["trusted.clientip"]
else:
clientip = None
logger.debug(u'testing trusted ticket: {}, {}, {}'.format(configs["server"], configs["server.user"], clientip))
sitename = '' # this is just a test, use the default site
test_ticket = None
try:
test_ticket = tabhttp.get_trusted_ticket(configs["server"], sitename, configs["server.user"], configs["server.ssl"], logger, configs["server.certcheck"], None, clientip)
logger.debug(u'Generated test trusted ticket. Value is: {}'.format(test_ticket))
except Exception as e:
errormessage = e.message
logger.error(errormessage)
quit_script(errormessage)
def get_views():
"""Get the set of Tableau Server views to check during this execution"""
try:
connstring = "dbname={} user={} host={} port={} password={}".format(configs["db.database"], configs["db.user"],
configs["db.host"], configs["db.port"],
configs["db.pw"])
conn = psycopg2.connect(connstring)
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute(configs["db.query"])
views = cur.fetchall()
logger.debug(u'PostgreSQL repository returned {} rows'.format(len(views)))
except psycopg2.Error as e:
errormessage = u'Failed to execute query against PostgreSQL repository: {}'.format(e)
logger.error(errormessage)
quit_script(errormessage)
except Exception as e:
errormessage = u'Unknown error obtaining views to process: {}'.format(e)
logger.error(errormessage)
quit_script(errormessage)
# retrieve schedule data from the last run and compare to current
statefile = configs["schedule.state.dir"] + SCHEDULE_STATE_FILENAME
# list of views to write to the state file again
persistviews = []
# final list of views to execute alerts for
execviews = []
try:
if not os.path.exists(statefile):
f = codecs.open(statefile, encoding='utf-8', mode='w+')
f.close()
except IOError as e:
errormessage = u'Invalid schedule state file: {}'.format(e.message)
logger.error(errormessage)
quit_script(errormessage)
try:
for line in fileinput.input([statefile]):
if not fileinput.isfirstline():
linedict = {}
linedict['site_name'] = line.split('\t')[0]
linedict['subscription_id'] = line.split('\t')[1]
linedict['view_id'] = line.split('\t')[2]
linedict['customized_view_id'] = line.split('\t')[3]
linedict['ran_last_at'] = line.split('\t')[4]
linedict['run_next_at'] = line.split('\t')[5]
linedict['schedule_id'] = line.split('\t')[6].rstrip() # remove trailing line break
for view in views:
# subscription_id is our unique identifier
if str(view['subscription_id']) == str(linedict['subscription_id']):
# preserve the last time the alert was scheduled to run
view['ran_last_at'] = str(linedict['ran_last_at'])
# if the run_next_at date is greater for this view since last we checked, mark it to run now
# the last condition ensures the alert doesn't run simply due to a schedule switch
# (note that CHANGING a schedule will still trigger the alert check...to be fixed later
if (
(datetime.datetime.strptime(str(view['run_next_at']), "%Y-%m-%d %H:%M:%S") \
!= datetime.datetime.strptime(str(linedict['run_next_at']), "%Y-%m-%d %H:%M:%S") \
and \
str(view["schedule_id"]) == str(linedict["schedule_id"]))
or
(view['is_test'] and \
datetime.datetime.strptime(str(view['run_next_at']), "%Y-%m-%d %H:%M:%S") \
!= datetime.datetime.strptime(str(linedict['ran_last_at']), "%Y-%m-%d %H:%M:%S")) # test alerts run immediately if never executed before
):
# For a test, run_next_at is anchored to the most recent comment, so use it as last run time
if view['is_test']:
view['ran_last_at'] = view['run_next_at']
else:
view['ran_last_at'] = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
seconds_since_last_run = \
abs((
datetime.datetime.strptime(str(linedict['ran_last_at']),
"%Y-%m-%d %H:%M:%S") -
datetime.datetime.utcnow()
).total_seconds())
# Set the timeout value in seconds to use for this view
timeout_s = view["timeout_s"]
for rule in configs["viz.data.timeout"]:
# REMOVE
logger.debug('Checking rule with from: {}, to: {}, timeout: {}'.format(rule[0], rule[1], rule[2]))
if rule[0] <= seconds_since_last_run <= rule[1]:
logger.debug('Rule applies!')
timeout_s = rule[2]
break
# Set the number of data retrieval attempts to use for this view
data_retrieval_tries = view["data_retrieval_tries"]
for rule in configs["viz.data.retrieval_tries"]:
if rule[0] <= seconds_since_last_run <= rule[1]:
data_retrieval_tries = rule[2]
# overwrite the placeholder values with our newly derived values
view['timeout_s'] = timeout_s
view['data_retrieval_tries'] = data_retrieval_tries
logger.debug(u'using timeout {}s, data retrieval tries {}, due to it being {} seconds since last'
' run.'.format(timeout_s, data_retrieval_tries, seconds_since_last_run))
execviews.append(view)
# add the view to the list to write back to our state file
persistviews.append(view)
# add NEW subscriptions that weren't in our state file
# this is ugly I, know...sorry. someday I'll be better at Python.
persist_sub_ids = []
for view in persistviews:
persist_sub_ids.append(view['subscription_id'])
for view in views:
if view['subscription_id'] not in persist_sub_ids:
persistviews.append(view)
# write the next run times to file
with codecs.open(statefile, encoding='utf-8', mode='w') as fw:
fw.write('{}\t{}\t{}\t{}\t{}\t{}\t{}\n'.format("site_name", "subscription_id", "view_id",
"customized_view_id", "ran_last_at", "run_next_at",
"schedule_id"))
for view in persistviews:
fw.write('{}\t{}\t{}\t{}\t{}\t{}\t{}\n'.format(view['site_name'], view["subscription_id"],
view["view_id"], view["customized_view_id"],
view["ran_last_at"], view["run_next_at"],
view["schedule_id"]))
except IOError as e:
errormessage = u'IOError accessing {} while getting views to process: {}'.format(e.filename, e.message)
logger.error(errormessage)
quit_script(errormessage)
except Exception as e:
errormessage = u'Error accessing {} while getting views to process: {}'.format(statefile, e)
logger.error(errormessage)
quit_script(errormessage)
return execviews
def process_csv(csvpath, view, sitename, viewname, subscriberemail, subscribersysname, subscriberdomain, viewurlsuffix, timeout_s):
"""For a CSV containing viz data, process it as a simple or advanced alert"""
try:
logger.debug(u'Opening file {} for reading'.format(csvpath))
f = open(csvpath, 'rU')
csvreader = UnicodeDictReader(f)
except Exception as e:
logger.error(u'Error accessing {} while getting processing view {}: {}'.format(csvpath, viewurlsuffix, e))
raise e
# get the data into a list of dictionaries
data = []
rowcount = 0
logger.debug(u'Iterating through rows')
for row in csvreader:
if rowcount > configs["viz.data.maxrows"]:
errormessage = u'Maximum rows of {} exceeded.'.format(configs["viz.data.maxrows"],
viewurlsuffix)
logger.error(errormessage)
raise UserWarning(errormessage)
data.append(row)
rowcount = rowcount + 1
logger.debug(u'Rowcount at: {}'.format(rowcount))
logger.debug('Done loading data')
# bail if no data to process
if rowcount == 0:
logger.info(u'0 rows found; no actions being taken')
return
# detect if this is a simple or advanced alert
if u' Email Action *' in csvreader.fieldnames:
logger.debug('Advanced alert detected')
simplealert = False
else:
logger.debug('Simple alert detected')
simplealert = True
vizurl = get_view_url(view)
# construct the body footer text for later use
bodyfooter = get_footer(subscriberemail, subscribersysname, subscriberdomain, vizurl, viewname, simplealert, configs["server.version"])
# set our clientip properly if Server is validating it
if configs["trusted.useclientip"]:
clientip = configs["trusted.clientip"]
else:
clientip = None
# process the simple alert scenario
if simplealert:
try:
logger.debug(u'Processing as a simple alert')
# export the viz to a PNG file
imagepath = tabhttp.export_view(configs, view, tabhttp.Format.PNG, logger)
# attachments are stored lists of dicts to handle Advanced Alerts
inlineattachments = [{'imagepath' : imagepath}]
appendattachments = [{'imagepath' : csvpath}]
# embed the viz image
# inlineattachments = [csvpath, imagepath]
logger.info(u'Sending simple alert email to user {}'.format(subscriberemail))
body = u'<a href="{}"><img src="cid:{}"></a>'.format(vizurl, basename(imagepath)) +\
bodyfooter.format(subscriberemail, vizurl, viewname)
subject = unicode(u'Alert triggered for {}'.format(viewname))
send_email(configs["smtp.address.from"], subscriberemail, subject, body,
None, None, inlineattachments, appendattachments)
return
except Exception as e:
errormessage = u'Alert was triggered, but encountered a failure rendering data/image:<br> {}'.format(e.message)
logger.error(errormessage)
raise UserWarning(errormessage)
else:
# this is an advanced alert, so we need to process all the fields appropriately
logger.debug(u'Processing as an advanced alert')
# ensure the subscriber is the owner of the viz -- if not, disregard it entirely
if view['subscriber_sysname'] != view['owner_sysname']:
logger.info(u'Ignoring advanced alert subscription_id {} for non-owner {}'.format(
view['subscription_id'], view['subscriber_sysname']))
return
# test for valid fields
if u' Email Action *' in csvreader.fieldnames:
missingfields = set(required_email_fields).difference(csvreader.fieldnames)
if len(missingfields) != 0:
errormessage = u'Missing email fields {}'.format(list(missingfields))
logger.error(errormessage)
raise UserWarning(errormessage)
# booleans determining whether optional fields are present
has_consolidate_email = False
has_email_from = False
has_email_cc = False
has_email_bcc = False
has_email_header = False
has_email_footer = False
has_email_attachment = False
# used for forcing a sort order in consolidated emails since the
# trigger view csv gets re-sorted by the download process
has_email_sort_order = False
# create variables for optional email fields
email_from = None
email_cc = None
email_bcc = None
email_header = None
email_footer = None
# assign variable for any viz image generated
imagepath = u''
if u' Email Consolidate ~' in csvreader.fieldnames:
has_consolidate_email = True
if u' Email From ~' in csvreader.fieldnames:
has_email_from = True
if u' Email CC ~' in csvreader.fieldnames:
has_email_cc = True
if u' Email BCC ~' in csvreader.fieldnames:
has_email_bcc = True
if u' Email Header ~' in csvreader.fieldnames:
has_email_header = True
if u' Email Footer ~' in csvreader.fieldnames:
has_email_footer = True
if u' Email Attachment ~' in csvreader.fieldnames:
has_email_attachment = True
if u' Email Sort Order ~' in csvreader.fieldnames:
has_email_sort_order = True
logger.debug(u'Validating email addresses')
# validate all From and Recipient addresses
addresserrors = validate_addresses(data, has_email_from, has_email_cc, has_email_bcc)
if addresserrors:
errormessage = u'Invalid email addresses found, details to be emailed.'
logger.error(errormessage)
# Need to send a custom email for this error
addresslist = u'<table border=1><tr><b><td>Row</td><td width="75">Field</td><td>Value</td><td>Error</td></b></tr>'
for adderror in addresserrors:
addresslist = addresslist + u'<tr><td width="75">{}</td><td width="75">{}</td><td>{}</td><td>{}</td></tr>'.format(adderror['Row'],
adderror['Field'],
adderror['Value'],
adderror['Error'],)
addresslist = addresslist + u'</table>'
appendattachments = [{'imagepath' : csvpath}]
view_failure(view, u'Errors found in recipients:<br><br>{}'.format(addresslist) + \
u'<br><br>See row numbers in attached CSV file.' ,
appendattachments)
return
# eliminate duplicate rows and ensure proper sorting
data = get_unique_vizdata(data, has_consolidate_email, has_email_from, has_email_cc, has_email_bcc, has_email_header, has_email_footer, has_email_attachment, has_email_sort_order)
rowcount_unique = len(data)
# could be multiple viz's (including PDF, CSV, TWB) for a single row in the CSV
# return a list of all found content reference VIZ_*() strings
# VIZ_*([optional custom view w/optional custom URL parameters]|[optional VizAlerts parameters])
# stored as a dict of dicts, the key is the content reference
vizcompleterefs = dict()
try:
vizcompleterefs = find_viz_refs(view, data, viewurlsuffix, has_email_header, has_email_footer, has_email_attachment)
except Exception as e:
errormessage = u'Alert was triggered, but encountered a failure getting data/image references:<br> {}'.format(e.message)
logger.error(errormessage)
raise UserWarning(errormessage)
# iterate through the rows and send emails accordingly
consolidate_email_ctr = 0
body = []
inlineattachments = []
appendattachments =[]
# Process each row of data
for i, row in enumerate(data):
logger.debug(u'Starting iteration {}, consolidate_email_ctr is {}'.format(i, consolidate_email_ctr))
for line in body:
logger.debug(u'Body row: {}'.format(line))
# make sure we set the "from" address if the viz did not provide it
if has_email_from:
email_from = row[' Email From ~']
else:
email_from = configs["smtp.address.from"] # use default from config file
# get the other recipient addresses
if has_email_cc:
email_cc = row[' Email CC ~']
else:
email_cc = None
if has_email_bcc:
email_bcc = row[' Email BCC ~']
else:
email_bcc = None
if row[' Email Action *'] == '1':
logger.debug(u'Starting email action')
# Append header row, if provided
if has_email_header and consolidate_email_ctr == 0:
logger.debug(u'has_email_header is {} and consolidate_email_ctr is '
u'{}, so appending body header'.format(has_email_header, consolidate_email_ctr))
body.append(row[' Email Header ~'])
# If rows are being consolidated, consolidate all with same recipients & subject
if has_consolidate_email:
# could put a test in here for mixing consolidated and non-consolidated emails in
# the same trigger view, would also need to check the sort in get_unique_vizdata
logger.debug(u'Consolidate value is true, row index is {}, rowcount is {}'.format(i, rowcount_unique))
# test for end of iteration--if done, take what we have so far and send it
if i + 1 == rowcount_unique:
logger.debug(u'Last email in set reached, sending consolidated email')
logger.info(u'Sending email to {}, CC {}, BCC {}, subject {}'.format(row[' Email To *'],
email_cc, email_bcc ,
row[' Email Subject *']))
try: # remove this later??
body, inlineattachments = append_body_and_inlineattachments(body, inlineattachments, row, vizcompleterefs, subscriberemail, vizurl, viewname, view, has_email_footer)
appendattachments = append_attachments(appendattachments, row, vizcompleterefs, has_email_attachment)
# send the email
send_email(email_from, row[' Email To *'], row[' Email Subject *'],
u''.join(body), email_cc, email_bcc, inlineattachments, appendattachments)
except Exception as e:
errormessage = u'Failed to send the email. Exception:<br> {}'.format(e)
logger.error(errormessage)
raise UserWarning(errormessage)
# reset variables for next email
body = []
inlineattachments = []
consolidate_email_ctr = 0
appendattachments = []
else:
# This isn't the end, and we're consolidating rows, so test to see if the next row needs
# to be a new email
this_row_recipients = []
next_row_recipients = []
this_row_recipients.append(row[' Email Subject *'])
this_row_recipients.append(row[' Email To *'])
this_row_recipients.append(email_from)
next_row_recipients.append(data[i + 1][' Email Subject *'])
next_row_recipients.append(data[i + 1][' Email To *'])
if has_email_from:
next_row_recipients.append(data[i + 1][' Email From ~'])
else:
next_row_recipients.append(email_from)
if has_email_cc:
this_row_recipients.append(email_cc)
next_row_recipients.append(data[i + 1][' Email CC ~'])
if has_email_bcc:
this_row_recipients.append(email_bcc)
next_row_recipients.append(data[i + 1][' Email BCC ~'])
# Now compare the data from the rows
if this_row_recipients == next_row_recipients:
logger.debug(u'Next row matches recips and subject, appending body & attachments')
body.append(row[' Email Body *'])
if has_email_attachment and len(row[' Email Attachment ~']) > 0:
appendattachments = append_attachments(appendattachments, row, vizcompleterefs, has_email_attachment)
consolidate_email_ctr += 1
else:
logger.debug(u'Next row does not match recips and subject, sending consolidated email')
logger.info(u'Sending email to {}, CC {}, BCC {}, Subject {}'.format(row[' Email To *'],
email_cc , email_bcc,
row[' Email Subject *']))
body, inlineattachments = append_body_and_inlineattachments(body, inlineattachments, row, vizcompleterefs, subscriberemail, vizurl, viewname, view, has_email_footer)
appendattachments = append_attachments(appendattachments, row, vizcompleterefs, has_email_attachment)
# send the email
try:
send_email(email_from, row[' Email To *'], row[' Email Subject *'],
u''.join(body), email_cc, email_bcc, inlineattachments, appendattachments)
except Exception as e:
errormessage = u'Failed to send the email. Exception:<br> {}'.format(e)
logger.error(errormessage)
raise UserWarning(errormessage)
body = []
consolidate_email_ctr = 0
inlineattachments = []
appendattachments = []
else:
# emails are not being consolidated, so send the email
logger.info(u'Sending email to {}, CC {}, BCC {}, Subject {}'.format(row[' Email To *'],
email_cc , email_bcc,
row[' Email Subject *']))
consolidate_email_ctr = 0 # I think this is redundant now...
body = []
# add the header if needed
if has_email_header:
body.append(row[' Email Header ~'])
body, inlineattachments = append_body_and_inlineattachments(body, inlineattachments, row, vizcompleterefs, subscriberemail, vizurl, viewname, view, has_email_footer)
appendattachments = append_attachments(appendattachments, row, vizcompleterefs, has_email_attachment)
try:
send_email(email_from, row[' Email To *'], row[' Email Subject *'], u''.join(body), email_cc,
email_bcc, inlineattachments, appendattachments)
except Exception as e:
errormessage = u'Failed to send the email. Exception:<br> {}'.format(e)
logger.error(errormessage)
raise UserWarning(errormessage)
inlineattachments = []
body = []
appendattachments=[]
else:
# missing any valid action
logger.info(u'No valid actions specified in view data for {}, skipping'.format(viewurlsuffix))
return
def get_mimetype(filename):
"""Returns the MIME type of the given file.
:param filename: A valid path to a file
:type filename: str
:returns: The file's MIME type
:rtype: tuple
"""
content_type, encoding = guess_type(filename)
if content_type is None or encoding is not None:
content_type = "application/octet-stream"
return content_type.split("/", 1)
def mimify_file(filename, inline = True, overridename = None):
"""Returns an appropriate MIME object for the given file.
:param filename: A valid path to a file
:type filename: str
:returns: A MIME object for the given file
:rtype: instance of MIMEBase
"""
filename = abspath(expanduser(filename))
if overridename:
basefilename = overridename
else:
basefilename = basename(filename)
if inline:
msg = MIMEBase(*get_mimetype(filename))
msg.set_payload(open(filename, "rb").read())
msg.add_header('Content-ID', '<{}>'.format(basefilename))
msg.add_header('Content-Disposition', 'inline; filename="%s"' % basefilename)
else:
msg = MIMEBase(*get_mimetype(filename))
msg.set_payload( open(filename,"rb").read() )
if overridename:
basefilename = overridename
msg.add_header('Content-Disposition', 'attachment; filename="%s"' % basefilename)
encode_base64(msg)
return msg
def quit_script(message):
""""Called when a fatal error is encountered in the script"""
try:
send_email(configs["smtp.address.from"], configs["smtp.address.to"], configs["smtp.subject"], message)
except Exception as e:
logger.error(u'Unknown error-sending exception alert email: {}'.format(e.message))
sys.exit(1)
def view_failure(view, message, attachments=None):
"""Alert the Admin, and optionally the Subscriber, to a failure to process their alert"""
subject = u'VizAlerts was unable to process view {}'.format(view["view_name"])
body = message + u'<br><br>' + \
u'<b>Details:</b><br><br>' + \
u'<b>View URL:</b> <a href="{}">{}<a>'.format(get_view_url(view), get_view_url(view)) + u'<br>' \
u'<b>Subscriber:</b> <a href="mailto:{}">{}</a>'.format(view['subscriber_email'], view['subscriber_sysname']) + u'<br>' \
u'<b>View Owner:</b> <a href="mailto:{}">{}</a>'.format(view['owner_email'], view['owner_sysname']) + u'<br>' \
u'<b>Site Id:</b> {}'.format(view['site_name']) + u'<br>' \
u'<b>Project:</b> {}'.format(view['project_name'])
if configs['smtp.notify_subscriber_on_failure'] == True:
toaddrs = view['subscriber_email'] # email the Subscriber, cc the Admin
ccaddrs = configs['smtp.address.to']
else:
toaddrs = configs['smtp.address.to'] # just email the Admin
ccaddrs = None
if attachments:
logger.debug('Failure email should include attachment: {}'.format(attachments))
try:
send_email(configs['smtp.address.from'], toaddrs, subject,
body, ccaddrs, None, None, attachments)
except Exception as e:
logger.error(u'Unknown error sending exception alert email: {}'.format(e.message))
def validate_addresses(vizdata, has_email_from, has_email_cc, has_email_bcc):
"""Loops through the viz data for an Advanced Alert and returns a list of dicts
containing any errors found in recipients"""
errorlist = []
rownum = 2 # account for field header in CSV
for row in vizdata:
result = addresses_are_invalid(row[' Email To *'], False) # empty string not acceptable as a To address
if result:
errorlist.append({'Row': rownum, 'Field': ' Email To *', 'Value': result['address'], 'Error': result['errormessage']})
if has_email_from:
result = addresses_are_invalid(row[' Email From ~'], False) # empty string not acceptable as a From address
if result:
errorlist.append({'Row': rownum, 'Field': ' Email From ~', 'Value': result['address'], 'Error': result['errormessage']})
if has_email_cc:
result = addresses_are_invalid(row[' Email CC ~'], True)
if result:
errorlist.append({'Row': rownum, 'Field': ' Email CC ~', 'Value': result['address'], 'Error': result['errormessage']})
if has_email_bcc:
result = addresses_are_invalid(row[' Email BCC ~'], True)
if result:
errorlist.append({'Row': rownum, 'Field': ' Email BCC ~', 'Value': result['address'], 'Error': result['errormessage']})
rownum = rownum + 1
return errorlist
def addresses_are_invalid(emailaddresses, emptystringok):
"""Validates all email addresses found in a given string"""
logger.debug(u'Validating email field value: {}'.format(emailaddresses))
address_list = re.split(EMAIL_RECIP_SPLIT_REGEX, emailaddresses.strip())
for address in address_list:
logger.debug(u'Validating presumed email address: {}'.format(address))
if emptystringok and (address == '' or address is None):
return None
else:
errormessage = address_is_invalid(address)
if errormessage:
logger.debug(u'Address is invalid: {}, Error: {}'.format(address, errormessage))
if len(address) > 64:
address = address[:64] + '...' # truncate a too-long address for error formattting purposes
return {'address':address, 'errormessage':errormessage}
return None
def address_is_invalid(address):
"""Checks for a syntactically invalid email address."""
# (most code derived from from http://zeth.net/archive/2008/05/03/email-syntax-check)
# Email address must not be empty
if address is None or len(address) == 0 or address == '':
errormessage = u'Address is empty'
logger.error(errormessage )
return errormessage
# Email address must be 6 characters in total.
# This is not an RFC defined rule but is easy
if len(address) < 6:
errormessage = u'Address is too short: {}'.format(address)
logger.error(errormessage)
return errormessage
# Unicode in addresses not yet supported
try:
address.decode('ascii')
except Exception as e:
errormessage = u'Address must contain only ASCII characers: {}'.format(address)
logger.error(errormessage)
return errormessage
# Split up email address into parts.
try:
localpart, domainname = address.rsplit('@', 1)