-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_connection.py
499 lines (433 loc) · 13.6 KB
/
db_connection.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
import csv
import datetime
import time
import logging
import os
from config import DB_HOST, DB_USER, DB_PWD, DB_DATABASE
from sql_queries import *
import mysql.connector
# Utils
def normalize_ce_name(target_ce):
return target_ce.replace("::", "_").lower()[len("alice_"):]
# Connection Functions
def get_connection(auto_commit=True):
"""
Establish database connection
Args:
auto_commit (bool, optional): Enable auto commit. Defaults to True.
Returns:
cursor: MySQL cursor object
connection: MySQL connection object
"""
try:
connection = mysql.connector.connect(
host=DB_HOST,
user=DB_USER,
password=DB_PWD,
database=DB_DATABASE,
autocommit=auto_commit
)
cursor = connection.cursor()
return cursor, connection
except mysql.connector.Error as error:
logging.error("Error while connecting to MySQL", error)
def clear_tables(all=False):
"""
Clear tables nodes, jobs, processing_state, parameters
Args:
all (bool, optional): Clear sites, run, keys table if True . Defaults to False.
"""
cursor, conn = get_connection(auto_commit=False)
try:
cursor.execute("SET FOREIGN_KEY_CHECKS = 0")
if all:
cursor.execute(DELETE_SITES)
cursor.execute(DELETE_RUN)
cursor.execute(DELETE_KEYS)
cursor.execute(DELETE_NODES)
cursor.execute(DELETE_PROCESSING_STATE)
cursor.execute(DELETE_PARAMETERS)
cursor.execute(DELETE_JOBS)
cursor.execute("SET FOREIGN_KEY_CHECKS = 1")
conn.commit()
logging.debug('Database tables cleared')
except mysql.connector.Error as error:
logging.error("Failed to clear database: {}".format(error))
conn.rollback()
finally:
if(conn.is_connected()):
cursor.close()
conn.close()
def increment_run_id():
"""
Increment the Run ID by one
"""
cursor, conn = get_connection()
try:
cursor.execute(INCREMENT_RUN_ID, ['STARTED'])
logging.debug('Run Id incremented')
except mysql.connector.Error as error:
logging.error("Failed to increment run id: {}".format(error))
finally:
if(conn.is_connected()):
cursor.close()
conn.close()
def start_new_run():
"""
Start a new run if a run does not exist
"""
cursor, conn = get_connection()
run_id = get_run_id()
run_exists = check_run_exists(run_id)
if not run_exists:
increment_run_id()
else:
logging.error(
"Cannot start a new run as the last run is still running")
def check_run_exists(run_id):
"""
Check whether the given run_id is still running
Args:
run_id (int): Run ID
Returns:
flag: True if run_id is still running
"""
cursor, conn = get_connection()
flag = True
try:
cursor.execute(CHECK_RUN_STATE, [run_id])
state = cursor.fetchone()[0]
if state == 'STARTED':
logging.debug('Last run is still running')
flag = True
else:
logging.debug('No currently executing runs')
flag = False
except mysql.connector.Error as error:
logging.error("Failed to increment run id: {}".format(error))
flag = False
finally:
if(conn.is_connected()):
cursor.close()
conn.close()
return flag
def change_run_state(state):
"""
Change the state of the Run
Args:
state (enum ['STARTED','COMPLETED','TIMED_OUT','ABORTED']): Run State
"""
run_id = get_run_id()
cursor, conn = get_connection()
try:
cursor.execute(ABORT_RUN, [state, run_id])
logging.debug('Run aborted')
except mysql.connector.Error as error:
logging.error("Failed to abort the run: {}".format(error))
finally:
if(conn.is_connected()):
cursor.close()
conn.close()
def get_run_id():
"""
Get latest Run ID
Returns:
run_id(int): Run ID
"""
cursor, conn = get_connection()
try:
cursor.execute(GET_LAST_RUN_ID)
run_id = cursor.fetchone()
return run_id[0]
except mysql.connector.Error as error:
logging.error("Failed to get last run id: {}".format(error))
finally:
if(conn.is_connected()):
cursor.close()
conn.close()
# Site Related Functions
def get_sites():
"""
Get all Grid sites
Returns:
sites(dict): All site data
"""
cursor, conn = get_connection()
try:
cursor.execute(GET_SITES)
results = cursor.fetchall()
sites = []
for row in results:
site_id = row[0]
site_name = row[1]
normalized_name = row[2]
num_nodes = row[3]
last_update = row[4]
site = {
'site_id': site_id,
'site_name': site_name,
'normalized_name': normalized_name,
'num_nodes': num_nodes,
'last_update': last_update
}
sites.append(site)
return sites
except mysql.connector.Error as error:
logging.error("Failed to retrieve sites: {}".format(error))
finally:
if(conn.is_connected()):
cursor.close()
conn.close()
def get_site_ids():
"""
Get Site IDs
Returns:
Site IDs(list)
"""
cursor, conn = get_connection()
try:
cursor.execute(GET_SITE_IDS)
results = cursor.fetchall()
ids = []
for row in results:
site_id = row[0]
ids.append(site_id)
return ids
except mysql.connector.Error as error:
logging.debug("Failed to get site ids: {}".format(error))
finally:
if(conn.is_connected()):
cursor.close()
conn.close()
def add_sites_from_csv(csv_filename):
"""
Add Grid sites from CSV file
Args:
csv_filename (str): Name of the CSV file (Format: sitename,num_nodes)
"""
cursor, conn = get_connection()
site_tuples = []
sitenames = get_sitenames()
with open(csv_filename, newline='') as csvfile:
csv_reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in csv_reader:
details = row[0].split(',')
current_site_name = details[0]
is_exists = check_sitename_exists(sitenames, current_site_name)
if (is_exists == True):
logging.warning(
'%s already exists in the database. Please use the update function. Skipping...', current_site_name)
else:
num_nodes = details[1]
if not num_nodes:
num_nodes = -1
else:
num_nodes = int(num_nodes)
normalized_name = normalize_ce_name(current_site_name)
site_tuples.append(
(current_site_name, normalized_name, num_nodes))
logging.debug('Adding %s to the database', current_site_name)
try:
cursor.executemany(ADD_SITE, site_tuples)
conn.commit()
logging.debug("Total number of sites added : %s", cursor.rowcount)
except mysql.connector.Error as error:
logging.error("Failed to add sites to database: {}".format(error))
conn.rollback()
finally:
if(conn.is_connected()):
cursor.close()
conn.close()
logging.debug("connection is closed")
def update_site_last_update_time(site_id):
"""
Update last update time of the site
Args:
site_id (int): Site ID
"""
cursor, conn = get_connection()
try:
cursor.execute(UPDATE_LAST_SITE_UPDATE_TIME, [site_id])
except mysql.connector.Error as error:
logging.error(
"Failed to update site last update times: {}".format(error))
finally:
if(conn.is_connected()):
cursor.close()
conn.close()
def check_sitename_exists(sitenames, current_site_name):
"""
Check whether current_site_name exists in sitenames
Args:
sitenames (list): List of available sites in the DB
current_site_name (str): Name of the new site
Returns:
Bool: True if current_site_name exists in sitenames
"""
if not sitenames:
return False
else:
if current_site_name in sitenames:
return True
else:
return False
def get_sitenames():
"""
Get all names of sites
Returns:
sitenames(list)
"""
cursor, conn = get_connection()
sitenames = []
try:
cursor.execute(GET_SITENAMES)
results = cursor.fetchall()
for row in results:
sitenames.append(row[0])
return sitenames
except mysql.connector.Error as error:
logging.error("Failed to get sitenames: {}".format(error))
finally:
if(conn.is_connected()):
cursor.close()
conn.close()
def update_processing_state(state, initialize=True):
"""
Update processing_states table
Return True if succesfull
"""
success_flag = False
run_id = get_run_id()
cursor, conn = get_connection(auto_commit=False)
try:
if initialize:
site_ids = get_site_ids()
state_tuple = []
for site_id in site_ids:
state_tuple.append((site_id, run_id, state))
cursor.executemany(INITIALIZE_PROCESSING_STATE, state_tuple)
else:
site_ids = get_sites_by_processing_state('WAITING')
state_tuple = []
for site_id in site_ids:
state_tuple.append((state, site_id, run_id))
cursor.executemany(UPDATE_PROCESSING_STATE, state_tuple)
conn.commit()
logging.debug('Updated processing states to %s successfully', state)
success_flag = True
except mysql.connector.Error as error:
logging.error("Failed to update processing states: {}".format(error))
success_flag = False
finally:
if(conn.is_connected()):
cursor.close()
conn.close()
return success_flag
def get_sites_by_processing_state(state):
"""
Get Sites in the given state
Args:
state (enum ['WAITING','COMPLETED','STALLED','ABORTED']): Processing state of site
run_id (int): Run ID
Returns:
site_ids(list): Site ID list
"""
run_id = get_run_id()
site_ids = []
cursor, conn = get_connection()
try:
cursor.execute(GET_SITE_IDS_BY_PROCESSING_STATE, (state, run_id))
results = cursor.fetchall()
for row in results:
site_ids.append(row[0])
except mysql.connector.Error as error:
logging.error("Failed to fetch processing states: {}".format(error))
finally:
if(conn.is_connected()):
cursor.close()
conn.close()
return site_ids
# Job related functions
def add_job(job_id, site_id):
"""
Add jobs to the database
Args:
job_id (str): Job ID
site_id (int)
"""
cursor, conn = get_connection()
try:
run_id = get_run_id()
cursor.execute(ADD_JOB, (job_id, run_id, site_id, 'STARTED'))
logging.debug('Job %s added to database succesfully', job_id.strip())
except mysql.connector.Error as error:
logging.error("Failed to add job: {}".format(error))
finally:
if(conn.is_connected()):
cursor.close()
conn.close()
def get_all_job_ids_by_state(state):
"""
Get all jobs in the database with given state
Args:
state (enum): ('STARTED','STALLED','COMPLETED','KILLED')
Returns:
job_ids(list): Job IDs of jobs in given state
"""
cursor, conn = get_connection()
try:
run_id = get_run_id()
cursor.execute(GET_ALL_JOB_IDS_BY_STATE, [state, run_id])
results = cursor.fetchall()
job_ids = []
for row in results:
job_ids.append(row[0])
return job_ids
except mysql.connector.Error as error:
logging.error("Failed to get jobs by state: {}".format(error))
finally:
if(conn.is_connected()):
cursor.close()
conn.close()
def update_job_state_by_job_id(job_id, state):
"""
Update state of the job
Args:
job_id (int): Single id or id list
state (enum): ('STARTED','ERROR','STALLED','COMPLETED','KILLED')
"""
cursor, conn = get_connection(auto_commit=False)
run_id = get_run_id()
job_tuple = []
if type(job_id) == str:
job_tuple.append((state, job_id, run_id))
elif type(job_id) == list:
for id in job_id:
job_tuple.append((state, id, run_id))
try:
cursor.executemany(UPDATE_JOB_STATE_BY_JOBID, job_tuple)
conn.commit()
except mysql.connector.Error as error:
logging.error("Failed to update job state: {}".format(error))
conn.rollback()
finally:
if(conn.is_connected()):
cursor.close()
conn.close()
def add_job_keys(keys):
"""
Add jobs keys to the database
Args:
keys (str): Key list of the commands in the job script
"""
cursor, conn = get_connection()
try:
run_id = get_run_id()
cursor.execute(ADD_KEYS, (run_id, keys))
logging.debug('Job key list %s added to database succesfully', keys)
except mysql.connector.Error as error:
logging.error("Failed to add job keys: {}".format(error))
finally:
if(conn.is_connected()):
cursor.close()
conn.close()