This repository has been archived by the owner on Apr 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
notification.py
139 lines (129 loc) · 5.59 KB
/
notification.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
from boto import ses
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from ghost_log import log
from ghost_tools import GHOST_JOB_STATUSES_COLORS
import requests
import json
import os
from gzip import GzipFile
import shutil
import StringIO
MAIL_LOG_FROM_DEFAULT = 'no-reply@cloud-deploy.io'
TEMPLATES_DIR = 'email-templates'
class Notification():
_aws_access_key = None
_aws_secret_key = None
_region = None
def __init__(self, aws_access_key=None, aws_secret_key=None, region=None):
self._aws_access_key = aws_access_key
self._aws_secret_key = aws_secret_key
self._region = region
def send_mail(self, From="", To="", subject="", body_text="", body_html="", attachments=None, sender_name=''):
attachments = attachments or []
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = From if sender_name == '' else '{sender} <{email_addr}>'.format(sender=sender_name, email_addr=From)
msg['To'] = To
msg.preamble = 'Multipart message.\n'
# the message body
# part1 = MIMEText(body_text, 'plain')
part2 = MIMEText(body_html, 'html')
msg.attach(part2)
# msg.attach(part1)
# the attachment
for attachment in attachments:
log_path = attachment['original_log_path']
with open(log_path, 'rb') as f_in:
log_stat = os.stat(log_path)
if log_stat.st_size > 512000:
gz_data = StringIO.StringIO()
with GzipFile(fileobj=gz_data, mode='wb', compresslevel=9, filename=attachment['filename']) as gz_out:
shutil.copyfileobj(f_in, gz_out)
part = MIMEApplication(gz_data.getvalue())
part.add_header('Content-Disposition', 'attachment', filename=attachment['filename']+'.gz')
gz_data.close()
else:
part = MIMEApplication(f_in.read())
part.add_header('Content-Disposition', 'attachment', filename=attachment['filename'])
msg.attach(part)
# connect to SES
connection = ses.connect_to_region(self._region, aws_access_key_id=self._aws_access_key, aws_secret_access_key=self._aws_secret_key)
# and send the message
result = connection.send_raw_email(msg.as_string(), source=msg['From'], destinations=[msg['To']])
return(result)
def send_slack_notification(self, config, msg, app, job, job_log, log_file=None):
try:
slack_url = config.get('webhooks_endpoint')
if config.get('ghost_base_url'):
notif = "[<{ghost_url}|{prefix}>]{msg} <{ghost_url}/web/jobs/{jobId}|{jobId}>".format(
ghost_url=config['ghost_base_url'],
prefix=config.get('message_prefix', 'Ghost'),
msg=msg,
jobId=str(job['_id']))
else:
notif = "[{prefix}]{msg}".format(prefix=config.get('message_prefix', 'Ghost'), msg=msg)
fields = [
{
"title": "Application",
"value": app['name'],
"short": True
},
{
"title": "Environnement",
"value": app['env'],
"short": True
},
{
"title": "Role",
"value": app['role'],
"short": True
},
{
"title": "Command",
"value": job['command'],
"short": True
},
{
"title": "User",
"value": job['user'],
"short": True
},
{
"title": "Status",
"value": job['status'],
"short": True
},
{
"title": "Message",
"value": job['message'],
"short": False
},
{
"title": "Log extract",
"value": job_log,
"short": False
}
]
payload = {
"channel": config.get('channel', '#ghost-deployments'),
"username": config.get('bot_name', 'Claranet Cloud Deploy'),
"icon_url": config.get('bot_icon', 'https://www.cloudeploy.io/ghost/cloud_deploy_logo_128.png'),
"attachments": [
{
"fallback": notif,
"pretext": config.get('message_prefix', 'Ghost job triggered'),
"color": GHOST_JOB_STATUSES_COLORS[job['status']],
"fields": fields,
"title": "Job #{jobId} triggered by {user}".format(jobId=str(job['_id']), user=job['user']),
"title_link": "{ghost_url}/web/jobs/{jobId}".format(ghost_url=config['ghost_base_url'], jobId=str(job['_id'])),
"footer": "Created at {created}".format(created=job['_created']),
}]
}
r = requests.post(slack_url, json.dumps(payload), headers={'content-type': 'application/json'})
if log_file:
log("Slack post status : {0} - {1}".format(r.status_code, r.text), log_file)
except Exception as e:
if log_file:
log("Error sending notification to Slack (%s)" % str(e), log_file)