-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmonitutils.py
282 lines (218 loc) · 8.28 KB
/
monitutils.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
#!/usr/bin/env python
import gzip
import json
import os
from datetime import datetime
import pymysql
import cx_Oracle
import yaml
from workflowwrapper import Workflow
# -----------------------------------------------------------------------------
def save_json(json_obj, filename='tmp', gzipped=False):
"""
save json object to a local formatted text file, for debug
:param dict json_obj: the json object
:param str filename: the base name of the file to be saved
:param bool gzipped: if gzip output document, default is False
:returns: full filename
:rtype: str
"""
fn = "{}.json".format(filename)
msg = json.dumps(
json_obj, sort_keys=True, indent=4, separators=(',', ': '))
if gzipped:
fn += '.gz'
with gzip.open(fn, 'wb') as f:
f.write(msg.encode())
else:
with open(fn, 'w') as f:
f.write(msg)
return fn
# -----------------------------------------------------------------------------
def get_yamlconfig(configPath):
'''
get a dict of config file (YAML) pointed by configPath.
:param str configPath: path of config file
:returns: dict of config
:rtype: dict
'''
if not os.path.isfile(configPath):
return {}
try:
return yaml.load(open(configPath).read(), Loader=yaml.FullLoader)
except:
return {}
# -----------------------------------------------------------------------------
def get_workflowlist_from_db(config, queryCmd):
'''
get a list of workflows from oracle db from a config dictionary which has a ``oracle`` key.
:param dict config: config dictionary
:param str queryCmd: SQL query command
:returns: list of workflow names that are LIKE running
:rtype: list
'''
if 'oracle' not in config:
return []
oracle_db_conn = cx_Oracle.connect(*config['oracle']) # pylint:disable=c-extension-no-member
oracle_cursor = oracle_db_conn.cursor()
oracle_cursor.execute(queryCmd)
wkfs = [row for row, in oracle_cursor]
oracle_db_conn.close()
return wkfs
# -----------------------------------------------------------------------------
def get_workflow_from_db(configPath, queryCmd):
'''
get a list of :py:class:`Workflow` objects by parsing the oracle db
indicated in ``config.yml`` pointed by configpath.
:param str configPath: path of config file
:param str queryCmd: SQL query command
:returns: list of :py:class:`Workflow`
:rtype: list
'''
wf_list = []
config = get_yamlconfig(configPath)
if not config:
return wf_list
wfs = get_workflowlist_from_db(config, queryCmd)
if wfs:
wf_list = [Workflow(wf) for wf in wfs]
return wf_list
# -----------------------------------------------------------------------------
def create_prediction_history_db(config):
username_, password_, dbname_ = config['mysql']
conn = pymysql.connect(host='localhost',
user=username_,
password=password_,
db=dbname_)
try:
with conn.cursor() as cursor:
sql = """\
create table if not exists OSDroidDB.PredictionHistory (
hid BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
good FLOAT,
acdc FLOAT,
resubmit FLOAT,
timestamp TIMESTAMP
); """
cursor.execute(sql)
conn.commit()
finally:
conn.close()
# -----------------------------------------------------------------------------
def create_label_archive_db(config):
username_, password_, dbname_ = config['mysql']
conn = pymysql.connect(host='localhost',
user=username_,
password=password_,
db=dbname_)
try:
with conn.cursor() as cursor:
sql = """\
create table if not exists OSDroidDB.LabelArchive (
name VARCHAR(255) NOT NULL PRIMARY KEY,
lable INT
); """
cursor.execute(sql)
conn.commit()
finally:
conn.close()
# -----------------------------------------------------------------------------
def create_doc_archive_db(config):
username_, password_, dbname_ = config['mysql']
conn = pymysql.connect(host='localhost',
user=username_,
password=password_,
db=dbname_)
try:
with conn.cursor() as cursor:
sql = """\
create table if not exists OSDroidDB.DocsOneMonthArchive (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
document LONGTEXT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);"""
cursor.execute(sql)
conn.commit()
print("Successfully created table OSDroidDB.DocsOneMonthArchive !")
with conn.cursor() as cursor:
sql = """\
CREATE EVENT OSDroidDB.DocsCleanOneMonth
ON SCHEDULE EVERY 24 HOUR
DO
DELETE FROM OSDroidDB.DocsOneMonthArchive
WHERE TIMESTAMPDIFF(DAY, timestamp, NOW()) > 30;"""
cursor.execute(sql)
conn.commit()
print("Successfully created event OSDroidDB.DocsCleanOneMonth !")
finally:
conn.close()
# -----------------------------------------------------------------------------
def update_prediction_history_db(config, values):
username_, password_, dbname_ = config['mysql']
conn = pymysql.connect(host='localhost',
user=username_,
password=password_,
db=dbname_)
if not isinstance(values, list):
values = [values,]
try:
with conn.cursor() as cursor:
sql = "INSERT INTO PredictionHistory (name, good, acdc, resubmit, timestamp) VALUES (%s, %s, %s, %s, %s);"
cursor.executemany(sql, values)
conn.commit()
finally:
conn.close()
# -----------------------------------------------------------------------------
def update_label_archive_db(config, values):
username_, password_, dbname_ = config['mysql']
conn = pymysql.connect(host='localhost',
user=username_,
password=password_,
db=dbname_)
if not isinstance(values, list):
values = [values,]
try:
with conn.cursor() as cursor:
sql = "REPLACE INTO LabelArchive (name, label) VALUES (%s, %s);"
cursor.executemany(sql, values)
conn.commit()
finally:
conn.close()
# -----------------------------------------------------------------------------
def update_doc_archive_db(config, values):
username_, password_, dbname_ = config['mysql']
conn = pymysql.connect(host='localhost',
user=username_,
password=password_,
db=dbname_)
if not isinstance(values, list):
values = [values,]
try:
with conn.cursor() as cursor:
sql = """INSERT INTO OSDroidDB.DocsOneMonthArchive (name, document) VALUES (%s, %s);"""
cursor.executemany(sql, values)
conn.commit()
finally:
conn.close()
# -----------------------------------------------------------------------------
def get_labeled_workflows(config):
username_, password_, dbname_ = config['mysql']
conn = pymysql.connect(host='localhost',
user=username_,
password=password_,
db=dbname_)
result = []
try:
with conn.cursor() as cursor:
sql = "SELECT name FROM LabelArchive;"
cursor.execute(sql)
result = [x[0] for x in cursor.fetchall()]
finally:
conn.close()
return result
# -----------------------------------------------------------------------------
def fmttime(ts, fmt='%Y-%m-%d %H:%M:%S'):
return datetime.fromtimestamp(ts).strftime(fmt)
# -----------------------------------------------------------------------------