-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathworkflowmonitexporter.py
310 lines (241 loc) · 9.56 KB
/
workflowmonitexporter.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
#!/usr/bin/env python
import os
import sys
import time
import sqlite3
import logging
import random
import concurrent.futures
import logging.config
from os.path import join, dirname, abspath
import yaml
from CMSMonitoring.StompAMQ import StompAMQ
from monitutils import get_yamlconfig, get_workflow_from_db
from workflowcollector import populate_error_for_workflow
CRED_FILE_PATH = join(dirname(abspath(__file__)), 'config/credential.yml')
CONFIG_FILE_PATH = join(dirname(abspath(__file__)), 'config/config.yml')
LOGGING_CONFIG = join(dirname(abspath(__file__)), 'config/configLogging.yml')
logger = logging.getLogger("workflowmonitLogger")
rootlogger = logging.getLogger()
class No502WarningFilter(logging.Filter):
def filter(self, record):
return 'STATUS: 502' not in record.getMessage()
rootlogger.addFilter(No502WarningFilter())
# -----------------------------------------------------------------------------
def do_work(item):
"""Query, build and return the error doc.
:param tuple item: (``Workflow``, minFailureRate, configPath)
:returns: error doc
:rtype: dict
"""
wf, minFailureRate, configPath = item
# database path and insertion command
dbPath = get_yamlconfig(configPath).get(
'workflow_status_db',
os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'workflow_status.sqlite'))
DB_UPDATE_CMD = """INSERT OR REPLACE INTO workflowStatuses VALUES (?,?,?)"""
res = {}
try:
time.sleep(random.random()*0.1)
failurerate = wf.get_failure_rate()
toUpdate = (wf.name, wf.get_reqdetail().get(wf.name, {}).get(
'RequestStatus', ''), failurerate)
if any(toUpdate[:-1]):
conn = sqlite3.connect(dbPath)
with conn:
c = conn.cursor()
c.execute(DB_UPDATE_CMD, toUpdate)
if failurerate > minFailureRate:
res = populate_error_for_workflow(wf)
except Exception as e:
logger.exception("workflow<{}> except when do_work!\nMSG: {}".format(
wf.name, str(e)))
pass
return res
# -----------------------------------------------------------------------------
def getCompletedWorkflowsFromDb(configPath):
"""
Get completed workflow list from local status db (setup to avoid unnecessary caching)
Workflows whose status ends with *archived* are removed from further caching.
:param str configPath: location of config file
:returns: list of workflow (str)
:rtype: list
"""
config = get_yamlconfig(configPath)
if not config:
sys.exit('Config file: {} not exist, exiting..'.format(configPath))
dbPath = config.get(
'workflow_status_db',
os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'workflow_status.sqlite'))
DB_CREATE_CMD = """CREATE TABLE IF NOT EXISTS workflowStatuses (
name TEXT PRIMARY KEY,
status TEXT,
failurerate REAL
);"""
DB_QUERY_CMD = """SELECT * FROM workflowStatuses WHERE status LIKE '%archived'"""
res = []
conn = sqlite3.connect(dbPath)
with conn:
c = conn.cursor()
c.execute(DB_CREATE_CMD)
for row in c.execute(DB_QUERY_CMD):
res.append(row[0])
return res
# -----------------------------------------------------------------------------
def updateWorkflowStatusToDb(configPath, wcErrorInfos):
"""
update workflow status to local status db, with the information from ``wcErrorInfos``.
:param str configPath: location of config file
:param list wcErrorInfos: list of dicts returned by :py:func:`buildDoc`
:returns: True
"""
config = get_yamlconfig(configPath)
if not config:
sys.exit('Config path: {} not exist, exiting..'.format(configPath))
dbPath = config.get(
'workflow_status_db',
os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'workflow_status.sqlite'))
DB_UPDATE_CMD = """INSERT OR REPLACE INTO workflowStatuses VALUES (?,?,?)"""
toUpdate = []
for e in wcErrorInfos:
entry = (e.get('name', ''), e.get('status', ''),
e.get('failureRate', 0.))
if not all(entry[:-1]):
continue
toUpdate.append(entry)
conn = sqlite3.connect(dbPath)
with conn:
c = conn.cursor()
c.executemany(DB_UPDATE_CMD, toUpdate)
return True
# -----------------------------------------------------------------------------
def prepareWorkflows(configpath, minfailurerate=0., test=False, batchsize=300):
"""
extract workflows from unified db, filter out those need to query,
stratified with batchsize.
:param str configpath: path to config file
:param float minfailurerate: input to pack for jobs
:param bool test: for debug
"param int batchsize: number of workflows per batch
:returns: list of list of (:py:class:`Workflow`, `minfailurerate`, `configpath`),
grouped per `batchsize`.
:rtype: list
"""
DB_QUERY_CMD = "SELECT NAME FROM CMS_UNIFIED_ADMIN.WORKFLOW WHERE WM_STATUS LIKE 'running%'"
_wkfs = []
try:
_wkfs = get_workflow_from_db(configpath, DB_QUERY_CMD) # list of `Workflow`
except Exception as e:
logger.error("Fail to get running workflows from UNIFIED DB!\nMsg: {}".format(str(e)))
raise
msg = 'Number of workflows fetched from db: {}'.format(len(_wkfs))
logger.info(msg)
if test: _wkfs = _wkfs[-10:]
completedWfs = getCompletedWorkflowsFromDb(configpath)
wkfs = [w for w in _wkfs if w.name not in completedWfs]
msg = 'Number of workflows to query: {}'.format(len(wkfs))
logger.info(msg)
wkfs = [(w, minfailurerate, configpath) for w in wkfs]
# slice them according to batch size
res = [wkfs[x:x + batchsize] for x in range(0, len(wkfs), batchsize)]
msg = 'Divided into {0} batches with batchsize {1}.'.format(len(res), batchsize)
logger.info(msg)
return res
# -----------------------------------------------------------------------------
def buildDoc(source, doconcurrent=True, timeout=300):
"""
Given a list of workflow packs, returns a list of documents (each for one workflow)
:param list source: a list of workflow packs (tuple)
:param bool doconcurrent: default True. If True, concurrently execute jobs
:param float timeout: default 300. timeout limit/seconds for each job when launching jobs parallelly
:returns: list of documents
:rtype: list
"""
results = list()
startTime = time.time()
if doconcurrent:
with concurrent.futures.ThreadPoolExecutor(
max_workers=len(source)) as executor:
futures = {executor.submit(do_work, item): item for item in source}
for future in concurrent.futures.as_completed(futures, timeout=timeout):
wfname = futures[future][0].name
try:
res = future.result()
if res: results.append(res)
except Exception as e:
print("*** Exception occured in buildDoc ***")
print("Workflow:", wfname)
print("Msg:", str(e))
else:
for item in source:
_starttime = time.time()
results.append(do_work(item))
logger.info("--> took {0}s".format(time.time()-_starttime))
elapsedTime = time.time() - startTime
msg = '---> took {}s'.format(elapsedTime)
logger.info(msg)
return results
# -----------------------------------------------------------------------------
def sendDoc(cred, docs):
"""
Given a credential dict and documents to send, make notification.
:param dict cred: credential required by StompAMQ
:param list docs: documents to send
:returns: None
"""
if not docs:
logger.info("No document going to be set to AMQ.")
return []
try:
amq = StompAMQ(
username=None,
password=None,
producer=cred['producer'],
topic=cred['topic'],
validation_schema=None,
host_and_ports=[(cred['hostport']['host'],
cred['hostport']['port'])],
logger=logger,
cert=cred['cert'],
key=cred['key'])
doctype = 'workflowmonit_{}'.format(cred['producer'])
notifications = [
amq.make_notification(payload=doc, docType=doctype)[0]
for doc in docs
]
failures = amq.send(notifications)
logger.info("{}/{} docs successfully sent to AMQ.".format(
(len(notifications) - len(failures)), len(notifications)))
return failures
except Exception as e:
logger.exception("Failed to send data to StompAMQ. Error: {}".format(
str(e)))
raise
# -----------------------------------------------------------------------------
def test():
with open(LOGGING_CONFIG, 'r') as f:
config = yaml.safe_load(f.read())
logging.config.dictConfig(config)
cred = get_yamlconfig(CRED_FILE_PATH)
wfpacks = prepareWorkflows(CONFIG_FILE_PATH, test=False)
# test only the first batch
firstbatch = wfpacks[0]
docs = buildDoc(firstbatch, doconcurrent=True)
updateWorkflowStatusToDb(CONFIG_FILE_PATH, docs)
logger.info('Number of updated workflows: {}'.format(len(docs)))
if docs:
print('Number of docs: ', len(docs))
if len(str(docs))>500:
print('[content]', str(docs)[:100], '...', str(docs)[-100:])
else:
print('[content]', docs)
else:
print("docs empty!!")
if __name__ == "__main__":
test()