-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjobutils.py
2228 lines (2109 loc) · 87 KB
/
jobutils.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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import uuid
from jinja2 import Template
import secrets
import kubejob
import yaml
import envvars
import mysql.connector
import json
import datetime
import logging
from cryptography.fernet import Fernet
import base64
import re
import email_utils
import shutil
import jira.client
from des_tasks.cutout.worker.bulkthumbs import validate_user_defaults as validate_cutout_user_defaults
from des_tasks.cutout.worker.bulkthumbs import validate_positions_table as validate_cutout_positions_table
import numpy as np
STATUS_OK = 'ok'
STATUS_ERROR = 'error'
# TODO: Replace this global hard-coded variable with input configuration
MAX_SIZE_IN_ARCMINUTES = 12.0
log_format = "%(asctime)s %(name)8s %(levelname)5s %(message)s"
logging.basicConfig(
level=logging.INFO,
handlers=[logging.FileHandler("test.log"), logging.StreamHandler()],
format=log_format,
)
logger = logging.getLogger(__name__)
try:
# Initialize global Jira API object
#
# Obtain the Jira API auth credentials from the mounted secret
jira_access_file = os.path.join(
os.path.dirname(__file__),
"jira_access.yaml"
)
with open(jira_access_file, 'r') as cfile:
conf = yaml.load(cfile, Loader=yaml.FullLoader)['jira']
# Initialize Jira API object
JIRA_API = jira.client.JIRA(
options={'server': 'https://opensource.ncsa.illinois.edu/jira'},
basic_auth=(
base64.b64decode(conf['uu']).decode().strip(),
base64.b64decode(conf['pp']).decode().strip()
)
)
except:
JIRA_API = None
def password_encrypt(password):
secret = envvars.JWT_HS256_SECRET
key = base64.urlsafe_b64encode(secret.encode('UTF-8'))
locksmith = Fernet(key)
return locksmith.encrypt(password.encode('UTF-8')).decode('UTF-8')
def password_decrypt(password):
secret = envvars.JWT_HS256_SECRET
key = base64.urlsafe_b64encode(secret.encode('UTF-8'))
locksmith = Fernet(key)
return locksmith.decrypt(password.encode('UTF-8')).decode('UTF-8')
class JobsDb:
def __init__(self, mysql_host, mysql_user, mysql_password, mysql_database):
self.host = mysql_host
self.user = mysql_user
self.password = mysql_password
self.database = mysql_database
self.cur = None
self.cnx = None
self.db_schema_version = 19
self.table_names = [
'job',
'query',
'cutout',
'role',
'session',
'meta',
'help',
'message',
'message_read',
'message_role',
'user_preferences',
'cron',
'analytics',
'job_renewal',
]
def open_db_connection(self):
if self.cnx is None or self.cur is None:
# Open database connection
self.cnx = mysql.connector.connect(
host=self.host,
user=self.user,
password=self.password,
database=self.database,
)
# Get database cursor object
self.cur = self.cnx.cursor()
def close_db_connection(self):
if self.cnx != None and self.cur != None:
try:
# Commit changes to database and close connection
self.cnx.commit()
self.cur.close()
self.cnx.close()
self.cur = None
self.cnx = None
except Exception as e:
error = str(e).strip()
self.cur = None
self.cnx = None
return False, error
def parse_sql_commands(self, sql_file):
msg = ''
status = STATUS_OK
commands = []
try:
with open(sql_file) as f:
dbUpdateSql = f.read()
#Individual SQL commands must be separated by the custom delimiter '#---'
for sqlCommand in dbUpdateSql.split('#---'):
if len(sqlCommand) > 0 and not sqlCommand.isspace():
commands.append(sqlCommand)
except Exception as e:
msg = str(e).strip()
logger.error(msg)
status = STATUS_ERROR
return [commands, status, msg]
def update_db_tables(self):
self.open_db_connection()
try:
current_schema_version = 0
try:
# Get currently applied database schema version if tables have already been created
self.cur.execute(
"SELECT `schema_version` FROM `meta` LIMIT 1"
)
for (schema_version,) in self.cur:
current_schema_version = schema_version
logger.info("schema_version taken from meta table")
except:
logger.info("meta table not found")
logger.info('current schema version: {}'.format(current_schema_version))
# Update the database schema if the versions do not match
if current_schema_version < self.db_schema_version:
# Sequentially apply each DB update until the schema is fully updated
for db_update_idx in range(current_schema_version+1, self.db_schema_version+1, 1):
sql_file = os.path.join(os.path.dirname(__file__), "db_schema_update", "db_schema_update.{}.sql".format(db_update_idx))
commands, status, msg = self.parse_sql_commands(sql_file)
for cmd in commands:
logger.info('Applying SQL command from "{}":'.format(sql_file))
logger.info(cmd)
# Apply incremental update
self.cur.execute(cmd)
# Update `meta` table to match
logger.info("Updating `meta` table...")
try:
self.cur.execute(
"INSERT INTO `meta` (`schema_version`) VALUES ({})".format(db_update_idx)
)
except:
self.cur.execute(
"UPDATE `meta` SET `schema_version`={}".format(db_update_idx)
)
self.cur.execute(
"SELECT `schema_version` FROM `meta` LIMIT 1"
)
for (schema_version,) in self.cur:
logger.info('Current schema version: {}'.format(schema_version))
except Exception as e:
logger.error(str(e).strip())
self.close_db_connection()
def init_db(self):
try:
# Initialize the database tables with info such as admin accounts
# with open(os.path.join(os.path.dirname(__file__), "db_init", "db_init.yaml")) as f:
self.open_db_connection()
with open(os.path.join(envvars.CONFIG_FOLDER_ROOT, "config", "db_init.yaml")) as f:
db_init = yaml.safe_load(f.read())
roles_added = []
for role in db_init['role']:
# Ignore redundant role definitions
if role not in roles_added:
roles_added.append(role)
# Only add the role if the record does not already exist.
self.cur.execute(
(
"SELECT id FROM `role` WHERE username = %s AND role_name = %s LIMIT 1"
),
(
role["username"],
role["role_name"],
)
)
rowId = None
for (id,) in self.cur:
rowId = id
if rowId == None:
self.cur.execute(
(
"INSERT INTO `role` "
"(username, role_name) "
"VALUES (%s, %s)"
),
(
role["username"],
role["role_name"],
)
)
self.close_db_connection()
except Exception as e:
logger.error(str(e).strip())
def reinitialize_tables(self):
try:
# Drop all existing database tables
self.open_db_connection()
for table in self.table_names:
self.cur.execute("DROP TABLE IF EXISTS `{}`".format(table))
self.close_db_connection()
# Sequentially apply updates to database schema until latest version is reached
self.update_db_tables()
# Initialize database
self.init_db()
except Exception as e:
logger.error(str(e).strip())
def validate_apitoken(self, apitoken):
self.open_db_connection()
self.cur.execute(
"SELECT id,user,uuid FROM `job` WHERE apitoken = '{}' LIMIT 1".format(
apitoken)
)
# If there is a result, assume only one exists and return the record id, otherwise return None
rowId = None
for (id,user,uuid) in self.cur:
rowId = id
self.close_db_connection()
return rowId
def delete_apitoken(self, apitoken):
error_msg = ''
self.open_db_connection()
try:
self.cur.execute(
(
"UPDATE `job` SET `apitoken` = '' WHERE `apitoken` = %s"
),
(
apitoken,
)
)
if self.cur.rowcount < 1:
error_msg = 'Error deleting apitoken: {}'.format(apitoken)
logger.error(error_msg)
except Exception as e:
error_msg = str(e).strip()
logger.error(error_msg)
self.close_db_connection()
return error_msg
def job_status(self, username, job_id):
self.open_db_connection()
request_status = STATUS_OK
msg = ''
job_info_list = []
try:
if job_id == "all":
uuid_criterion_sql = ''
sql_values = (username,)
else:
uuid_criterion_sql = ' AND j.uuid = %s '
sql_values = (username, job_id)
sql = '''
SELECT j.type, j.name, j.uuid, j.status, j.msg, j.time_start, j.time_complete, j.time_submitted, q.data, q.query, q.files, c.file_list, c.summary as cutout_summary, c.positions, r.renewal_token, r.expiration_date
FROM `job` j
LEFT JOIN `query` q
ON j.id = q.job_id
LEFT JOIN `cutout` c
ON j.id = c.job_id
LEFT JOIN `job_renewal` r
ON j.id = r.job_id
WHERE j.user = %s {} AND j.deleted = 0 ORDER BY j.time_start DESC
'''.format(uuid_criterion_sql)
self.cur.execute(sql, sql_values)
job_info = None
for (type, name, uuid, status, msg, time_start, time_complete, time_submitted, data, query, files, file_list, cutout_summary, positions, renewal_token, expiration_date) in self.cur:
job_info = {}
job_info["job_type"] = type
job_info["job_name"] = name
job_info["job_id"] = uuid
job_info["job_status"] = status
job_info["job_status_message"] = msg
job_info["job_time_start"] = "" if time_start is None else time_start
job_info["job_time_complete"] = "" if time_complete is None else time_complete
job_info["job_time_submitted"] = "" if time_submitted is None else time_submitted
job_info["data"] = {} if data is None else json.loads(data)
job_info["query"] = query
job_info["query_files"] = [] if files is None else json.loads(files)
job_info["cutout_files"] = [] if file_list is None else json.loads(file_list)
job_info["cutout_summary"] = {} if cutout_summary is None else json.loads(cutout_summary)
job_info["cutout_positions"] = "" if positions is None else positions
job_info["renewal_token"] = "" if renewal_token is None else renewal_token
job_info["expiration_date"] = "" if expiration_date is None else expiration_date
if job_id != "all" or job_info["job_type"] != 'query' or (isinstance(data, str) and data == '{}'):
job_info_list.append(job_info)
if job_id != "all" and not job_info_list:
request_status = STATUS_ERROR
msg = 'Error retrieving job status for user {}, specific job_id {}'.format(username, job_id)
logger.error(msg)
except:
request_status = STATUS_ERROR
msg = 'Error retrieving job status for user {}, job_id {}'.format(username, job_id)
logger.error(msg)
self.close_db_connection()
return [job_info_list, request_status, msg]
def job_list(self, username):
self.open_db_connection()
request_status = STATUS_OK
msg = ''
job_info_list = []
try:
# SELECT uuid as job_id, status as job_status, type as job_type, name as job_name
# FROM `job`
# WHERE `user` = %s AND `deleted` = 0 AND (data IS NULL and
# ORDER BY `time_start` DESC
sql = '''
SELECT j.uuid as job_id, j.status as job_status, j.type as job_type, j.name as job_name, q.data
FROM `job` j
LEFT JOIN `query` q
ON j.id = q.job_id
WHERE j.user = %s AND j.deleted = 0 ORDER BY j.time_start DESC
'''
self.cur.execute(sql, (username,))
job_info = None
for (job_id, job_status, job_type, job_name, data) in self.cur:
job_info = {}
job_info["job_id"] = job_id
job_info["job_status"] = job_status
job_info["job_type"] = job_type
job_info["job_name"] = job_name
if job_type != 'query' or (isinstance(data, str) and data == '{}'):
job_info_list.append(job_info)
# logger.info('Including(data type: {}) {}'.format(type(data), job_info))
# else:
# logger.info('Skipping (data type: {}) {}\nData: {}'.format(type(data), job_info, data))
except:
request_status = STATUS_ERROR
msg = 'Error retrieving job list for user {}'.format(username)
logger.error(msg)
self.close_db_connection()
return [job_info_list, request_status, msg]
def register_job(self, conf):
self.open_db_connection()
if 'email' in conf:
email = conf['email']
else:
email = ''
newJobSql = (
"INSERT INTO `job` "
"(user, type, name, uuid, status, apitoken, user_agent, email, msg, time_submitted) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
)
newJobInfo = (
conf['configjob']["metadata"]["username"],
conf['configjob']["kind"],
conf['configjob']["metadata"]["job_name"],
conf['configjob']["metadata"]["jobId"],
'init',
conf['configjob']["metadata"]["apiToken"],
conf["user_agent"],
email,
'',
datetime.datetime.utcnow(),
)
self.cur.execute(newJobSql, newJobInfo)
if self.cur.lastrowid:
if conf['configjob']["kind"] == 'query':
newQuerySql = (
"INSERT INTO `query` "
"(job_id, query, files, sizes, data) "
"VALUES (%s, %s, %s, %s, %s)"
)
newQueryInfo = (
self.cur.lastrowid,
conf['configjob']['spec']["inputs"]["queryString"],
'[]',
'[]',
'{}',
)
self.cur.execute(newQuerySql, newQueryInfo)
elif conf['configjob']["kind"] == 'test':
# TODO: Add test table row associated with test task
logger.info('Created new job of type "test"')
elif conf['configjob']["kind"] == 'cutout':
opt_vals = {}
opt_params = [
'positions',
'make_fits',
'make_rgb_stiff',
'make_rgb_lupton',
'xsize',
'ysize',
'colors_fits',
'rgb_stiff_colors',
'rgb_lupton_colors',
'rgb_minimum',
'rgb_stretch',
'rgb_asinh',
'discard_fits_files',
]
for key in opt_params:
if key in conf['configjob']['spec']:
opt_vals[key] = conf['configjob']['spec'][key]
else:
opt_vals[key] = None
self.cur.execute(
(
'''
INSERT INTO `cutout`
(
`job_id`,
`db`,
`release`,
`positions`,
`make_fits`,
`make_rgb_stiff`,
`make_rgb_lupton`,
`xsize`,
`ysize`,
`colors_fits`,
`rgb_stiff_colors`,
`rgb_lupton_colors`,
`rgb_minimum`,
`rgb_stretch`,
`rgb_asinh`,
`discard_fits_files`
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
'''
),
(
self.cur.lastrowid,
conf['configjob']['spec']['db'],
conf['configjob']['spec']['release'],
conf['configjob']['spec']['positions'],
opt_vals['make_fits'],
opt_vals['make_rgb_stiff'],
opt_vals['make_rgb_lupton'],
opt_vals['xsize'],
opt_vals['ysize'],
opt_vals['colors_fits'],
opt_vals['rgb_stiff_colors'],
opt_vals['rgb_lupton_colors'],
opt_vals['rgb_minimum'],
opt_vals['rgb_stretch'],
opt_vals['rgb_asinh'],
opt_vals['discard_fits_files'],
)
)
else:
logger.error("Error inserting new job.")
self.close_db_connection()
def update_job_start(self, apitoken):
error_msg = None
rowId = self.validate_apitoken(apitoken)
if not isinstance(rowId, int):
error_msg = 'Invalid apitoken'
return error_msg
self.open_db_connection()
try:
updateJobSql = (
"UPDATE `job` "
"SET status=%s, time_start=%s "
"WHERE id=%s"
)
updateJobInfo = (
'started',
datetime.datetime.utcnow(),
rowId
)
self.cur.execute(updateJobSql, updateJobInfo)
except Exception as e:
error_msg = str(e).strip()
self.close_db_connection()
return error_msg
if self.cur.rowcount != 1:
error_msg = 'Error updating job record'
self.close_db_connection()
return error_msg
def count_pending_jobs(self, username):
num_pending_jobs = 0
self.open_db_connection()
try:
self.cur.execute(
(
"SELECT `status` FROM `job` where `user` = %s AND `deleted` = 0"
),
(
username,
)
)
for (status,) in self.cur:
if status not in ['success', 'failure', 'unknown']:
num_pending_jobs += 1
except Exception as e:
logger.error(str(e).strip())
self.close_db_connection()
return num_pending_jobs
def update_job_complete(self, apitoken, response):
error_msg = None
rowId = self.validate_apitoken(apitoken)
if not isinstance(rowId, int):
error_msg = 'Invalid apitoken'
return error_msg
self.open_db_connection()
try:
response_status = response["status"]
if response_status == "ok":
job_status = "success"
elif response_status == "error":
job_status = "failure"
else:
job_status = "unknown"
except:
job_status = "unknown"
try:
updateJobSql = (
"UPDATE `job` "
"SET status=%s, time_complete=%s, msg=%s "
"WHERE id=%s"
)
updateJobInfo = (
job_status,
datetime.datetime.utcnow(),
'' if response['msg'] is None else response['msg'],
rowId
)
self.cur.execute(updateJobSql, updateJobInfo)
except Exception as e:
error_msg = str(e).strip()
self.close_db_connection()
return error_msg
if self.cur.rowcount != 1:
error_msg = 'Error updating job record {}'.format(rowId)
else:
selectJobSql = (
"SELECT user,type,uuid,name,email from `job` WHERE id=%s"
)
selectJobInfo = (
rowId,
)
self.cur.execute(selectJobSql, selectJobInfo)
for (user, type, uuid, name, email) in self.cur:
job_id = uuid
job_name = name
if job_status == "unknown":
logger.warning('Job {} completion report did not include a final status.'.format(job_id))
conf = {"job": type}
conf['namespace'] = get_namespace()
conf["job_name"] = job_name
conf["job_id"] = job_id
conf["cm_name"] = get_job_configmap_name(type, job_id, user)
# if 'synchronous' not in response or response['synchronous'] != True:
# kubejob.delete_job(conf)
if type == 'test':
updateQuerySql = (
"UPDATE `job` "
"SET msg=%s "
"WHERE id=%s"
)
updateQueryInfo = (
'' if response['msg'] is None else response['msg'],
rowId
)
self.cur.execute(updateQuerySql, updateQueryInfo)
elif type == 'query':
updateQuerySql = (
"UPDATE `query` "
"SET files=%s, sizes=%s, data=%s "
"WHERE job_id=%s"
)
updateQueryInfo = (
json.dumps(response["files"]),
json.dumps(response["sizes"]),
json.dumps(response["data"]),
rowId
)
self.cur.execute(updateQuerySql, updateQueryInfo)
elif type == 'cutout':
self.cur.execute(
(
"UPDATE `cutout` "
"SET file_list=%s, file_size=%s, file_number=%s , summary=%s "
"WHERE job_id=%s"
),
(
json.dumps(response["files"]),
str(response["sizes"]),
len(response["files"]),
json.dumps(response["summary"]),
rowId
)
)
try:
if len(email) > 4:
email_utils.send_note(user, job_id, job_name, email)
except:
logger.error('Failed to send job complete email: {}/{}.'.format(user, job_id))
self.close_db_connection()
error_msg_delete = self.delete_apitoken(apitoken)
if error_msg_delete:
error_msg += f'; {error_msg_delete}'
return error_msg
def session_login(self, username, token, ciphertext):
self.open_db_connection()
status = STATUS_OK
try:
self.cur.execute(
(
"SELECT id from `session` WHERE username=%s"
),
(
username,
)
)
session_id = None
for (id,) in self.cur:
session_id = id
if isinstance(session_id, int):
self.cur.execute(
(
"UPDATE `session` "
"SET last_login=%s, password=%s "
"WHERE username=%s"
),
(
datetime.datetime.utcnow(),
ciphertext,
username,
)
)
else:
self.cur.execute(
(
"INSERT INTO `session` "
"(username, last_login, password) "
"VALUES (%s, %s, %s) "
),
(
username,
datetime.datetime.utcnow(),
ciphertext,
)
)
except Exception as e:
logger.error(str(e).strip())
status = STATUS_ERROR
self.close_db_connection()
return status
def session_logout(self, username):
# This function assumes the logout action is already authorized
self.open_db_connection()
status = STATUS_OK
try:
self.cur.execute(
(
"UPDATE `session` "
"SET password=%s "
"WHERE username=%s"
),
(
'',
username,
)
)
if self.cur.rowcount < 1:
status = "warning"
logger.warning('No record in session table found for user {}'.format(username))
except Exception as e:
logger.error(str(e).strip())
status = STATUS_ERROR
self.close_db_connection()
return status
def get_role_user_list(self, role_name):
self.open_db_connection()
users = []
try:
self.cur.execute(
(
"SELECT username from `role` WHERE role_name=%s"
),
(
role_name,
)
)
for (username,) in self.cur:
if username not in users:
users.append(username)
except Exception as e:
logger.error(str(e).strip())
self.close_db_connection()
return users
def get_user_roles(self, username):
self.open_db_connection()
# Ensure that all users have the default role
roles = ['default']
try:
self.cur.execute(
(
"SELECT role_name from `role` WHERE username=%s"
),
(
username,
)
)
for (role_name,) in self.cur:
if isinstance(role_name, str) and not role_name in roles:
roles.append(role_name)
except Exception as e:
logger.error(str(e).strip())
self.close_db_connection()
return roles
def get_all_user_roles_and_help_requests(self):
self.open_db_connection()
users = {}
users_array = []
try:
self.cur.execute("SELECT username, role_name from `role`")
for (username, role_name,) in self.cur:
# Assume that if the user is in this table, it must have at least one associated role
if username in users:
users[username]['roles'].append(role_name)
else:
users[username] = {
'roles': [role_name],
'help_requests': []
}
# Ensure that all users have the default role
if not 'default' in users[username]['roles']:
users[username]['roles'].append('default')
self.cur.execute("SELECT user, jira_issue from `help` WHERE resolved = 0 ")
for (user, jira_issue,) in self.cur:
if user in users:
users[user]['help_requests'].append(jira_issue)
else:
users[user] = {
# Ensure that all users have the default role
'roles': ['default'],
'help_requests': [jira_issue]
}
for username in users:
users_array.append({
'username': username,
'roles': users[username]['roles'],
'help_requests': users[username]['help_requests']
})
# # Search for issues in DESHELP
# jql = '''summary ~ "Help with DESDM account"
# and project = "DESHELP"
# and (text ~ "Reset my passwords" | text ~ "Forgot DB credentials")
# and status = "Open"
# '''
# deshelpIssues = []
# try:
# for issue in JIRA_API.search_issues(jql):
# deshelpIssues.append(issue.key)
# logger.info('password reset issues: \n{}'.format(deshelpIssues))
# except Exception as e:
# logger.error(str(e).strip())
except Exception as e:
logger.error(str(e).strip())
self.close_db_connection()
return users_array
def sync_help_requests_with_jira(self):
error_msg = ''
self.open_db_connection()
try:
self.cur.execute("SELECT id, user, jira_issue from `help` ")
# Compile the records in an array before executing more SQL commands to empty the cursor
jira_issues = []
for (id, user, jira_issue,) in self.cur:
jira_issues.append({
'id': id,
'user': user,
'jira_issue': jira_issue
})
for x in jira_issues:
try:
issue = JIRA_API.issue(x['jira_issue'])
# View the fields and their values for the issue:
# for field_name in issue.raw['fields']:
# logger.info("Field: {}\nValue: {}".format(field_name, issue.raw['fields'][field_name]))
if issue.fields.resolution == None:
self.cur.execute("UPDATE `help` SET resolved = 0 WHERE id = {}".format(x['id']))
else:
self.cur.execute("UPDATE `help` SET resolved = 1 WHERE id = {}".format(x['id']))
except Exception as e:
error_msg = '{}\n{}'.format(error_msg, str(e).strip())
logger.error(error_msg)
except Exception as e:
error_msg = str(e).strip()
logger.error(error_msg)
self.close_db_connection()
return error_msg
def get_password(self, username):
self.open_db_connection()
try:
self.cur.execute(
(
"SELECT password from `session` WHERE username=%s"
),
(
username,
)
)
ciphertext = None
for (password,) in self.cur:
ciphertext = password
if isinstance(ciphertext, str):
return password_decrypt(ciphertext)
except Exception as e:
logger.error(str(e).strip())
self.close_db_connection()
def mark_job_deleted(self, job_id):
error_msg = ''
self.open_db_connection()
try:
self.cur.execute(
(
"UPDATE `job` SET `deleted`=%s WHERE `uuid` = %s"
),
(
True,
job_id,
)
)
if self.cur.rowcount != 1:
error_msg = 'Error updating job record'
except Exception as e:
error_msg = str(e).strip()
logger.error(error_msg)
self.close_db_connection()
return error_msg
def delete_job_files(self, job_id, username):
status = STATUS_OK
error_msg = ''
self.open_db_connection()
try:
job_info_list, request_status, status_msg = JOBSDB.job_status(username, job_id)
if request_status == STATUS_ERROR:
status = STATUS_ERROR
error_msg = status_msg
else:
delete_path = os.path.join('/jobfiles', username, job_info_list[0]['job_type'], job_id)
if os.path.isdir(delete_path):
shutil.rmtree(delete_path)
archive_file = os.path.join('/jobfiles', username, job_info_list[0]['job_type'], '{}.tar.gz'.format(job_id))
if os.path.isfile(archive_file):
os.remove(archive_file)
except Exception as e:
error_msg = str(e).strip()
logger.error(error_msg)
self.close_db_connection()
return [status, error_msg]
def renew_job(self, renewal_token, job_ttl=envvars.DESACCESS_JOB_FILES_LIFETIME):
status = STATUS_OK
msg = ''
valid = True
self.open_db_connection()
try:
# Validate the submitted renewal token
status, msg, job_table_id, username = JOBSDB.validate_renewal_token(renewal_token)
if status != STATUS_OK or not isinstance(job_table_id, int):
valid = False
self.close_db_connection()
return status, msg, valid
# Record the job renewal
sql = '''
SELECT `job_id`, `renewals_used`, `renewals_left`, `expiration_date` FROM `job_renewal`
WHERE `renewal_token` = %s LIMIT 1
'''
self.cur.execute(sql, (renewal_token,))
results = self.cur.fetchall()
for (job_id, renewals_used, renewals_left, expiration_date) in results:
# If there are no more renewals available, return a failure message
if renewals_left < 1:
status = STATUS_ERROR
msg = 'No more renewals are allowed for this job.'
self.close_db_connection()
return status, msg, valid
# Update the job_renewal information by updating the number of used/left renewals and advancing the expiration date
sql = '''
UPDATE `job_renewal`
SET `renewals_used` = %s, `renewals_left` = %s, `renewal_token` = %s, `expiration_date` = %s, `email_sent` = %s
WHERE `job_id` = %s
'''
self.cur.execute(sql, (
renewals_used + 1,
renewals_left - 1,
generate_uuid() if renewals_left > 1 else None,
expiration_date + datetime.timedelta(0, job_ttl),
False,
job_table_id,
))
if self.cur.rowcount != 1:
status = STATUS_ERROR
msg = 'Error updating job renewal for job table row id "{}" in job_renewal database table'.format(job_table_id)
self.close_db_connection()
return status, msg, valid
except Exception as e:
status = STATUS_ERROR
msg = str(e).strip()
logger.error(msg)
self.close_db_connection()
return status, msg, valid
def validate_renewal_token(self, renewal_token):
status = STATUS_OK
msg = ''
job_table_id = None
username = None
self.open_db_connection()
try:
sql = '''
SELECT r.job_id as job_row_id, j.user as job_username FROM `job_renewal` r
LEFT JOIN `job` j
ON r.job_id = j.id
WHERE r.renewal_token = %s LIMIT 1
'''
self.cur.execute(sql, (renewal_token,))
for (job_row_id, job_username,) in self.cur:
job_table_id = job_row_id
username = job_username
if not job_table_id:
msg = 'Invalid job renewal token'
except Exception as e:
status = STATUS_ERROR
msg = str(e).strip()
logger.error(msg)
self.close_db_connection()
return status, msg, job_table_id, username
def prune_job_files(self, USER_DB_MANAGER, job_ttl, job_warning_period, current_time):
status = STATUS_OK
msg = ''
# logger.info('job_ttl: {}, job_warning_period: {}'.format(job_ttl, job_warning_period))
# Enforce a positive finite lifetime and warning period.
if job_ttl <= 0 or job_warning_period <= 0 or job_ttl - job_warning_period <= 0:
status = STATUS_ERROR
msg = 'Invalid job lifetime and/or warning period specified. Skipping job file pruning...'
return status, msg
self.open_db_connection()
try:
sql = '''
SELECT j.id as job_row_id, j.uuid as job_id, j.user as username, j.type as job_type, j.name as job_name, j.time_complete,
r.id as renewal_row_id, r.renewals_used, r.renewals_left, r.expiration_date, r.renewal_token, r.email_sent as email_sent
FROM `job` j
LEFT JOIN `job_renewal` r
ON j.id = r.job_id
WHERE j.deleted = 0 AND j.time_complete > 0
'''
self.cur.execute(sql)
completed_jobs = self.cur.fetchall()
expiring_job_messages = {}
for (job_row_id, job_id, username, job_type, job_name, time_complete, renewal_row_id, renewals_used, renewals_left, expiration_date, renewal_token, email_sent) in completed_jobs: