-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJobSuccessReport.py
327 lines (287 loc) · 15.4 KB
/
JobSuccessReport.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
import sys
import os
import re
from datetime import datetime
import logging
from time import sleep
import traceback
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search, Q
import TextUtils
import Configuration
from Reporter import Reporter
from indexpattern import indexpattern_generate
class Jobs:
def __init__(self):
self.jobs = {}
def add_job(self, site, job):
if site not in self.jobs:
self.jobs[site] = []
self.jobs[job.site].append(job)
class Job:
def __init__(self, end_time, start_time, jobid, site, host, exit__code):
self.end_time = end_time
self.start_time = start_time
self.jobid = jobid
self.site = site
self.host = host
self.exit_code = exit__code
class JobSuccessRateReporter(Reporter):
def __init__(self, configuration, start, end, vo, template, is_test, verbose, no_email):
Reporter.__init__(self, configuration, start, end, verbose)
self.no_email = no_email
self.is_test = is_test
self.vo = vo
self.template = template
self.title = "Production Jobs Success Rate {0} - {1}".format(self.start_time, self.end_time)
self.run = Jobs()
self.clusters = {}
self.connectStr = None
self.datesplit_pattern = re.compile('[-/ :]')
self.usermatch_CILogon = re.compile('.+CN=UID:(\w+)')
self.usermatch_FNAL = re.compile('.+/(\w+\.fnal\.gov)')
self.jobparts = re.compile('\w+\.(\w+\.\w+\.\w+)#(\w+\.\w+)#.+')
self.realhost_pattern = re.compile('\s\(primary\)')
def query(self, client):
"""Method that actually queries elasticsearch"""
# Set up our search parameters
voq = self.config.get("query", "{}_voname".format(self.vo.lower()))
productioncheck = '*Role=Production*'
start_date = self.datesplit_pattern.split(self.start_time)
starttimeq = datetime(*[int(elt) for elt in start_date]).isoformat()
end_date = self.datesplit_pattern.split(self.end_time)
endtimeq = datetime(*[int(elt) for elt in end_date]).isoformat()
# Generate the index pattern based on the start and end dates
indexpattern = indexpattern_generate(start_date, end_date)
if self.verbose:
print >> sys.stdout, indexpattern
sleep(3)
# Elasticsearch query
resultset = Search(using=client, index=indexpattern) \
.query("wildcard", VOName=productioncheck) \
.filter(Q({"term": {"VOName": voq}})) \
.filter("range", EndTime={"gte": starttimeq, "lt": endtimeq}) \
.filter(Q({"term": {"ResourceType": "Payload"}}))
if self.verbose:
print resultset.to_dict()
return resultset
def generate_result_array(self, resultset):
# Compile results into array
results = []
for hit in resultset.scan():
try:
# Parse userid
try:
# Grabs the first parenthesized subgroup in the hit['CommonName'] string, where that subgroup comes
# after "CN=UID:"
userid = self.usermatch_CILogon.match(hit['CommonName']).\
group(1)
except AttributeError:
try:
userid = self.usermatch_FNAL.match(hit['CommonName']).\
group(1) # If this doesn't match CILogon standard, just grab the *.fnal.gov string at the end
except AttributeError:
userid = hit['CommonName'] # Just print the CN string, move on
# Parse jobid
try:
# Parse the GlobalJobId string to grab the cluster number and schedd
jobparts = self.jobparts.match(hit['GlobalJobId']).group(2
,1)
# Put these together to create the jobid (e.g. [email protected])
jobid = '{}@{}'.format(*jobparts)
except AttributeError:
jobid = hit[
'GlobalJobId'] # If for some reason a probe gives us a bad jobid string, just keep going
realhost = self.realhost_pattern.sub('', hit['Host']) # Parse to get the real hostname
outstr = '{starttime}\t{endtime}\t{CN}\t{JobID}\t{hostdescription}\t{host}\t{exitcode}'.format(
starttime=hit['StartTime'],
endtime=hit['EndTime'],
CN=userid,
JobID=jobid,
hostdescription=hit['Host_description'],
host=realhost,
exitcode=hit['Resource_ExitCode']
)
results.append(outstr)
if self.verbose:
print >> sys.stdout, outstr
except KeyError:
# We want to ignore records where one of the above keys isn't listed in the ES document.
# This is consistent with how the old MySQL report behaved.
pass
return results
def add_to_clusters(self, results):
# Grab each line in results, instantiate Job class for each one, and add to clusters
for line in results:
tmp = line.split('\t')
start_time = tmp[0].strip().replace('T', ' ').replace('Z', '')
end_time = tmp[1].strip().replace('T', ' ').replace('Z', '')
userid = tmp[2].strip()
jobid = tmp[3].strip()
site = tmp[4].strip()
if site == "NULL":
continue
host = tmp[5].strip()
status = int(tmp[6].strip())
job = Job(end_time, start_time, jobid, site, host, status)
self.run.add_job(site, job)
clusterid = jobid.split(".")[0]
if clusterid not in self.clusters:
self.clusters[clusterid] = {'userid': userid, 'jobs': []}
self.clusters[clusterid]['jobs'].append(job)
return
def generate(self):
# Set up elasticsearch client
client = Elasticsearch(['https://fifemon-es.fnal.gov'],
use_ssl=True,
verify_certs=True,
ca_certs='/etc/grid-security/certificates/cilogon-osg.pem',
client_cert='gracc_cert/gracc-reports-dev.crt',
client_key='gracc_cert/gracc-reports-dev.key',
timeout=60)
resultset = self.query(client) # Generate Search object for ES
response = resultset.execute() # Execute that Search
return_code_success = response.success() # True if the elasticsearch query completed without errors
results = self.generate_result_array(resultset) # Format our resultset into an array we use later
if not return_code_success:
raise Exception('Error accessing ElasticSearch')
if len(results) == 1 and len(results[0].strip()) == 0:
print >> sys.stdout, "Nothing to report"
return
self.add_to_clusters(results) # Parse our results and create clusters objects for each
return
def send_report(self):
table = ""
total_failed = 0
if len(self.run.jobs) == 0:
return
table_summary = ""
job_table = ""
job_table_cl_count = 0
# Look in clusters, figure out whether job failed or succeded, categorize appropriately,
# and generate HTML line for total jobs failed by cluster
for cid, cdict in self.clusters.iteritems():
total_jobs = len(cdict['jobs'])
failures = []
total_jobs_failed = 0
for job in cdict['jobs']:
if job.exit_code == 0:
continue
total_jobs_failed += 1
failures.append(job)
if total_jobs_failed == 0:
continue
if job_table_cl_count < 100: # Limit number of clusters shown in report to 100.
job_table += '\n<tr><td align = "left">{}</td><td align = "right">{}</td><td align = "right">{}'\
'</td><td align = "right">{}</td><td></td><td></td><td></td><td></td><td></td>'\
'<td></td></tr>'.format(
cid,
cdict['userid'],
total_jobs,
total_jobs_failed)
# Generate HTML line for each failed job
for job in failures:
job_table += '\n<tr><td></td><td></td><td></td><td></td><td align = "left">{}</td>'\
'<td align = "left">{}</td><td align = "left">{}</td><td align = "right">{}</td>'\
'<td align = "right">{}</td><td align = "right">{}</td></tr>'.format(
job.jobid,
job.start_time,
job.end_time,
job.site,
job.host,
job.exit_code)
job_table_cl_count += 1
total_jobs = 0
# Compile count of failed jobs, calculate job success rate
for key, jobs in self.run.jobs.items():
failed = 0
total = len(jobs)
failures = {}
for job in jobs:
if job.exit_code != 0:
failed += 1
if job.host not in failures:
failures[job.host] = {}
if job.exit_code not in failures[job.host]:
failures[job.host][job.exit_code] = 0
failures[job.host][job.exit_code] += 1
total_jobs += total
total_failed += failed
table_summary += '\n<tr><td align = "left">{}</td><td align = "right">{}</td><td align = "right">{}</td>'\
'<td align = "right">{}</td></tr>'.format(
key,
total,
failed,
round((total - failed) * 100. / total, 1))
table += '\n<tr><td align = "left">{}</td><td align = "right">{}</td><td align = "right">{}</td>'\
'<td align = "right">{}</td><td></td><td></td><td></td></tr>'.format(
key,
total,
failed,
round((total - failed) * 100. / total, 1))
for host, errors in failures.items():
for code, count in errors.items():
table += '\n<tr><td></td><td></td><td></td><td></td><td align = "left">{}</td>'\
'<td align = "right">{}</td><td align = "right">{}</td></tr>'.format(
host,
code,
count)
table += '\n<tr><td align = "left">Total</td><td align = "right">{}</td><td align = "right">{}</td>'\
'<td align = "right">{}</td><td></td><td></td><td></td></tr>'.format(
total_jobs,
total_failed,
round((total_jobs - total_failed) * 100. / total_jobs, 1))
table_summary += '\n<tr><td align = "left">Total</td><td align = "right">{}</td><td align = "right">{}</td>'\
'<td align = "right">{}</td></td></tr>'.format(
total_jobs,
total_failed,
round((total_jobs - total_failed) * 100. / total_jobs, 1))
# Grab HTML template, replace variables shown
text = "".join(open(self.template).readlines())
text = text.replace("$START", self.start_time)
text = text.replace("$END", self.end_time)
text = text.replace("$TABLE_SUMMARY", table_summary)
text = text.replace("$TABLE_JOBS", job_table)
text = text.replace("$TABLE", table)
text = text.replace("$VO", self.vo)
# Generate HTML file to send
fn = "{}-jobrate.{}".format(self.vo.lower(),
self.start_time.replace("/", "-"))
with open(fn, 'w') as f:
f.write(text)
# The part that actually emails people.
if self.no_email:
print "Not sending email"
return
if self.is_test:
emails = re.split('[; ,]', self.config.get("email", "test_to"))
else:
emails = re.split('[; ,]', self.config.get("email", "{}_email".format(self.vo.lower()))) + \
re.split('[: ,]', self.config.get("email", "test_to"))
TextUtils.sendEmail(([], emails),
"{} Production Jobs Success Rate on the OSG Sites ({} - {})".format(self.vo,
self.start_time,
self.end_time),
{"html": text},
("Gratia Operation", "[email protected]"),
"smtp.fnal.gov")
os.unlink(fn) # Delete HTML file
if __name__ == "__main__":
opts, args = Reporter.parse_opts()
if opts.debug:
logging.basicConfig(filename='jobsuccessreport.log', level=logging.DEBUG)
else:
logging.basicConfig(filename='jobsuccessreport.log', level=logging.ERROR)
logging.getLogger('elasticsearch.trace').addHandler(logging.StreamHandler())
try:
config = Configuration.Configuration()
config.configure(opts.config)
r = JobSuccessRateReporter(config, opts.start, opts.end, opts.vo, opts.template, opts.is_test, opts.verbose,
opts.no_email)
r.generate()
r.send_report()
except Exception as e:
print >> sys.stderr, traceback.format_exc()
Reporter.runerror(e, traceback.format_exc(), ['[email protected]'])
sys.exit(1)
sys.exit(0)