-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdispatcher_query.py
2532 lines (2100 loc) · 117 KB
/
dispatcher_query.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
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed May 10 10:55:20 2017
@author: andrea tramcere
"""
import os
import pathlib
import time
from builtins import (open, str, range,
object)
import traceback
from collections import Counter, OrderedDict
import copy
# import logging
# from werkzeug.utils import secure_filename
import glob
import string
import random
import fcntl
from flask import jsonify, send_from_directory, make_response
from flask import request, g
import time as time_
import tempfile
import tarfile
import gzip
import socket
import logstash
import shutil
import jwt
import re
import logging
import json
import typing
from ..plugins import importer
from ..analysis.queries import SourceQuery
from ..analysis import tokenHelper, email_helper, matrix_helper
from ..analysis.instrument import params_not_to_be_included
from ..analysis.hash import make_hash
from ..analysis.hash import default_kw_black_list
from ..analysis.job_manager import job_factory
from ..analysis.io_helper import FilePath, format_size
from .mock_data_server import mock_query
from ..analysis.products import QueryOutput
from ..configurer import DataServerConf
from ..analysis.exceptions import BadRequest, APIerror, MissingRequestParameter, RequestNotUnderstood, RequestNotAuthorized, ProblemDecodingStoredQueryOut, InternalError
from . import tasks
from ..flask_app.sentry import sentry
from oda_api.api import DispatcherAPI
from .logstash import logstash_message
from oda_api.data_products import NumpyDataProduct
import oda_api
from cdci_data_analysis.timer import block_timer
logger = logging.getLogger(__name__)
class NoInstrumentSpecified(BadRequest):
pass
class InstrumentNotRecognized(BadRequest):
pass
class InvalidJobIDProvided(BadRequest):
pass
class InstrumentQueryBackEnd:
def __repr__(self):
return f"[ {self.__class__.__name__} : {self.instrument_name} ]"
@property
def instrument_name(self):
return getattr(self, '_instrument_name', 'instrument-not-set')
@instrument_name.setter
def instrument_name(self, instrument_name):
self._instrument_name = instrument_name
@property
def query_progression(self):
if not hasattr(self, '_query_progression'):
self._query_progression = []
return self._query_progression
def log_query_progression(self, message):
self.query_progression.append(dict(
t_s = time_.time(),
message = message,
))
t0 = self.query_progression[0]['t_s']
self.logger.warning("%s %s s", message, self.query_progression[-1]['t_s'] - t0)
def __init__(self, app,
instrument_name=None,
par_dic=None,
config=None,
data_server_call_back=False,
verbose=False,
get_meta_data=False,
download_products=False,
download_files=False,
resolve_job_url=False,
query_id=None,
update_token=False):
self.logger = logging.getLogger(f"{repr(self)} [{query_id}]")
self.logger = logging.getLogger(repr(self))
if verbose:
self.logger.setLevel(logging.DEBUG)
else:
self.logger.setLevel(logging.INFO)
self.request_files_dir = self.get_request_files_dir()
params_not_to_be_included.clear()
params_not_to_be_included.append('user_catalog')
self.app = app
temp_scratch_dir = None
temp_job_id = None
self.set_sentry_sdk(getattr(self.app.config.get('conf'), 'sentry_url', None))
try:
if par_dic is None:
self.set_args(request, verbose=verbose, download_files=download_files, download_products=download_products)
else:
self.par_dic = par_dic
self.log_query_progression("after set args")
self.log_query_progression("before set_session_id")
self.set_session_id()
self.log_query_progression("after set_session_id")
if data_server_call_back or resolve_job_url:
# in the case of call_back or resolve_job_url the job_id can be extracted from the received par_dic
self.job_id = None
if 'job_id' in self.par_dic:
self.job_id = self.par_dic['job_id']
else:
sentry.capture_message("job_id not present during a call_back")
raise RequestNotUnderstood("job_id must be present during a call_back")
if data_server_call_back:
# this can be set since it's a call_back and job_id and session_id are available
self.logger.info(f"before setting scratch_dir: job_id: {self.par_dic['job_id']} callback: {data_server_call_back}, resolve_job_url: {resolve_job_url}")
self.set_scratch_dir(session_id=self.par_dic['session_id'], job_id=self.par_dic['job_id'])
self.set_session_logger(self.scratch_dir, verbose=verbose, config=config)
self.logger.info(f"scratch_dir set {self.scratch_dir}, job_id: {self.par_dic['job_id']} callback: {data_server_call_back}, resolve_job_url: {resolve_job_url}")
self.set_scws_call_back_related_params()
self.logger.info(f"set_scws_call_back_related_params executed")
else:
self.set_scws_related_params(request)
self.client_name = self.par_dic.pop('client-name', 'unknown')
self.return_progress = self.par_dic.pop('return_progress', False) == 'True'
if os.environ.get("DISPATCHER_ASYNC_ENABLED", "no") == "yes": # TODO: move to config!
self.async_dispatcher = self.par_dic.pop(
'async_dispatcher', 'True') == 'True' # why string true?? else false anyway
else:
self.async_dispatcher = False
"""
async dispatcher operation avoids building QueryOutput in the sync request, and instead sends it in the queue
in the queue, the same request is repeated, same session id/job id, but requesting sync request
this immitates two repeated identical requests from the same client, which takes care of aliasing/etc complexity
the remaining complexity is to send back a response which indicates "submitted" but not submitted job - only request
"""
self.time_request = g.get('request_start_time', None)
# By default, a request is public, let's now check if a token has been included
# In that case, validation is needed
self.public = True
self.token = None
email=None
roles=None
self.decoded_token = None
if 'token' in self.par_dic.keys() and self.par_dic['token'] not in ["", "None", None]:
self.token = self.par_dic['token']
self.public = False
# token validation and decoding can be done here, to check if the token is expired
self.log_query_progression("before validate_query_from_token")
try:
if self.validate_query_from_token():
roles = tokenHelper.get_token_roles(self.decoded_token)
email = tokenHelper.get_token_user_email_address(self.decoded_token)
except jwt.exceptions.ExpiredSignatureError as e:
logstash_message(app, {'origin': 'dispatcher-run-analysis', 'event': 'token-expired'})
message = ("The token provided is expired, please try to logout and login again. "
"If already logged out, please clean the cookies, "
"and resubmit you request.")
if data_server_call_back:
message = "The token provided is expired, please resubmit you request with a valid token."
self.logger.info(message)
sentry.capture_message(message)
raise RequestNotAuthorized(message)
except jwt.exceptions.InvalidSignatureError as e:
logstash_message(app, {'origin': 'dispatcher-run-analysis', 'event': 'not-valid-token'})
message = ("The token provided is not valid, please try to logout and login again. "
"If already logged out, please clean the cookies, "
"and resubmit you request.")
if data_server_call_back:
message = "The token provided is expired, please resubmit you request with a valid token."
self.logger.info(message)
sentry.capture_message(message)
raise RequestNotAuthorized(message)
self.log_query_progression("after validate_query_from_token")
logstash_message(app, {'origin': 'dispatcher-run-analysis', 'event':'token-accepted', 'decoded-token':self.decoded_token })
self.log_query_progression("after logstash_message")
if download_products or resolve_job_url or update_token or download_files:
instrument_name = 'mock'
self.logger.info("before setting instrument, self.par_dic: %s", self.par_dic)
if instrument_name is None:
if 'instrument' in self.par_dic:
self.instrument_name = self.par_dic['instrument']
else:
self.logger.error("NoInstrumentSpecified, self.par_dic: %s", self.par_dic)
raise NoInstrumentSpecified(
f"have parameters: {list(self.par_dic.keys())} ")
else:
self.instrument_name = instrument_name
if get_meta_data:
self.logger.info("get_meta_data request: no scratch_dir")
self.set_instrument(self.instrument_name, roles, email)
# TODO
# decide if it is worth to add the logger also in this case
#self.set_scratch_dir(self.par_dic['session_id'], verbose=verbose)
#self.set_session_logger(self.scratch_dir, verbose=verbose, config=config)
# self.set_sentry_client()
else:
logger.debug("NOT get_meta_data request: yes scratch_dir")
# TODO why here and not at the beginning ?
# self.set_sentry_client()
# TODO is also the case of call_back to handle ?
if not data_server_call_back:
self.set_instrument(self.instrument_name, roles, email)
# TODO: if not callback!
# if 'query_status' not in self.par_dic:
# raise MissingRequestParameter('no query_status!')
verbose = self.par_dic.get('verbose', 'False') == 'True'
if not (data_server_call_back or resolve_job_url or download_files):
query_status = self.par_dic['query_status']
self.job_id = None
if query_status == 'new':
# let's generate a temporary job_id used for the creation of the scratch_dir
self.generate_job_id()
else:
if 'job_id' not in self.par_dic:
raise RequestNotUnderstood(
f"job_id must be present if query_status != \"new\" (it is \"{query_status}\")")
self.job_id = self.par_dic['job_id']
if not download_files:
# let's generate a temporary scratch_dir using the temporary job_id
self.set_scratch_dir(self.par_dic['session_id'], job_id=self.job_id, verbose=verbose)
# temp_job_id = self.job_id
temp_scratch_dir = self.scratch_dir
temp_job_id = self.job_id
if not data_server_call_back:
try:
self.set_temp_dir(self.par_dic['session_id'], verbose=verbose)
except Exception as e:
sentry.capture_message(f"problem creating temp directory: {e}")
raise InternalError("we have encountered an internal error! "
"Our team is notified and is working on it. We are sorry! "
"When we find a solution we will try to reach you", status_code=500)
if self.instrument is not None and not isinstance(self.instrument, str):
products_url = self.app.config.get('conf').products_url
bind_host = self.app.config.get('conf').bind_host
bind_port = self.app.config.get('conf').bind_port
self.instrument.parse_inputs_files(
par_dic=self.par_dic,
request=request,
temp_dir=self.temp_dir,
verbose=verbose,
use_scws=self.use_scws,
upload_dir=self.request_files_dir,
products_url=products_url,
bind_host=bind_host,
bind_port=bind_port,
request_files_dir=self.request_files_dir,
decoded_token=self.decoded_token,
sentry_dsn=self.sentry_dsn
)
self.par_dic = self.instrument.set_pars_from_dic(self.par_dic, verbose=verbose)
# self.update_ownership_files(uploaded_files_obj)
# update the job_id
if not (data_server_call_back or resolve_job_url or download_files):
query_status = self.par_dic['query_status']
self.job_id = None
if query_status == 'new':
provided_job_id = self.par_dic.get('job_id', None)
if provided_job_id == "": # frontend sends this
provided_job_id = None
# let's generate the definitive job_id
self.generate_job_id()
if provided_job_id is not None and self.job_id != provided_job_id:
raise RequestNotUnderstood((
f"during query_status == \"new\", provided (unnecessarily) job_id {provided_job_id} "
f"did not match self.job_id {self.job_id} computed from request"
))
else:
if 'job_id' not in self.par_dic:
raise RequestNotUnderstood(
f"job_id must be present if query_status != \"new\" (it is \"{query_status}\")")
self.job_id = self.par_dic['job_id']
elif download_files:
self.job_id = None
if not download_files:
# let's set the scratch_dir with the updated job_id
self.set_scratch_dir(self.par_dic['session_id'], job_id=self.job_id, verbose=verbose)
self.log_query_progression("before move_temp_content")
self.move_temp_content()
self.log_query_progression("after move_temp_content")
self.set_session_logger(self.scratch_dir, verbose=verbose, config=config)
self.config = config
self.logger.info(f'==> found par dict {self.par_dic.keys()}')
except APIerror:
raise
except Exception as e:
self.logger.error('\033[31mexception in constructor of %s %s\033[0m', self, repr(e))
self.logger.error("traceback: %s", traceback.format_exc())
raise RequestNotUnderstood(f"{self} constructor failed: {e}")
finally:
self.logger.info("==> clean-up temporary directory")
self.log_query_progression("before clear_temp_dir")
self.clear_temp_dir(temp_scratch_dir=temp_scratch_dir, temp_job_id=temp_job_id)
self.log_query_progression("after clear_temp_dir")
logger.info("constructed %s:%s for data_server_call_back=%s", self.__class__, self, data_server_call_back)
@staticmethod
def free_up_space(app):
token = request.args.get('token', None)
app_config = app.config.get('conf')
secret_key = app_config.secret_key
output, output_code = tokenHelper.validate_token_from_request(token=token, secret_key=secret_key,
required_roles=['space manager'],
action="free_up space on the server")
if output_code is not None:
return make_response(output, output_code)
current_time_secs = time.time()
hard_minimum_folder_age_days = app_config.hard_minimum_folder_age_days
# let's pass the minimum age the folders to be deleted should have
soft_minimum_folder_age_days = request.args.get('soft_minimum_age_days', None)
if soft_minimum_folder_age_days is None:
soft_minimum_folder_age_days = app_config.soft_minimum_folder_age_days
else:
soft_minimum_folder_age_days = int(soft_minimum_folder_age_days)
list_scratch_dir = sorted(glob.glob("scratch_sid_*_jid_*"), key=os.path.getmtime)
list_scratch_dir_to_delete = []
for scratch_dir in list_scratch_dir:
scratch_dir_age_days = (current_time_secs - os.path.getmtime(scratch_dir)) / (60 * 60 * 24)
if scratch_dir_age_days >= hard_minimum_folder_age_days:
list_scratch_dir_to_delete.append(scratch_dir)
elif scratch_dir_age_days >= soft_minimum_folder_age_days:
analysis_parameters_path = os.path.join(scratch_dir, 'analysis_parameters.json')
with open(analysis_parameters_path) as analysis_parameters_file:
dict_analysis_parameters = json.load(analysis_parameters_file)
token = dict_analysis_parameters.get('token', None)
token_expired = False
if token is not None:
try:
tokenHelper.get_decoded_token(token, secret_key)
except jwt.exceptions.ExpiredSignatureError:
token_expired = True
job_monitor_path = os.path.join(scratch_dir, 'job_monitor.json')
with open(job_monitor_path, 'r') as jm_file:
monitor = json.load(jm_file)
job_status = monitor['status']
job_id = monitor['job_id']
if job_status == 'done' and (token is None or token_expired):
list_scratch_dir_to_delete.append(scratch_dir)
else:
incomplete_job_alert_message = f"The job {job_id} is yet to complete despite being older "\
f"than {soft_minimum_folder_age_days} days. This has been detected "\
f"while checking for deletion the folder {scratch_dir}."
logger.info(incomplete_job_alert_message)
sentry.capture_message(incomplete_job_alert_message)
else:
break
pre_clean_space_stats = shutil.disk_usage(os.getcwd())
pre_clean_available_space = format_size(pre_clean_space_stats.free, format_returned='M')
logger.info(f"Number of scratch folder before clean-up: {len(list_scratch_dir)}.\n"
f"The available amount of space is {pre_clean_available_space}")
for d in list_scratch_dir_to_delete:
shutil.rmtree(d)
list_lock_files = sorted(glob.glob(".lock_*"), key=os.path.getatime)
num_lock_files_removed = 0
for l in list_lock_files:
lock_file_job_id = l.split('_')[-1]
list_job_id_scratch_dir = glob.glob(f"scratch_sid_*_jid_{lock_file_job_id}*")
if len(list_job_id_scratch_dir) == 0:
os.remove(l)
num_lock_files_removed += 1
post_clean_space_space = shutil.disk_usage(os.getcwd())
post_clean_available_space = format_size(post_clean_space_space.free, format_returned='M')
list_scratch_dir = sorted(glob.glob("scratch_sid_*_jid_*"))
list_lock_files = sorted(glob.glob(".lock_*"))
logger.info(f"Number of scratch folder after clean-up: {len(list_scratch_dir)}, "
f"number of lock files after clean-up: {len(list_lock_files)}.\n"
f"Removed {len(list_scratch_dir_to_delete)} scratch directories "
f"and {num_lock_files_removed} lock files.\n"
f"Now the available amount of space is {post_clean_available_space}")
result_scratch_dir_deletion = f"Removed {len(list_scratch_dir_to_delete)} scratch directories, " \
f"and {num_lock_files_removed} lock files."
logger.info(result_scratch_dir_deletion)
return jsonify(dict(output_status=result_scratch_dir_deletion))
@staticmethod
def get_user_specific_instrument_list(app):
token = request.args.get('token', None)
roles = []
email = None
if token is not None:
app_config = app.config.get('conf')
secret_key = app_config.secret_key
output, output_code = tokenHelper.validate_token_from_request(token=token, secret_key=secret_key,
action="getting the list of instrument")
if output_code is not None:
return make_response(output, output_code)
else:
decoded_token = tokenHelper.get_decoded_token(token, secret_key)
roles = tokenHelper.get_token_roles(decoded_token)
email = tokenHelper.get_token_user_email_address(decoded_token)
with block_timer(logger=logger,
message_template="Instrument factory iteration took {:.1f} seconds"):
out_instrument_list = []
for instrument_factory in importer.instrument_factory_iter:
if hasattr(instrument_factory, 'instrument_query'):
instrument_query = instrument_factory.instrument_query
if hasattr(instrument_factory, 'instr_name'):
instr_name = instrument_factory.instr_name
else:
instr_name = instrument_factory().name
else:
instrument = instrument_factory()
instrument_query = instrument.instrumet_query
instr_name = instrument.name
if instrument_query.check_instrument_access(roles, email):
out_instrument_list.append(instr_name)
return jsonify(out_instrument_list)
@staticmethod
def inspect_state():
recent_days = request.args.get('recent_days', 3, type=float)
job_id = request.args.get('job_id', None)
include_session_log = request.args.get('include_session_log', False) == 'True'
include_status_query_output = request.args.get('include_status_query_output', False) == 'True'
exclude_analysis_parameters = request.args.get('exclude_analysis_parameters', False) == 'True'
group_by_job = request.args.get('group_by_job', False) == 'True'
records_content = []
for scratch_dir in glob.glob("scratch_sid_*_jid_*"):
r = re.match(
r"scratch_sid_(?P<session_id>[A-Z0-9]{16})_jid_(?P<job_id>[a-z0-9]{16})(?P<aliased_marker>_aliased|)",
scratch_dir)
if r is not None:
if job_id is not None:
if r.group('job_id')[:8] != job_id:
continue
scratch_dir_job_id = r.group('job_id')
if os.path.exists(scratch_dir):
if (time_.time() - os.stat(scratch_dir).st_mtime) < recent_days * 24 * 3600:
if group_by_job:
result_job_status = InstrumentQueryBackEnd.read_job_status_scratch_dir(scratch_dir,
include_session_log=include_session_log,
include_status_query_output=include_status_query_output,
exclude_analysis_parameters=exclude_analysis_parameters
)
job_status_search_result = [(index, job_status_obj)
for index, job_status_obj in enumerate(records_content) if
job_status_obj.get('job_id') == scratch_dir_job_id]
if len(job_status_search_result) > 0:
records_content[job_status_search_result[0][0]]['job_status_data'].append(dict(**result_job_status))
else:
records_content.append(dict(
job_id=scratch_dir_job_id,
job_status_data=[dict(**result_job_status)]
)
)
else:
result_content, request_completed, token_expired = InstrumentQueryBackEnd.read_content_scratch_dir(scratch_dir,
include_session_log=include_session_log,
include_status_query_output=include_status_query_output,
exclude_analysis_parameters=exclude_analysis_parameters)
record = dict(
mtime=os.stat(scratch_dir).st_mtime,
ctime=os.stat(scratch_dir).st_ctime,
session_id=r.group('session_id'),
job_id=scratch_dir_job_id,
request_completed=request_completed,
aliased_marker=r.group('aliased_marker'),
**result_content
)
if token_expired is not None:
record['token_expired'] = token_expired
records_content.append(record)
else:
logger.warning(f"scratch_dir {scratch_dir} not existing, cannot be inspected")
logger.info("found %s records", len(records_content))
return dict(records=records_content)
@staticmethod
def read_analysis_parameters_scratch_dir(scratch_dir, decode_token=False):
analysis_parameters_obj = None
reading_output_message = ""
fn = os.path.join(scratch_dir, 'analysis_parameters.json')
try:
with open(fn) as analysis_parameters_file:
analysis_parameters_obj = json.load(analysis_parameters_file)
except Exception as e:
logger.warning('unable to read: %s', fn)
reading_output_message = f'problem reading {fn}: {repr(e)}'
if analysis_parameters_obj is not None and decode_token and 'token' in analysis_parameters_obj:
analysis_parameters_obj['token'] = tokenHelper.get_decoded_token(analysis_parameters_obj['token'], secret_key=None, validate_token=False)
return analysis_parameters_obj, reading_output_message
@staticmethod
def read_job_status_scratch_dir(scratch_dir, include_session_log=False, include_status_query_output=False, exclude_analysis_parameters=True):
result_job_status = dict(
request_completed = False,
scratch_dir_fn = scratch_dir,
scratch_dir_content = None
)
result_job_status['scratch_dir_content'], result_job_status['request_completed'], token_expired = (
InstrumentQueryBackEnd.read_content_scratch_dir(scratch_dir,
include_session_log=include_session_log,
include_status_query_output=include_status_query_output,
exclude_analysis_parameters=exclude_analysis_parameters))
if token_expired is not None:
result_job_status['token_expired'] = token_expired
return result_job_status
@staticmethod
def read_content_scratch_dir(scratch_dir, include_session_log=False, include_status_query_output=False, exclude_analysis_parameters=True):
result_content = {}
file_list = []
for f in glob.glob(os.path.join(scratch_dir, "*")):
file_list.append(f)
result_content['file_list'] = file_list
request_completed = False
token_expired = None
if not exclude_analysis_parameters:
result_content['analysis_parameters'], reading_output_message = InstrumentQueryBackEnd.read_analysis_parameters_scratch_dir(scratch_dir,
decode_token=True)
if result_content['analysis_parameters'] is None:
result_content['analysis_parameters'] = reading_output_message
else:
if 'token' in result_content['analysis_parameters']:
token_expired = result_content['analysis_parameters']['token']['exp'] < time_.time()
if include_session_log:
result_content['session_log'] = ''
session_log_fn = os.path.join(scratch_dir, 'session.log')
if os.path.exists(session_log_fn):
with open(session_log_fn) as session_log_fn_f:
result_content['session_log'] = session_log_fn_f.read()
result_content['email_history'] = []
for email in glob.glob(os.path.join(scratch_dir, 'email_history/*')):
ctime = os.stat(email).st_ctime,
result_content['email_history'].append(dict(
ctime=ctime,
ctime_isot=time_.strftime("%Y-%m-%dT%H:%M:%S", time_.gmtime(os.stat(email).st_ctime)),
fn=email,
))
result_content['matrix_message_history'] = []
for msg in glob.glob(os.path.join(scratch_dir, 'matrix_message_history/*')):
ctime = os.stat(msg).st_ctime,
result_content['matrix_message_history'].append(dict(
ctime=ctime,
ctime_isot=time_.strftime("%Y-%m-%dT%H:%M:%S", time_.gmtime(os.stat(msg).st_ctime)),
fn=msg,
))
result_content['fits_files'] = []
for fits_fn in glob.glob(os.path.join(scratch_dir, '*fits*')):
ctime = os.stat(fits_fn).st_ctime
result_content['fits_files'].append(dict(
ctime=ctime,
ctime_isot=time_.strftime("%Y-%m-%dT%H:%M:%S", time_.gmtime(ctime)),
fn=fits_fn,
))
if include_status_query_output:
result_content['status_query_output'] = ''
query_output_fn = os.path.join(scratch_dir, 'query_output.json')
try:
with open(query_output_fn) as query_output_file:
query_output_content = json.load(query_output_file)
query_output_status_dict = query_output_content.get('status_dictionary', None)
if query_output_status_dict is not None:
result_content['status_query_output'] = query_output_status_dict
except Exception as e:
logger.warning('unable to read: %s', query_output_fn)
result_content['status_query_output'] = f'problem reading {query_output_fn}: {repr(e)}'
result_content['job_monitor'] = []
for fn in glob.glob(os.path.join(scratch_dir, 'job_monitor*')):
with open(fn) as job_status_file:
job_monitor_content = json.load(job_status_file)
job_monitor_ctime = os.stat(fn).st_ctime
job_monitor_status = job_monitor_content['status']
request_completed = (request_completed or job_monitor_status == 'done')
result_content['job_monitor'].append(dict(
ctime=job_monitor_ctime,
ctime_isot=time_.strftime("%Y-%m-%dT%H:%M:%S", time_.gmtime(job_monitor_ctime)),
fn=fn,
job_monitor_content=job_monitor_content
))
return result_content, request_completed, token_expired
@staticmethod
def restricted_par_dic(par_dic, kw_black_list=None):
"""
restricts parameter list to those relevant for request content
"""
if kw_black_list is None:
kw_black_list = default_kw_black_list
return OrderedDict({
k: v for k, v in par_dic.items()
if k not in kw_black_list and v is not None
})
def user_specific_par_dic(self, par_dic):
if par_dic.get('token') is not None:
secret_key = self.app.config.get('conf').secret_key
decoded_token = tokenHelper.get_decoded_token(par_dic['token'], secret_key)
return {
**par_dic,
"sub": tokenHelper.get_token_user_email_address(decoded_token)
}
else:
return par_dic
def calculate_job_id(self,
par_dic: dict,
kw_black_list: typing.Union[None,dict]=None) -> str:
"""
restricts parameter list to those relevant for request content, and makes string hash
"""
user_par_dict = self.user_specific_par_dic(par_dic)
user_restricted_par_dict = self.restricted_par_dic(user_par_dict, kw_black_list)
return make_hash(user_restricted_par_dict)
def generate_job_id(self, kw_black_list=None):
self.logger.info("\033[31m---> GENERATING JOB ID <---\033[0m")
self.logger.info(
"\033[31m---> new job id for %s <---\033[0m", self.par_dic)
try:
self.logger.debug("generate_job_id: %s", json.dumps(self.par_dic, indent=4, sort_keys=True))
except Exception as e:
self.logger.error("unable to jsonify this self.par_dic = %s", self.par_dic)
raise
self.job_id = self.calculate_job_id(self.par_dic, kw_black_list)
self.logger.info(
'\033[31mgenerated NEW job_id %s \033[0m', self.job_id)
def set_session_id(self):
self.logger.info("---> SET_SESSION_ID <---")
if 'session_id' not in self.par_dic.keys():
self.par_dic['session_id'] = None
self.logger.info('passed SESSION ID: %s', self.par_dic['session_id'])
if self.par_dic['session_id'] is None or self.par_dic['session_id'] == 'new':
self.logger.info('generating SESSION ID: %s',
self.par_dic['session_id'])
self.par_dic['session_id'] = u''.join(random.choice(
string.ascii_uppercase + string.digits) for _ in range(16))
self.logger.info('setting SESSION ID: %s', self.par_dic['session_id'])
def set_session_logger(self, scratch_dir, verbose=False, config=None):
logger = logging.getLogger(__name__)
if verbose:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
session_log_filename = os.path.join(scratch_dir, 'session.log')
have_handler = False
for handler in logger.handlers:
if isinstance(handler, logging.FileHandler) and handler.baseFilename:
handler_path = pathlib.Path(handler.baseFilename)
if handler_path.parent.stem == scratch_dir:
logger.info("found correspondent FileHandler: %s : %s",
handler, handler.baseFilename)
have_handler = True
else:
logger.info("found not correspondent FileHandler: %s : %s, assigning a new one",
handler, handler.baseFilename)
logger.removeHandler(handler)
#handler.baseFilename == session_log_filename
if not have_handler:
fileh = logging.FileHandler(session_log_filename, 'a')
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fileh.setFormatter(formatter)
logger.addHandler(fileh) # set the new handler
if verbose:
print('logfile set to dir=', scratch_dir,
' with name=', session_log_filename)
# if config is not None:
# logger=self.set_logstash(logger,logstash_host=config.logstash_host,logstash_port=config.logstash_port)
self.logger = logger
def set_logstash(self, logger, logstash_host=None, logstash_port=None):
_logger = logger
if logstash_host is not None:
logger.addHandler(logstash.TCPLogstashHandler(
logstash_host, logstash_port))
extra = {
'origin': 'cdci_dispatcher',
}
_logger = logging.LoggerAdapter(logger, extra)
else:
pass
return _logger
def set_sentry_sdk(self, sentry_dsn=None):
if sentry_dsn is not None:
if sentry.sentry_url != sentry_dsn:
raise NotImplementedError
self.sentry_dsn = sentry.sentry_url
def get_current_ip(self):
return socket.gethostbyname(socket.gethostname())
def set_scws_related_params(self, request):
# it is nowhere necessary within the dispatcher-app,
# but it is re-attached to the url within the email
# when sending it since it is used by the frontend
self.use_scws = self.par_dic.pop('use_scws', None)
#
if 'scw_list' in self.par_dic.keys():
if self.use_scws == 'no' or self.use_scws == 'user_file':
raise RequestNotUnderstood("scw_list parameter was found "
"despite use_scws was indicating this was not provided, "
"please check the inputs")
_p = request.values.getlist('scw_list')
if len(_p) > 1:
self.par_dic['scw_list'] = _p
# it could be a comma-separated string, so let's convert to a list
elif len(_p) == 1:
_p_space_separated = _p[0].split()
if len(_p_space_separated) > 1:
raise RequestNotUnderstood('a space separated science windows list is an unsupported format, '
'please provide it as a comme separated list')
_p = str(_p)[1:-1].replace('\'','').split(",")
if len(_p) > 1:
# TODO to be extended also to cases with one element,
# so to be consistent with how it is handled when passed with a file,
# EDIT: after a quick check, only a test adaptation is needed, though net very crucial
self.par_dic['scw_list'] = _p
# use_scws should be set for, if any, url link within the email
if self.use_scws is None:
self.use_scws = 'form_list'
print('=======> scw_list', self.par_dic['scw_list'], _p, len(_p))
else:
# not necessary to check the case of scw_list passed via file,
# since it is verified at a later stage
if self.use_scws is not None and self.use_scws == 'form_list':
raise RequestNotUnderstood("scw_list parameter was expected to be passed, "
"but it has not been found, "
"please check the inputs")
if self.use_scws is None or self.use_scws == 'no':
# to prevent the scw_list to be added to the par_dict
# TODO: to be improved!
params_not_to_be_included.append('scw_list')
def set_scws_call_back_related_params(self):
# get the original params dict from the json file within the folder
original_request_par_dic = self.get_request_par_dic()
if original_request_par_dic is not None:
self.use_scws = original_request_par_dic.get('use_scws', None)
if 'scw_list' in original_request_par_dic.keys():
if self.use_scws is None:
self.use_scws = 'form_list'
def set_args(self, request, verbose=False, download_products=False, download_files=False):
supported_methods = ['GET', 'POST']
if download_files or download_products:
supported_methods.append('HEAD')
if request.method in supported_methods:
args = request.values
else:
raise NotImplementedError
self.par_dic = {}
for k, v in args.to_dict().items():
if k in ['catalog_selected_objects', 'selected_catalog']:
self.par_dic[k] = v
continue
if v == '\x00':
self.par_dic[k] = None
continue
try:
decoded = json.loads(v)
if isinstance(decoded, (dict, list)):
self.par_dic[k] = decoded
else:
self.par_dic[k] = v
except json.JSONDecodeError:
self.par_dic[k] = v
if verbose:
print('par_dic', self.par_dic)
self.args = args
def get_request_files_dir(self):
request_files_dir = FilePath(file_dir='request_files')
request_files_dir.mkdir()
return request_files_dir.path
def set_scratch_dir(self, session_id, job_id=None, verbose=False):
lock_file = f".lock_{self.job_id}"
scratch_dir_retry_attempts = 6
scratch_dir_retry_delay = 0.2
scratch_dir_created = True
if verbose:
print('SETSCRATCH ---->', session_id, type(session_id), job_id, type(job_id))
wd = 'scratch'
if session_id is not None:
wd += '_sid_' + session_id
if job_id is not None:
wd += '_jid_'+job_id
for attempt in range(scratch_dir_retry_attempts):
try:
with open(lock_file, 'w') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
alias_workdir = self.get_existing_job_ID_path(wd=FilePath(file_dir=wd).path)
if alias_workdir is not None:
wd = wd + '_aliased'
wd_path_obj = FilePath(file_dir=wd)
wd_path_obj.mkdir()
self.scratch_dir = wd_path_obj.path
scratch_dir_created = True
break
except (OSError, IOError) as io_e:
scratch_dir_created = False
self.logger.warning(f'Failed to acquire lock for the scratch directory "{wd}" creation, attempt number {attempt + 1} ({scratch_dir_retry_attempts - (attempt + 1)} left), sleeping {scratch_dir_retry_delay} seconds until retry.\nError: {str(io_e)}')
time.sleep(scratch_dir_retry_delay)
scratch_dir_retry_delay *= 2
if not scratch_dir_created:
dir_list = glob.glob(f"*_jid_{job_id}*")
sentry.capture_message(f"Failed to acquire lock for \"{wd}\" directory creation after multiple attempts.\njob_id: {self.job_id}\ndir_list: {dir_list}")
raise InternalError(f"Failed to acquire lock for directory \"{wd}\" creation after {scratch_dir_retry_attempts} attempts.", status_code=500)
def set_temp_dir(self, session_id, job_id=None, verbose=False):
if verbose:
print('SETTEMP ---->', session_id,
type(session_id), job_id, type(job_id))
suffix = ""
if session_id is not None:
suffix += '_sid_' + session_id
if job_id is not None:
suffix += '_jid_'+job_id
temp_parent_dir = '.'
if hasattr(self, 'scratch_dir'):
temp_parent_dir = self.scratch_dir
td = tempfile.mkdtemp(suffix=suffix, dir=temp_parent_dir)
self.temp_dir = td
def move_temp_content(self):
if hasattr(self, 'temp_dir') and os.path.exists(self.temp_dir) \
and os.path.exists(self.scratch_dir):
for f in os.listdir(self.temp_dir):
file_full_path = os.path.join(self.temp_dir, f)
shutil.copy(file_full_path, self.scratch_dir)
def clear_temp_dir(self, temp_scratch_dir=None, temp_job_id=None):
if hasattr(self, 'temp_dir') and os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
if temp_scratch_dir is not None and temp_scratch_dir != self.scratch_dir and os.path.exists(temp_scratch_dir):
shutil.rmtree(temp_scratch_dir)
if temp_job_id is not None and os.path.exists(f".lock_{temp_job_id}"):
os.remove(f".lock_{temp_job_id}")
@staticmethod
def validated_download_file_path(basepath, filename, should_exist=True):
# basic arg validation
if "../" in filename or filename.startswith(os.sep):
raise RequestNotAuthorized('No such file')
# still explicitly check if the file is in the dir
base_abs = os.path.realpath(basepath)
file_abs = os.path.realpath(os.path.join(basepath, filename))
if (os.path.commonpath([base_abs]) != os.path.commonpath([base_abs, file_abs])
or (should_exist and not os.path.isfile(file_abs)) ):
raise RequestNotAuthorized('No such file')
return file_abs
def verify_access_to_file(self, file_name):