-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathk8s_emailer.py
More file actions
284 lines (237 loc) · 8.13 KB
/
k8s_emailer.py
File metadata and controls
284 lines (237 loc) · 8.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import argparse
from email.message import EmailMessage
import json
import kubernetes.client as k8s_client
import kubernetes.config as k8s_config
import logging
import os
import prometheus_client
import smtplib
import time
__version__ = '0.2.1'
METADATA_PREFIX = 'k8s-emailer.hpc.nyu.edu/'
LABEL_MODE = METADATA_PREFIX + 'mode'
ANNOTATION_EMAIL = METADATA_PREFIX + 'addresses'
ANNOTATION_LAST_NOTIFIED = METADATA_PREFIX + 'last-notified'
logger = logging.getLogger('k8s_emailer')
PROM_BAD_ANNOTATIONS = prometheus_client.Gauge(
'bad_annotations',
"Number of jobs with incorrect annotations/labels",
['namespace'],
)
PROM_ANNOTATED = prometheus_client.Gauge(
'annotated',
"Number of jobs found with email annotations",
['namespace'],
)
PROM_EMAILS = prometheus_client.Counter(
'emails',
"Number of emails sent",
['namespace'],
)
PROM_SEND_ERRORS = prometheus_client.Counter(
'email_errors',
"Number of errors sending emails",
)
if 'FULL_SYNC_INTERVAL' in os.environ:
FULL_SYNC_INTERVAL = int(os.environ['FULL_SYNC_INTERVAL'], 10)
else:
FULL_SYNC_INTERVAL = 120
class Emailer(object):
def __init__(self):
self.subject_template = os.environ.get(
'EMAIL_SUBJECT_TEMPLATE',
"[{tag}] {status}: {name}",
)
self.tag = os.environ.get('EMAIL_TAG', 'Kubernetes')
if os.environ.get('EMAIL_SSL', '0') not in ('0', 'no', 'false', 'off'):
self.cls = smtplib.SMTP_SSL
default_port = 465
else:
self.cls = smtplib.SMTP
default_port = 587
self.host = os.environ.get('EMAIL_HOST')
assert self.host, "EMAIL_HOST is not set"
if 'EMAIL_PORT' in os.environ:
self.port = int(os.environ['EMAIL_PORT'], 10)
else:
self.port = default_port
self.from_address = os.environ.get('EMAIL_FROM')
assert self.from_address, "EMAIL_FROM is not set"
if 'EMAIL_USERNAME' in os.environ or 'EMAIL_PASSWORD' in os.environ:
self.credentials = (
os.environ['EMAIL_USERNAME'],
os.environ['EMAIL_PASSWORD'],
)
else:
self.credentials = None
def send(self, addresses, message, ns, name):
fullname = ns + '/' + name
subject = (
self.subject_template
.replace('{tag}', self.tag)
.replace('{status}', message)
.replace('{name}', fullname)
)
body = f"{message}: {fullname}"
with self.cls(self.host, self.port) as smtp:
if self.credentials is not None:
smtp.login(*self.credentials)
for address in addresses:
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = self.from_address
msg['To'] = address
msg.set_content(body)
smtp.send_message(msg)
PROM_EMAILS.labels(ns).inc(len(addresses))
def main():
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
parser = argparse.ArgumentParser(
'ceph-backup',
description="Backup up Ceph volumes on a Kubernetes cluster",
)
parser.add_argument('--kubeconfig', nargs=1)
parser.add_argument('--cleanup-only', action='store_true', default=False)
args = parser.parse_args()
prometheus_client.start_http_server(8080)
if args.kubeconfig:
logger.info("Using specified config file")
k8s_config.load_kube_config(args.kubeconfig[0])
else:
logger.info("Using in-cluster config")
k8s_config.load_incluster_config()
api = k8s_client.ApiClient()
emailer = Emailer()
# TODO: Use the watch API
while True:
do_sync(api, emailer)
time.sleep(FULL_SYNC_INTERVAL)
def do_sync(api, emailer):
bad_annotations = {}
annotations = {}
batchv1 = k8s_client.BatchV1Api(api)
# Find jobs with the label
jobs = batchv1.list_job_for_all_namespaces(label_selector=LABEL_MODE).items
for job in jobs:
# Read metadata
meta = job.metadata
ns = meta.namespace
mode = meta.labels[LABEL_MODE]
addresses_annotation = meta.annotations.get(ANNOTATION_EMAIL, '')
addresses = set()
for address in addresses_annotation.split(','):
address = address.strip()
if address:
addresses.add(address)
addresses = sorted(addresses)
annotations[ns] = annotations.get(ns, 0) + 1
# Select what to notify based on mode
if mode == 'failure':
send_on_failure = True
send_on_success = False
send_on_retry = False
elif mode == 'complete':
send_on_failure = True
send_on_success = True
send_on_retry = False
else:
# mode=all is also the default
if mode != 'all':
bad_annotations[ns] = bad_annotations.get(ns, 0) + 1
send_on_failure = True
send_on_success = True
send_on_retry = True
# Determine job status
is_success = is_failure = False
if any(
condition.type.lower() == 'failed'
and condition.status.lower() == 'true'
for condition in job.status.conditions or ()
):
is_failure = True
elif job.status.completion_time:
is_success = True
retries = job.status.failed or 0
# Read last notified state
last_annotation = {}
if ANNOTATION_LAST_NOTIFIED in meta.annotations:
last_annotation = meta.annotations[ANNOTATION_LAST_NOTIFIED]
try:
last_annotation = json.loads(last_annotation)
except json.JSONDecodeError:
pass
# Build email
message = None
if (
is_failure
and not last_annotation.get('is_failure', False)
and send_on_failure
):
message = "Job failed"
elif (
is_success
and not last_annotation.get('is_success', False)
and send_on_success
):
message = "Job succeeded"
elif (
retries != 0
and retries != last_annotation.get('retries', 0)
and send_on_retry
):
message = "Job was retried"
if message:
logger.info(
"Sending email to %d addresses: %s %s/%s",
len(addresses),
message,
ns,
meta.name,
)
try:
emailer.send(
addresses,
message,
ns,
meta.name,
)
except Exception:
logger.exception(
"Error sending emails for %s/%s",
ns,
meta.name,
)
PROM_SEND_ERRORS.inc()
else:
# Update last notification annotation
last_annotation = {
'is_failure': is_failure,
'is_success': is_success,
'retries': retries,
}
batchv1.patch_namespaced_job(
meta.name,
ns,
{
'metadata': {
'annotations': {
ANNOTATION_LAST_NOTIFIED: json.dumps(
last_annotation,
separators=(',', ':'),
),
},
},
},
)
PROM_ANNOTATED.clear()
for count_ns, count in annotations.items():
PROM_ANNOTATED.labels(count_ns).set(count)
# This makes sure the time series exist, enabling rate() to work
PROM_EMAILS.labels(count_ns).inc(0)
PROM_BAD_ANNOTATIONS.clear()
for count_ns, count in bad_annotations.items():
PROM_BAD_ANNOTATIONS.labels(count_ns).set(count)