-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
2637 lines (2449 loc) · 97.9 KB
/
main.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 rpdb
import tornado.ioloop
import tornado.web
import tornado
import json
import yaml
import datetime
import logging
import kubejob
import dbutils
from jwtutils import authenticated
from jwtutils import encode_info
from jwtutils import validate_token
import envvars
import jobutils
import time
import os
import easyaccess as ea
import jira.client
import base64
from jinja2 import Template
import email_utils
import jlab
import ip
import uuid
import shutil
import re
from des_tasks.cutout.worker.bulkthumbs import validate_positions_table as validate_cutout_positions_table
import sys
STATUS_OK = 'ok'
STATUS_ERROR = 'error'
PASSWORD_REGEX = r'^[A-Za-z]+[A-Za-z0-9]{10,40}'
PASSWORD_VALIDITY_MESSAGE = "Password must be between 10 and 30 characters long and contain only characters A-Z, a-z, 0-9, '.', '?', '!', '-'"
ALLOWED_ROLE_LIST = envvars.ALLOWED_ROLE_LIST.split(',')
# Get global instance of the job handler database interface
JOBSDB = jobutils.JobsDb(
mysql_host=envvars.MYSQL_HOST,
mysql_user=envvars.MYSQL_USER,
mysql_password=envvars.MYSQL_PASSWORD,
mysql_database=envvars.MYSQL_DATABASE
)
# Configure logging
#
# Set logging format and basic config
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,
)
# Create a logging filter to protect user passwords and reduce clutter.
class TornadoLogFilter(logging.Filter):
def filter(self, record):
print(record.getMessage())
if record.getMessage().find('api/login') > -1 or \
record.getMessage().find('api/job/status') > -1 or \
record.getMessage().find('api/job/list') > -1 or \
record.getMessage().find('api/profile') > -1:
ret_val = 0
else:
ret_val = 1
return ret_val
logging.getLogger("tornado.access").addFilter(TornadoLogFilter())
# Define the logger for this module
logger = logging.getLogger("main")
logger.setLevel(logging.INFO)
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
# Initialize the Oracle database user manager and set email list address
if envvars.DESACCESS_INTERFACE == 'public':
USER_DB_MANAGER = dbutils.dbConfig(envvars.ORACLE_PUB_DBS)
EMAIL_LIST_ADDRESS = envvars.DESACCESS_PUBLIC_EMAILS
else:
USER_DB_MANAGER = dbutils.dbConfig(envvars.ORACLE_PRV_DBS)
EMAIL_LIST_ADDRESS = envvars.DESACCESS_PRIVATE_EMAILS
# The datetime type is not JSON serializable, so convert to string
def json_converter(o):
if isinstance(o, datetime.datetime):
return o.__str__()
# The @analytics decorator captures usage statistics
def analytics(cls_handler):
def wrap_execute(handler_execute):
def wrapper(handler, kwargs):
current_time = datetime.datetime.utcnow()
try:
request_path = handler.request.path
except:
request_path = ''
try:
user_agent = handler.request.headers["User-Agent"]
except:
user_agent = ''
try:
remote_ip = handler.request.remote_ip
except:
remote_ip = ''
try:
status, msg = JOBSDB.analytics_record_api(request_path, current_time, user_agent, remote_ip)
if status != STATUS_OK:
error_msg = msg
except Exception as e:
error_msg = str(e).strip()
logger.error(error_msg)
return
def _execute(self, transforms, *args, **kwargs):
wrapper(self, kwargs)
return handler_execute(self, transforms, *args, **kwargs)
return _execute
cls_handler._execute = wrap_execute(cls_handler._execute)
return cls_handler
def webcron_jupyter_prune(current_time=None):
status = STATUS_OK
msg = ''
try:
if not current_time:
current_time = datetime.datetime.utcnow()
# Get list of users in Jupyter role
jupyter_users = JOBSDB.get_role_user_list('jupyter')
pruned, msg = jlab.prune(jupyter_users, current_time)
logger.info('Pruned Jupyter servers for users: {}'.format(pruned))
except Exception as e:
status = STATUS_ERROR
msg = str(e).strip()
logger.error(msg)
return status, msg
def webcron_refresh_database_table_cache():
status = STATUS_OK
msg = ''
# Refresh the cache of DES database tables and their schemas
try:
status, msg = USER_DB_MANAGER.refresh_table_cache()
if status != STATUS_OK:
msg = 'webcron refresh_database_table_cache error: {}'.format(msg)
logger.error(msg)
else:
logger.info('Refreshed the cache of DES database tables and their schemas.')
except Exception as e:
status = STATUS_ERROR
msg = str(e).strip()
logger.error(msg)
return status, msg
def webcron_prune_job_files(job_ttl=envvars.DESACCESS_JOB_FILES_LIFETIME, job_warning_period=envvars.DESACCESS_JOB_FILES_WARNING_PERIOD, current_time=None):
status = STATUS_OK
msg = ''
# Delete job files older than the set lifetime. Send warning to users whose jobs are approaching their expiration.
try:
if not current_time:
current_time = datetime.datetime.utcnow()
status, msg = JOBSDB.prune_job_files(USER_DB_MANAGER, job_ttl, job_warning_period, current_time)
if status != STATUS_OK:
msg = 'webcron webcron_prune_job_files error: {}'.format(msg)
logger.error(msg)
else:
logger.info('Pruned job files.')
except Exception as e:
status = STATUS_ERROR
msg = str(e).strip()
logger.error(msg)
return status, msg
def webcron_sync_email_list():
status = STATUS_OK
msg = ''
# Sync the current list of public DESaccess users to the remote data source for the announcement email list
all_users = None
list_file = '/email_list/desaccess_email_list.txt'
temp_file = '{}.tmp'.format(list_file)
try:
# Fetch the current list of all users
all_users = USER_DB_MANAGER.list_all_users()
# Filter the user list to ensure valid information for email list data source file
email_data_source_list = []
for username, given_name, family_name, email in all_users:
if not given_name:
given_name = ''
if not family_name:
family_name = ''
# Simplistic check that the email address is valid
if isinstance(email, str) and email.find('@') > 0 and email.split('@')[1].find('.') > 0:
email_data_source_list.append([email, given_name, family_name])
else:
try:
logger.warning('User account omitted from email list data source file: username: {}, email: {}, given_name: {}, family_name: {}'.format(username, email, given_name, family_name))
except:
pass
# Sanity check to ensure that the the user list is probably valid
if len(email_data_source_list) > 10:
with open(temp_file, 'w') as listfile:
print('## Data for Sympa member import\n#\n#', file=listfile)
for email, given_name, family_name in email_data_source_list:
print('{} {} {}'.format(email, given_name, family_name), file=listfile)
else:
logger.warning('Email list data source file was not updated because the number of valid email addresses is only {}'.format(len(email_data_source_list)))
except Exception as e:
status = STATUS_ERROR
msg = str(e).strip()
logger.error(msg)
else:
if len(email_data_source_list) > 10:
shutil.copyfile(temp_file, list_file)
logger.info('Email list file "{}" updated.'.format(list_file))
os.remove(temp_file)
return status, msg
# The @webcron decorator executes cron jobs at intervals equal to or greater
# than the cron job's frequency spec. Cron jobs are manually registered in the
# JobHandler database like so
#
# INSERT INTO `cron` (`name`, `period`, `enabled`) VALUES ('my_cron_job_name', frequency_in_minutes, enabled_0_or_1)
#
def webcron(cls_handler):
def wrap_execute(handler_execute):
def run_cron(handler, kwargs):
# logger.info('Running webcron...')
cronjobs, error_msg = JOBSDB.cron_get_all()
if error_msg != '':
cronjobs = []
logger.error(error_msg)
try:
current_time = datetime.datetime.utcnow()
for cronjob in cronjobs:
try:
last_run_time = cronjob['last_run']
logger.debug('cronjob ({} min): {}'.format(cronjob['period'],cronjob['name']))
logger.debug('current time: {}'.format(current_time))
logger.debug('last run: {}'.format(last_run_time))
# Period is an integer in units of minutes
time_diff = current_time - last_run_time
time_diff_in_minutes = time_diff.total_seconds()/60
logger.debug('time diff (min): {}'.format(time_diff_in_minutes))
except:
last_run_time = False
if not last_run_time or time_diff_in_minutes >= cronjob['period']:
# Time to run the cron job again
logger.info('Running cron job "{}" at "{}".'.format(cronjob['name'], current_time))
if cronjob['name'] == 'jupyter_prune':
webcron_jupyter_prune(current_time)
elif cronjob['name'] == 'refresh_database_table_cache':
webcron_refresh_database_table_cache()
elif cronjob['name'] == 'prune_job_files':
webcron_prune_job_files()
elif cronjob['name'] == 'sync_email_list':
webcron_sync_email_list()
else:
logger.warning(f'Unsupported cronjob did not run: {cronjob}')
# Update the last_run time with the current time
JOBSDB.cron_update_run_time(cronjob['name'], current_time)
except Exception as e:
error_msg = str(e).strip()
logger.error(error_msg)
return
def _execute(self, transforms, *args, **kwargs):
run_cron(self, kwargs)
return handler_execute(self, transforms, *args, **kwargs)
return _execute
cls_handler._execute = wrap_execute(cls_handler._execute)
return cls_handler
# The @allowed_roles decorator must be accompanied by a preceding @authenticated decorator, allowing
# it to restrict access to the decorated function to authenticated users with specified roles.
def allowed_roles(roles_allowed = []):
# Always allow admin access
roles_allowed.append('admin')
# Actual decorator is check_roles
def check_roles(cls_handler):
def wrap_execute(handler_execute):
def wrapper(handler, kwargs):
response = {
"status": STATUS_OK,
"msg": ""
}
try:
roles = handler._token_decoded["roles"]
# logger.info('Authenticated user roles: {}'.format(roles))
if not any(role in roles for role in roles_allowed):
handler.set_status(200)
response["status"] = STATUS_ERROR
response["message"] = "Access denied."
handler.write(response)
handler.finish()
return
except:
handler.set_status(200)
response["status"] = STATUS_ERROR
response["message"] = "Error authorizing access."
logger.error(response["message"])
return
def _execute(self, transforms, *args, **kwargs):
wrapper(self, kwargs)
return handler_execute(self, transforms, *args, **kwargs)
return _execute
cls_handler._execute = wrap_execute(cls_handler._execute)
return cls_handler
return check_roles
class TileDataHandler(tornado.web.StaticFileHandler):
def initialize(self, **kwargs):
self.check_auth()
super(TileDataHandler, self).initialize(**kwargs)
def check_auth(self):
try:
params = {k: self.get_argument(k) for k in self.request.arguments}
response = validate_token(params['token'])
if response['status'] != STATUS_OK:
self._transforms = []
self.set_status(401)
self.finish()
return
except:
self._transforms = []
self.set_status(401)
self.finish()
return
# @webcron
class BaseHandler(tornado.web.RequestHandler):
def set_default_headers(self):
# By default the responses are JSON format. Individual GET responses that are text/html must
# declare the header in the relevant subclass
self.set_header("Content-Type", "application/json")
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
self.set_header("Access-Control-Allow-Methods",
" POST, PUT, DELETE, OPTIONS, GET")
def options(self):
self.set_status(204)
self.finish()
def get_username_parameter(self):
response = {
'status': STATUS_OK,
'message': ''
}
username = None
try:
# Authenticated username from auth token:
authn_username = self._token_decoded["username"].lower()
# Username provided as request parameter:
input_username = self.getarg('username', '').lower()
# If no username parameter is provided, default to the authenticated username
if input_username == '' or input_username == authn_username:
username = authn_username
# If the username parameter is not the authenticated user and the authenticated user is an admin, use the parameter value
elif 'admin' in self._token_decoded['roles']:
username = input_username
# If the username parameter is not the authenticated user and the authenticated user is not an admin, fail
else:
username = None
raise Exception('If username is provided it must match the authenticated user.')
except Exception as e:
response['status'] = STATUS_ERROR
response['message'] = str(e).strip()
# 400 Bad Request: The server could not understand the request due to invalid syntax.
# The assumption is that if a function uses `getarg()` to get a required parameter,
# then the request must be a bad request if this exception occurs.
self.set_status(400)
self.write(json.dumps(response))
self.finish()
raise e
return username
def getarg(self, arg, default=None):
response = {
'status': STATUS_OK,
'message': ''
}
value = default
try:
# If the request encodes arguments in JSON, parse the body accordingly
if 'Content-Type' in self.request.headers and self.request.headers['Content-Type'] in ['application/json', 'application/javascript']:
data = tornado.escape.json_decode(self.request.body)
if default == None:
# The argument is required and thus this will raise an exception if absent
value = data[arg]
else:
# Set the value to the default
value = default if arg not in data else data[arg]
# Otherwise assume the arguments are in the default content type
else:
# The argument is required and thus this will raise an exception if absent
if default == None:
value = self.get_argument(arg)
else:
value = self.get_argument(arg, default)
except Exception as e:
response['status'] = STATUS_ERROR
response['message'] = str(e).strip()
logger.error(response['message'])
# 400 Bad Request: The server could not understand the request due to invalid syntax.
# The assumption is that if a function uses `getarg()` to get a required parameter,
# then the request must be a bad request if this exception occurs.
self.set_status(400)
self.write(json.dumps(response))
self.finish()
raise e
return value
@authenticated
@allowed_roles(['admin'])
class TriggerWebcronHandler(BaseHandler):
def post(self):
response = {
'status': STATUS_OK,
'message': ''
}
try:
cronjob = self.getarg('cronjob')
if cronjob == 'jupyter_prune':
webcron_jupyter_prune()
elif cronjob == 'refresh_database_table_cache':
webcron_refresh_database_table_cache()
elif cronjob == 'prune_job_files':
webcron_prune_job_files()
elif cronjob == 'sync_email_list':
webcron_sync_email_list()
else:
response['msg'] = 'Specified cronjob is not valid.'
except Exception as e:
response['msg'] = str(e).strip()
logger.error(response['msg'])
response['status'] = STATUS_ERROR
self.write(response)
@authenticated
@allowed_roles(ALLOWED_ROLE_LIST)
class ProfileHandler(BaseHandler):
# API endpoint: /profile
def post(self):
response = {}
decoded = self._token_decoded
exptime = datetime.datetime.utcfromtimestamp(decoded['exp'])
ttl = (exptime - datetime.datetime.utcnow()).seconds
response["status"] = STATUS_OK
response["message"] = "valid token"
response["name"] = decoded["name"]
response["lastname"] = decoded["lastname"]
response["username"] = decoded["username"]
response["email"] = decoded["email"]
response["db"] = decoded["db"]
response["roles"] = decoded["roles"]
try:
prefs, error_msg = JOBSDB.get_user_preference('all', decoded["username"])
if error_msg != '':
logger.error(error_msg)
prefs = {}
except Exception as e:
error_msg = str(e).strip()
logger.error(error_msg)
prefs = {}
response["preferences"] = prefs
response["ttl"] = ttl
response["new_token"] = self._token_encoded
self.flush()
self.write(response)
self.finish()
return
@authenticated
@allowed_roles(['monitor'])
class UserStatisticsHandler(BaseHandler):
# API endpoint: /statistics/users
def get(self):
response = {}
try:
num_users = JOBSDB.get_statistics_session()
response['status'] = STATUS_OK
response['message'] = ''
response['results'] = num_users[0]
except Exception as e:
response['message'] = str(e).strip()
response['status'] = STATUS_ERROR
self.write(response)
@authenticated
@allowed_roles(['monitor'])
class EndpointStatisticsHandler(BaseHandler):
# API endpoint: /statistics/endpoints
def get(self):
response = {}
try:
endpts = JOBSDB.get_statistics_analytics()
response['status'] = STATUS_OK
response['message'] = ''
response['results'] = endpts[0]
except Exception as e:
response['message'] = str(e).strip()
response['status'] = STATUS_ERROR
self.write(response)
class StatusHandler(BaseHandler):
# API endpoint: /status
def get(self):
response = {}
try:
response['status'] = STATUS_OK
response['message'] = ''
except Exception as e:
response['message'] = str(e).strip()
response['status'] = STATUS_ERROR
self.set_status(500)
self.write(json.dumps(response))
self.finish()
return
self.write(response)
@authenticated
@allowed_roles(['monitor'])
class CutoutStatisticsHandler(BaseHandler):
# API endpoint: /statistics/cutout
def get(self):
response = {}
try:
cutout_file_size = JOBSDB.get_statistics_cutout()
response['status'] = STATUS_OK
response['message'] = ''
response['results'] = cutout_file_size[0]
except Exception as e:
response['message'] = str(e).strip()
response['status'] = STATUS_ERROR
self.write(response)
@authenticated
@allowed_roles(['monitor'])
class QueryStatisticsHandler(BaseHandler):
# API endpoint: /statistics/query
def get(self):
response = {}
try:
query_file_size = JOBSDB.get_statistics_query()
response['status'] = STATUS_OK
response['message'] = ''
response['results'] = query_file_size[0]
except Exception as e:
response['message'] = str(e).strip()
response['status'] = STATUS_ERROR
self.write(json.dumps(response))
@authenticated
@allowed_roles(['monitor'])
class IPStatisticsHandler(BaseHandler):
# API endpoint: /statistics/ips
def get(self):
response = {}
response['results'] = {}
for cluster in ['pub','prod']:
try:
ip_list = ip.query_pod_logs(cluster = cluster)
response['status'] = STATUS_OK
response['message'] = ''
response['results'][cluster] = ip_list
except Exception as e:
response['message'] = str(e).strip()
response['status'] = STATUS_ERROR
self.write(response)
@authenticated
@allowed_roles(ALLOWED_ROLE_LIST)
@analytics
class ProfileUpdateHandler(BaseHandler):
# API endpoint: /profile/update/info
def post(self):
response = {}
response["new_token"] = self._token_encoded
# Enforce lowercase usernames
try:
username = self.get_username_parameter()
first = self.getarg('firstname')
last = self.getarg('lastname')
email = self.getarg('email')
except:
return
try:
status, msg = USER_DB_MANAGER.update_info(username, first, last, email)
response['status'] = status
response['message'] = msg
except Exception as e:
response['message'] = str(e).strip()
response['status'] = STATUS_ERROR
self.write(response)
@authenticated
@allowed_roles(ALLOWED_ROLE_LIST)
@analytics
class ProfileUpdatePasswordHandler(BaseHandler):
# API endpoint: /profile/update/password
def post(self):
response = {}
try:
username = self.get_username_parameter()
oldpwd = self.getarg('oldpwd')
newpwd = self.getarg('newpwd')
database = self.getarg('db', self._token_decoded["db"])
except:
return
try:
status, message = USER_DB_MANAGER.change_credentials(username, oldpwd, newpwd, database)
response['status'] = status
response['message'] = message
except Exception as e:
response['message'] = str(e).strip()
response['status'] = STATUS_ERROR
self.write(response)
class LoginHandler(BaseHandler):
# API endpoint: /login
def post(self):
response = {
'status': STATUS_OK,
'message': ''
}
username = self.getarg('username', '')
email = self.getarg('email', '')
passwd = self.getarg('password')
db = self.getarg('database')
# At least one identifier must be provided
if username == '' and email == '':
response["status"] = STATUS_ERROR
response["message"] = 'Either username or email must be provided.'
self.set_status(400)
self.flush()
self.write(json.dumps(response))
self.finish()
return
# Support login using either username or email
auth, username, err, update = USER_DB_MANAGER.check_credentials(username, passwd, db, email)
if not auth:
if update:
self.set_status(406)
response["update"] = True
else:
self.set_status(401)
response["update"] = False
response["status"] = STATUS_ERROR
response["message"] = err
self.flush()
self.write(json.dumps(response))
self.finish()
return
try:
name, last, email = USER_DB_MANAGER.get_basic_info(username, db)
except Exception as e:
error_msg = str(e).strip()
logger.error(error_msg)
response["status"] = STATUS_ERROR
response["message"] = 'User not found.'
self.flush()
self.write(json.dumps(response))
self.finish()
return
roles = JOBSDB.get_user_roles(username)
encoded = encode_info(name, last, username, email, db, roles, envvars.JWT_TTL_SECONDS)
# Return user profile information, user preferences and auth token
response["message"] = "login"
response["username"] = username
response["name"] = name
response["lastname"] = last
response["email"] = email
response["db"] = db
response["roles"] = roles
response["token"] = encoded.decode(encoding='UTF-8')
try:
prefs, error_msg = JOBSDB.get_user_preference('all', username)
if error_msg != '':
logger.error(error_msg)
prefs = {}
except Exception as e:
error_msg = str(e).strip()
logger.error(error_msg)
prefs = {}
response["preferences"] = prefs
# Store encrypted password in database for subsequent job requests
ciphertext = jobutils.password_encrypt(passwd)
response["status"] = JOBSDB.session_login(username, response["token"], ciphertext)
self.write(json.dumps(response))
@authenticated
class LogoutHandler(BaseHandler):
# API endpoint: /logout
def post(self):
response = {
'status': STATUS_OK,
'message': ''
}
response["message"] = "logout {}".format(self._token_decoded["username"])
response["status"] = JOBSDB.session_logout(self._token_decoded["username"])
self.write(json.dumps(response))
@analytics
class JobRenewHandler(BaseHandler):
def get(self, token):
response = {
'status': STATUS_OK,
'message': '',
'valid': False
}
logger.info('Renewal request token: {} ({})'.format(token, self.request.path))
try:
status, msg, valid = JOBSDB.renew_job(token)
response["valid"] = valid
if status != STATUS_OK:
response["status"] = STATUS_ERROR
response["message"] = msg
self.write(json.dumps(response))
return
except Exception as e:
response["status"] = STATUS_ERROR
response["message"] = str(e).strip()
logger.error(response["status"])
self.write(json.dumps(response))
@authenticated
@allowed_roles(ALLOWED_ROLE_LIST)
@analytics
class JobHandler(BaseHandler):
def put(self):
'''
Required parameters:
- job
Optional parameters:
- username
- user_agent
- db
- email
'''
def add_request_params_if_supplied(in_array, params):
dummy_default = '6adc0ba0ae3b46b3919693a02a7190f16adc0ba0ae3b46b3919693a02a7190f18ed22249332e4ffd9dec9b675e865f23'
for param in params:
if param not in in_array:
val = self.getarg(param, dummy_default)
if val != dummy_default:
in_array[param] = val
return in_array
params = {}
# Applicable to all jobs
try:
params["user_agent"] = self.request.headers["User-Agent"]
except:
params["user_agent"] = ''
params['username'] = self.get_username_parameter()
# If the database is not specified in the request, assume the database to
# use is the one encoded in the authentication token
params['db'] = self.getarg('db', self._token_decoded["db"])
if 'db' not in params or not isinstance(params['db'], str) or len(params['db']) < 1:
params["db"] = self._token_decoded["db"]
# REQUIRED PARAMETER FOR ALL JOBS
job_type = self.request.path.split('/')[-1]
if job_type in ['query', 'cutout']:
params['job'] = job_type
else:
params['job'] = self.getarg('job')
# params['return_list'] = True
params = add_request_params_if_supplied(params,
[
'email',
'job_name',
'query',
'quick',
'check',
'compression',
'filename',
'positions',
'release',
'xsize',
'ysize',
'rgb_stiff_colors',
'rgb_lupton_colors',
'colors_fits',
'make_fits',
'make_rgb_lupton',
'make_rgb_stiff',
'rgb_minimum',
'rgb_stretch',
'rgb_asinh',
'discard_fits_files',
# synchronous option disabled in production
# 'synchronous',
]
)
# logger.info(json.dumps(params, indent=2))
# Reject jobs from users that have been blocked.
if any(role in self._token_decoded["roles"] for role in ['blocked']):
out = {
'status': STATUS_ERROR,
'message': 'This account has been blocked from submitting jobs. Contact DES help if you have questions.',
'jobid': '',
'new_token': self._token_encoded
}
self.write(json.dumps(out, indent=4))
return
# Enforce job request limits. Apply the cutout job limit to query jobs also.
if any(role in self._token_decoded["roles"] for role in ['admin', 'unlimited']):
LIMIT_CUTOUTS_CUTOUTS_PER_JOB = 0
LIMIT_CUTOUTS_CONCURRENT_JOBS = 0
else:
LIMIT_CUTOUTS_CUTOUTS_PER_JOB = envvars.LIMIT_CUTOUTS_CUTOUTS_PER_JOB
LIMIT_CUTOUTS_CONCURRENT_JOBS = envvars.LIMIT_CUTOUTS_CONCURRENT_JOBS
params['limits'] = {
'cutout': {
'concurrent_jobs': LIMIT_CUTOUTS_CONCURRENT_JOBS,
'cutouts_per_job': LIMIT_CUTOUTS_CUTOUTS_PER_JOB,
},
}
job_id = ''
try:
status, message, job_id = jobutils.submit_job(params)
except Exception as e:
status = STATUS_ERROR
message = str(e).strip()
logger.error(message)
out = {
'status': status,
'message': message,
'jobid': job_id,
'new_token': self._token_encoded
}
self.write(json.dumps(out, indent=4))
# API endpoint: /job/delete
def delete(self):
status = STATUS_OK
message = ''
username = self.get_username_parameter()
job_ids = []
# job-id is a required parameter. Use integer default value so that
# the refreshed token will be returned in the case of error
job_id = self.getarg('job-id', 0)
if isinstance(job_id, str):
job_ids.append(job_id)
elif isinstance(job_id, list):
job_ids = job_id
else:
status = STATUS_ERROR
message = 'job-id must be a single job ID value or an array of job IDs'
out = {
'status': status,
'message': message,
'new_token': self._token_encoded
}
self.write(json.dumps(out, indent=4))
for job_id in job_ids:
try:
# Determine the type of the job to delete
job_info_list, request_status, status_msg = JOBSDB.job_status(username, job_id)
if request_status == STATUS_ERROR:
status = STATUS_ERROR
message = status_msg
else:
job_type = job_info_list[0]['job_type']
except:
status = STATUS_ERROR
message = 'Invalid username or job ID specified.'
out = {
'status': status,
'message': message,
'new_token': self._token_encoded
}
self.write(json.dumps(out, indent=4))
if status == STATUS_OK:
# TODO: Allow specifying job-id "all" to delete all of user's jobs
conf = {}
conf["job_type"] = job_type
conf["namespace"] = jobutils.get_namespace()
conf["job_name"] = jobutils.get_job_name(job_type, job_id, username)
conf["job_id"] = job_id
conf["cm_name"] = jobutils.get_job_configmap_name(job_type, job_id, username)
try:
# Delete the k8s Job if it is still running
kubejob.delete_job(conf)
except:
pass
# Delete the job files on disk
status, message = JOBSDB.delete_job_files(job_id, username)
# Mark the job deleted in the JobHandler database
if status == STATUS_OK:
message = JOBSDB.mark_job_deleted(job_id)
if message != '':
status = STATUS_ERROR
else:
message = 'Job "{}" deleted.'.format(job_id)
out = {
'status': status,
'message': message,
'new_token': self._token_encoded
}
self.write(json.dumps(out, indent=4))
@authenticated
@allowed_roles(ALLOWED_ROLE_LIST)
class JobStatusHandler(BaseHandler):
# API endpoint: /job/status
def post(self):
username = self.get_username_parameter()
job_id = self.getarg("job-id")
job_info_list, status, message = JOBSDB.job_status(username, job_id)
out = {
'status': status,
'message': message,
'jobs': job_info_list,
'new_token': self._token_encoded
}
self.write(json.dumps(out, indent=4, default = json_converter))
# @authenticated
# @allowed_roles(ALLOWED_ROLE_LIST)
# class JobGetHandler(BaseHandler):
# # API endpoint: /job/[job_id]
# def get(self, job_id):
# username = self.get_username_parameter()
# job_info_list, status, message = JOBSDB.job_status(username, job_id)
# out = {
# 'status': status,
# 'message': message,
# 'jobs': job_info_list,
# 'new_token': self._token_encoded
# }
# self.write(json.dumps(out, indent=4, default = json_converter))
@authenticated
@allowed_roles(ALLOWED_ROLE_LIST)
class JobListHandler(BaseHandler):
# API endpoint: /job/list
def get(self):
username = self.get_username_parameter()
job_info_list, status, message = JOBSDB.job_list(username)
out = {
'status': status,
'message': message,
'jobs': job_info_list,
'new_token': self._token_encoded