forked from volodymyrss/dda-ddosa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ddosa.py
3746 lines (2808 loc) · 121 KB
/
ddosa.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
# check for logic in osa! make sure there is none!
# make cool plots
# reduce logs to essential; marker stream on topic
# output effect
# evaluate time, estimate time to do
# gzip files always
# simlink import
# avoid optional caches
# deep cacges
# asynch logs
#
# there are two ways to define common origin:
# define during class declaratopm
# dynamic redefinition of the classes, like ScWData, will invalidate (hopefully) the get call, so it should be reexecuted
# there is special treatement
# import as
# maks environment, osa, as input
# make aliases for evolutions
from dataanalysis.core import AnalysisException, DataFile
from dataanalysis.caches import cache_core
from dataanalysis import hashtools
from dataanalysis.hashtools import shhash
import dataanalysis.printhook
import dataanalysis.core as da
import io
import pilton
from pilton import heatool
import pprint
import os,shutil,re,time,glob
from os import access, R_OK
from os.path import isfile
from astropy.io import fits
from astropy import wcs
from astropy import wcs as pywcs
import subprocess,os
import ast
import copy
import json
import re
try:
import pandas as pd
except ImportError:
print("no pandas!")
try:
import yaml
except ImportError:
print("no yaml!")
import numpy as np
if hasattr(da,'DataAnalysisPrototype'):
DataAnalysisPrototype = da.DataAnalysisPrototype
else:
DataAnalysisPrototype = da.DataAnalysis
def remove_repeating(inlist):
if inlist==[]:
return inlist
outlist=[inlist[0]]
for l in inlist[1:]:
if l in outlist:
print("repearing item:",l)
else:
outlist.append(l)
return outlist
class MemCacheIntegralBase:
def get_scw(self,hashe):
if isinstance(hashe,tuple):
if hashe[0]=="analysis": # more universaly
if hashe[2].startswith('ScWData'):
if isinstance(hashe[1],tuple):
return hashe[1][-1]
else:
return hashe[1]
return self.get_scw(hashe[1])
if hashe[0]=="list": # more universaly
for k in hashe[1:]:
r=self.get_scw(k)
if r is not None:
return r
return None
raise Exception("unknown tuple in the hash:"+str(hashe))
if hashe is None:
return None #'Any'
if isinstance(hashe,str):
return None
raise Exception("unknown class in the hash:"+str(hashe))
def get_rev(self,hashe):
#if dataanalysis.printhook.global_log_enabled: print("search for rev in",hashe)
if isinstance(hashe,tuple):
if hashe[0]=="analysis": # more universaly
if hashe[2].startswith('Revolution'):
return hashe[1]
return self.get_rev(hashe[1])
if hashe[0]=="list": # more universaly
for k in hashe[1:]:
r=self.get_rev(k)
if r is not None:
return r
return None
raise Exception("unknown tuple in the hash:"+str(hashe))
if hashe is None:
return None
if isinstance(hashe,str):
return None
raise Exception("unknown class in the hash:"+str(hashe))
def get_marked(self,hashe):
#if dataanalysis.printhook.global_log_enabled: print("search for marked in",hashe)
if isinstance(hashe,tuple):
if hashe[0]=="analysis": # more universaly
r=[]
if hashe[2].endswith('..'):
r.append(hashe[2][:-2])
if '...' in hashe[2]:
r+=hashe[2].split('...')[1:]
r+=self.get_marked(hashe[1])
return r
if hashe[0]=="list": # more universaly
r=[]
for k in hashe[1:]:
r+=self.get_marked(k)
return r
raise Exception("unknown tuple in the hash:"+str(hashe))
if hashe is None:
return []
if isinstance(hashe,str):
return []
raise Exception("unknown class in the hash:"+str(hashe))
def hashe2signature(self,hashe):
scw=self.get_scw(hashe)
if scw is not None:
if isinstance(hashe,tuple):
if hashe[0]=="analysis":
return hashe[2]+":"+scw+":"+shhash(hashe)[:8]
return shhash(hashe)[:8]
rev=self.get_rev(hashe)
if rev is not None:
if isinstance(hashe,tuple):
if hashe[0]=="analysis":
return hashe[2]+":"+rev+":"+shhash(hashe)[:8]
return shhash(hashe)[:8]
return hashe[2]+":"+shhash(hashe)[:16]
def construct_cached_file_path(self,hashe,obj=None):
#print("will construct INTEGRAL cached file path for",hashe)
#hashe= hashtools.hashe_replace_object(hashe, None, "None")
scw=self.get_scw(hashe)
rev=self.get_rev(hashe)
def hash_to_path2(hashe):
return shhash(hashe[1])[:8]
marked=self.get_marked(hashe[1])
marked=remove_repeating(marked)
if dataanalysis.printhook.global_log_enabled: print("marked",marked)
for mark in marked:
hashe=hashtools.hashe_replace_object(hashe,mark+"..","any")
if not isinstance(scw,str):
scw=None
if scw=="Any":
scw=None
if scw is None:
if dataanalysis.printhook.global_log_enabled: print("not scw-grouped cache")
if rev is None:
if dataanalysis.printhook.global_log_enabled: print("not rev-grouped cache")
r=self.filecacheroot+"/global/"+hashe[2]+"/"+"/".join(marked)+"/"+hash_to_path2(hashe)+"/"
else:
hashe=hashtools.hashe_replace_object(hashe,rev,"any")
#print("reduced hashe",hashe)
if dataanalysis.printhook.global_log_enabled: print("cached rev:",rev)
r=self.filecacheroot+"/byrev/"+rev+"/"+hashe[2]+"/"+"/".join(marked)+"/"+hash_to_path2(hashe)+"/" # choose to avoid overlapp
else:
hashe=hashtools.hashe_replace_object(hashe,scw,"any")
hashe=hashtools.hashe_replace_object(hashe,('analysis', scw[:4], 'Revolution.v0'),('analysis', 'any', 'Revolution.v0'))
#str("reduced hashe:",hashe,hash_to_path2(hashe))
#if dataanalysis.printhook.global_log_enabled: print("reduced hashe:",hashe,hash_to_path2(hashe))
#open("reduced_hashe.txt","w").write(hash_to_path2(hashe)+"\n\n"+pprint.pformat(hashe)+"\n")
print(scw,hashe[2],marked)
r=self.filecacheroot+"/byscw/"+scw[:4]+"/"+scw+"/"+hashe[2]+"/"+"/".join(marked)+"/"+hash_to_path2(hashe)+"/" # choose to avoid overlapp
print(self,"cached path:",r)
return r # choose to avoid overlapp
import dqueue
import base64
import bravado
def localized_DataFile(f):
if isinstance(f, DataFile):
fn = f.get_path()
else:
fn = f
# this removes gz and postixes set for uniqueness by dda
a, b = os.path.basename(fn).split('.fits')
lfn = a + ".fits"
if lfn != fn:
fits.open(fn).writeto(lfn, overwrite=True)
print("\033[35mlocalizing DataFile:", fn, lfn, "\033[0m")
return DataFile(lfn)
if os.environ.get("DDA_DISABLE_ASYNC", "no") == "yes" or os.environ.get("ODA_DISABLE_DATALAKE", "no") == "yes":
class ODACache(dataanalysis.caches.cache_core.CacheBlob):
def __repr__(self):
return "[" + self.__class__.__name__ + "DISABLED]"
def approved_hashe(self, hashe):
return False
def find(self, hashe):
return None
def deposit_blob(self, hashe, blob):
pass
def retrieve_blob(self, hashe):
return None
else:
class ODACache(dataanalysis.caches.cache_core.CacheBlob):
_leader = None
def __repr__(self):
return f"[{self.__class__.__name__}: leader {self.leader}]"
@property
def leader(self):
if self._leader is None:
self._leader = dqueue.from_uri(os.environ.get("ODAHUB"))
return self._leader
def approved_hashe(self, hashe):
if os.environ.get('DDOSA_RESTRICT_ODA_CACHE', 'no') == 'yes':
if hashe[-1].split(".")[0] in [
'mosaic_ii_skyimage',
'ISGRISpectraSum',
'ISGRILCSum',
'spe_pick',
'ReportScWList',
]:
return True
else:
if hashe[-1].split(".")[0] in [
'ibis_gti', 'ibis_dead', 'CatExtract',
'BinMapsImage', 'BinEventsImage', 'ghost_bustersImage', 'ii_skyimage',
'mosaic_ii_skyimage',
'ii_spectra_extract', 'ISGRISpectrumPack',
'BinMapsSpectra', 'BinEventsSpectra', 'ghost_bustersSpectra', 'ii_spectra_extract', 'ISGRISpectraSum',
'BinMapsLC', 'ii_lc_extract', 'ISGRILCSum',
'ii_light',
'jemx_image', 'jemx_spe', 'jemx_lcr',
'spe_pick',
'ReportScWList',
'ISGRIImagePack',
# 'RebinResponse',
]:
return True
def find(self, hashe):
print("\033[33mchecking if exists in ODA\033[0m")
if os.environ.get('DDA_DEBUG_HASHE', 'no') == 'yes':
print("\033[35m", pprint.pformat(hashe), "\033[0m")
while True:
try:
r = self.leader.consult_fact(
dag=hashe,
return_data=False
)
print("\033[34mYES exists in ODA\033[0m")
break
except dqueue.data.NotFound as e:
print("\033[32mnot found in ODA\033[0m", e)
return None
except bravado.exception.HTTPBadGateway as e:
print("\033[31mproblem with gateway!\033[0m", e)
time.sleep(1)
continue
except Exception as e:
print("\033[31munknown problem, maybe with gateway!\033[0m", e)
time.sleep(1)
continue
print("\033[33mfound in ODA\033[0m", r)
return r
def deposit_blob(self, hashe, blob):
blob_b64 = base64.b64encode(blob.read()).decode()
r = self.leader.assert_fact(
dag=hashe,
data={ "blob": blob_b64 }
)
r = None
print("deposited blob in ODA:",r)
def retrieve_blob(self, hashe):
print("\033[33mtrying to restore from ODA\033[0m")
while True:
try:
r = self.leader.consult_fact(
dag=hashe,
)
break
except dqueue.data.NotFound as e:
print("\033[32mnot found in ODA\033[0m", e)
return None
except bravado.exception.HTTPBadGateway as e:
print("\033[31mproblem with gateway!\033[0m", e)
time.sleep(1)
continue
blob = base64.b64decode(json.loads(r['data_json'])['blob'])
print("\033[33mrestored from ODA\033[0m: blob of", len(blob)/1024/1024, "kb")
return io.BytesIO(blob)
class MemCacheIntegralFallback(MemCacheIntegralBase,dataanalysis.caches.cache_core.CacheNoIndex):
def store(self, hashe, obj):
return dataanalysis.caches.cache_core.CacheNoIndex.store(self,hashe,obj)
def restore(self, hashe, obj, restore_config=None):
return dataanalysis.caches.cache_core.CacheNoIndex.restore(self, hashe, obj, restore_config)
class LocalCacheNoParent(dataanalysis.caches.cache_core.CacheNoIndex):
def restore_from_parent(self, *x, **xx):
print("\033[31m", self, "disabled parent entirely\033[0m")
return None
class IntegralODAFallback(MemCacheIntegralFallback):
def __init__(self, *a, **aa):
self._odacache = ODACache()
MemCacheIntegralFallback.__init__(self, *a, **aa)
def store_local(self, hashe, obj):
return LocalCacheNoParent.store(self, hashe, obj)
def find(self, hashe):
print("\033[33mchecking if exists in ODA\033[0m")
if self._odacache.find(hashe):
return True
print("\033[33mchecking if exists in ", self, "\033[0m")
return MemCacheIntegralFallback.find(self, hashe)
def store(self, hashe, obj):
r = self.store_local(hashe, obj)
print("storing to ODACache")
self._odacache.store(hashe, obj)
print("after odacache store:", obj.factory.factory_assumptions_stacked)
return r
def restore(self, hashe, obj, restore_config=None):
parent = self.parent
self.parent = None
local_result = LocalCacheNoParent.restore(
self,
hashe,
obj,
restore_config,
)
print(obj, "\033[032mLocalCacheNoParent returns", local_result, "\033[0m")
self.parent = parent
oda_exists = self._odacache.find(hashe)
print(obj, "\033[032m_odacache.find returns", oda_exists, "\033[0m")
if local_result:
print(obj, "\033[032mrestored from local cache, ensuring it is stored to ODACache\033[0m")
obj._da_locally_complete = None
obj._da_restored = None
if oda_exists:
print(obj, "\033[032malready exists in ODA as well as in local cache, nothing to do\033[0m")
else:
print(obj, "\033[031mreconstructing object with local cache references\033[0m")
local_result = LocalCacheNoParent.restore(self, hashe, obj,
{**restore_config,
'copy_cached_input': True,
'datafile_restore_mode': 'copy'},
)
print(obj, "\033[031does not exist in ODA, uploading!\033[0m")
#TODO: this seems to fail if cache is restored incomplete!
try:
self._odacache.store(hashe, obj)
except Exception as e:
print(obj, "\033[031failed storing locally cached to ODA!\033[0m")
raise
else:
print(obj, "\033[031mtrying to restore from ODA cache\033[0m")
oda_result = None
if oda_exists:
oda_result = self._odacache.restore(hashe, obj,
{**restore_config,
'copy_cached_input': True,
'datafile_restore_mode': 'copy'})
if not oda_result:
print("\033[31mcan not restore from ODA, but was supposed to exist!\033[0m")
oda_result = None
if oda_result is not None:
print(obj, "\033[031mrestored from ODACache, now storing to local cache\033[0m")
# we should rather learn to upload to new cache from non-copied cache files, but it's dda change
self.store_local(hashe, obj)
obj._da_locally_complete = None
obj._da_restored = None
print(obj, "\033[031mreconstructing object with local cache references\033[0m")
local_result = LocalCacheNoParent.restore(self, hashe, obj, restore_config)
else:
print(obj, "\033[036m", hashe, "\033[0m")
print(obj, f"\033[031mno result in either cache, will follow with parent", self.parent, "compute\033[0m")
return self.restore_from_parent(hashe, obj, restore_config)
return local_result
#class MemCacheIntegralFallbackOldPath(MemCacheIntegralBaseOldPath,dataanalysis.caches.core.CacheNoIndex):
#readonly_cache=True
#class MemCacheIntegralIRODS(MemCacheIntegralBase,dataanalysis.MemCacheIRODS):
# pass
#mc=dataanalysis.TransientCacheInstance
#mcg=MemCacheIntegral('/Integral/data/reduced/ddcache/')
#mc=mcg
#mc.parent=mcg
#mcgl=MemCacheIntegralLegacy('/Integral/data/reduced/ddcache/')
#mcg.parent=mcgl
IntegralCacheRoots=os.environ.get('INTEGRAL_DDCACHE_ROOT','/data/reduced/ddcache/')
CacheStack=[]
#CacheStack.append(ODACache())
for IntegralCacheRoot in IntegralCacheRoots.split(":"):
ro_flag=False
if IntegralCacheRoot.startswith("ro="):
ro_flag=True
IntegralCacheRoot=IntegralCacheRoot.replace("ro=","")
mcgfb = IntegralODAFallback(IntegralCacheRoot)
#mcgfb=MemCacheIntegralFallback(IntegralCacheRoot)
mcgfb.readonly_cache=ro_flag
if CacheStack==[]:
CacheStack=[mcgfb]
else:
CacheStack[-1].parent=mcgfb
CacheStack.append(mcgfb)
#mcgfb_oldp=MemCacheIntegralFallbackOldPath(IntegralCacheRoot)
#mcgfb_oldp.readonly_cache=ro_flag
#mcgfb.parent=mcgfb_oldp
#CacheStack.append(mcgfb_oldp)
#mcgirods=MemCacheIntegralIRODS('/tempZone/home/integral/data/reduced/ddcache/')
#CacheStack[-1].parent=mcgirods
#CacheStack.append(mcgirods)
mc=CacheStack[0]
print("cache stack:",CacheStack)
class OSA_tool_kit_class(object):
tool_versions=None
def get_tool_version(self,name):
if self.tool_versions is None:
self.tool_versions={}
if name not in self.tool_versions:
cl=subprocess.Popen([name,"--version"],stdout=subprocess.PIPE)
self.tool_versions[name]=cl.stdout.read().strip().split()[-1]
return self.tool_versions[name]
OSA_tool_kit=OSA_tool_kit_class()
def get_OSA_tools(names=None):
if names is None:
return da.NoAnalysis
if isinstance(names,str) or isinstance(names,tuple):
names=[names]
names=[ name if isinstance(name,tuple) else (name,None)
for name in names ]
class OSA_tools(DataAnalysisPrototype):
osa_tools=names[:]
def get_version(self):
v=self.get_signature()+"."+self.version
for osa_tool,default_version in self.osa_tools:
current_version=OSA_tool_kit.get_tool_version(osa_tool)
if default_version is None or current_version!=default_version:
v+="."+osa_tool+"_"+current_version
return v
return OSA_tools
class HaveExpiredAnalysisExceptions(Exception):
pass
class DataAnalysis(DataAnalysisPrototype):
cache=mc
write_caches=[cache_core.TransientCache, MemCacheIntegralFallback, IntegralODAFallback, ODACache]
read_caches=[cache_core.TransientCache, MemCacheIntegralFallback, IntegralODAFallback, ODACache]
#write_caches=[cache_core.TransientCache,MemCacheIntegralFallback]
#read_caches=[cache_core.TransientCache,MemCacheIntegralFallback]
input_osatools=get_OSA_tools()
cached=False
def get_scw(self):
if self._da_locally_complete is not None:
try:
return "(completescw:%s)"%self.cache.get_scw(getattr(self,'_da_locally_complete',None))
except:
return "(complete)"
for a in self.assumptions:
if isinstance(a,ScWData):
return "(assumescw:%s)"%str(a.input_scwid)
return ""
def __repr__(self):
return "[%s%s%s%s%i]"%(self.get_version(),self.get_scw(),";Virtual" if self.virtual else "",";Complete" if self._da_locally_complete else "",id(self))
@property
def is_still_worth_recomputing(self):
involved_scws = []
for a in self.assumptions:
print("\n\033[33mhave assumption", a, "\033[0m\n")
if isinstance(a,ScWData):
involved_scws.append(str(a.input_scwid))
scw = self.cache.get_scw(getattr(self,'_da_locally_complete',None))
if scw is not None:
involved_scws.append(scw)
print("\n\033[32mall involved scws:", involved_scws, "\033[0m\n")
for scw in involved_scws:
if int(scw).endswith(".000"):
return True
#if int(scw.strip("[]")[:4]) > 2500:
# return True
if len(involved_scws) == 0:
return True
else:
return False
def post_restore(self):
# TODO: product expiration globally?
# TODO: delicate state process, compare exception creation to index state
exceptions = self.get_exceptions()
if len(exceptions) > 0:
da.log(da.render("{RED}DDOSA found stored exceptions{/} in"), repr(self), " requested by "+(" ".join(self._da_requested_by)), level='top')
else:
da.log(da.render("{RED}DDOSA found {GREEN}NO stored exceptions{/} in"), repr(self), " requested by "+(" ".join(self._da_requested_by)), level='top')
have_expired_exceptions = False
for exception in exceptions:
print(da.render("{RED}stored exception{/}: {BLUE}" + exception[0] + " {/}"))
print(da.render(" : {CYAN}" + repr(type(exception[1])) + ": " + repr(exception[1]) + " {/}"))
print(da.render("{CYAN}" + repr(type(exception[1])) + ": " + repr(exception[1]) + " {/}"))
try:
if 'scw data not found and not allowed to download' in str(exception) or \
'no revdir available! tried:' in str(exception) or \
'NoValidScW' in str(exception):
if self.is_still_worth_recomputing:
have_expired_exceptions = True
da.log(da.render("{RED}detected stored exception EXPIRED!{/}"), level='top')
except Exception as e:
raise Exception(f"unexpected: {e} in {exception}")
if have_expired_exceptions:
da.log(da.render("{RED}stored exceptions EXPIRED!{/}"), level='top')
raise HaveExpiredAnalysisExceptions()
da.log(da.render("{RED}DDOSA {GREEN}post-restore finished smoothly{/}"), repr(self), " requested by "+(" ".join(self._da_requested_by)), level='top')
def retrieve_cache(self, fih, rc=None):
try:
return super().retrieve_cache(fih, rc)
except HaveExpiredAnalysisExceptions:
da.log(da.render("{RED}stored exceptions EXPIRED!{/}"), level='top')
self.analysis_exceptions = []
return False
class NoScWData(da.AnalysisException):
@property
def expired(self):
return False
class ERR_ISGR_OSM_DATA_INCONSISTENCY(da.AnalysisException):
pass
class NoDeadData(da.AnalysisException):
pass
class NoISGRIEvents(da.AnalysisException):
pass
class NoRevDir(da.AnalysisException):
pass
class EmptyScWList(da.AnalysisException):
pass
class NoValidScW(da.AnalysisException):
pass
class EmptyImageList(da.AnalysisException):
pass
class ScWDataCorrupted(da.AnalysisException):
pass
class FractionalEnergyBinsNotAllowed(da.AnalysisException):
pass
class EfficiencyNotComputed(da.AnalysisException):
pass
class PossiblyWrongEnergyRange(da.AnalysisException):
pass
class BinnedMapsNotComputed(Exception):
pass
class IncompatibleIISpectraExtract(Exception):
pass
def good_file(fn):
return os.path.exists(fn) and isfile(fn) and access(fn, R_OK)
class INTEGRALArchive(DataAnalysis):
run_for_hashe=True
# archive_version="cons/rev_3"
def main(self):
return INTEGRALArchiveRev3()
class INTEGRALArchiveRev3(da.NoAnalysis):
pass
class ScWData(DataAnalysis):
input_scwid=None
cached=False # how do we implement that this can change?
schema_hidden=True
version="v1"
scwver="001"
auxadpver="001"
def main(self):
try:
self.scwid = self.input_scwid.handle
except:
self.scwid = self.input_scwid
self.scwver = self.scwid[-3:]
self.revid = self.scwid[:4]
print(f"extracted scwver {self.scwver} revid {self.revid}")
if not self.find():
print("ScW not found")
print("\033[31mScWData not found\033[0m")
# TODO: put proper limit!
if int(self.revid) > 400:
print(f"\033[31mthis ScW ID is to recent to be considered a permanent refernece in rev_3 index!\033[0m")
# return ScWDataVolatile(input_scwid=self.scwid)
if os.environ.get("DDOSA_SCWDATA_DOWNLOAD", "no") == "yes":
print("\033[31mScWData download allowed\033[0m")
self.download()
if self.find():
print("\033[32mScWData found after download!\033[0m")
return
else:
print("\033[31mScWData NOT found after download!\033[0m")
raise da.AnalysisException("scw data download failed somehow")
else:
print("\033[31mScWData download forbidden! set DDOSA_SCWDATA_DOWNLOAD=yes to allow\033[0m")
raise da.AnalysisException("scw data not found and not allowed to download, set DDOSA_SCWDATA_DOWNLOAD=yes to allow")
# raise NoScWData("scw data not found and not allowed to download, set DDOSA_SCWDATA_DOWNLOAD=yes to allow")
def download(self):
print("\033[31mScW not found\033[0m")
subprocess.check_call(["download_data.sh", self.revid, self.scwid[:12]])
def find(self):
try:
print(f"searching in {detect_rbp(self.scwver)} for scwver {self.scwver}")
self.assume_rbp(detect_rbp(self.scwver))
return True
except da.AnalysisException as e:
print("exception searching for scw data:", e)
# return False
if self.scwver == "000":
print("searching for nrt in "+detect_rbp(self.scwver)+"/nrt")
self.assume_rbp(detect_rbp(self.scwver)+"/nrt")
return True
else:
return False
except Exception as e:
print("\033[31mScWData find failed\033[0m", e)
return False
def test_scw(self):
try:
f=fits.open(self.scwpath+"/swg.fits")
print("valid file:",f)
except IOError as e:
print(f"\033[31m{self}.test_scw FAILED: {e} {e.__class__} {e.args}\033[0m")
message = getattr(e, 'message', None)
if message == None:
if len(e.args) > 0:
message = e.args[0]
if message == "Header missing END card.":
raise ScWDataCorrupted(self.scwpath, message)
else:
raise
def test_isgri_events(self):
print("checking for readable events...")
options=[self.scwpath+"/isgri_events.fits"]
options.append(options[-1]+".gz")
for option in options:
if good_file(option):
print("ok:",option)
return
raise NoISGRIEvents("no usable event data for: "+repr(self.scwid))
def assume_rbp(self,rbp):
print("will try to assume RBP:", rbp)
self.revdirver = None
tried = []
for v in self.scwver, "002", "001", "000":
p = rbp+"/scw/"+self.revid+"/rev." + v
if os.path.exists(p):
self.revdirver = v
print("found revdir ver", v)
break
tried.append(p)
if self.revdirver is None:
# raise Exception("no revdir available! tried: {}".format(tried))
raise NoRevDir("no revdir available! tried: {}".format(tried))
self.scwpath=rbp+"/scw/"+self.revid+"/"+self.scwid
self.revdirpath=rbp+"/scw/"+self.revid+"/rev."+self.revdirver
#self.auxadppath=rbp+"/aux/adp/"+self.revid+"."+self.auxadpver
print("searching for auxadpver")
for ver in "000", "001":
self.auxadppath=rbp+"/aux/adp/"+self.revid+"."+ver
self.auxadpver=ver
if os.path.exists(self.auxadppath):
print("auxadpver picked", self.auxadpver, self.auxadppath)
break
if not good_file(self.scwpath+"/swg.fits"):
if not good_file(self.scwpath+"/swg.fits.gz"):
print("failed searching for",self.scwpath+"/swg.fits")
raise NoScWData("no scw data for: "+repr(self.scwid))
#raise Exception("no scw data!")
else:
self.swgpath=self.scwpath+"/swg.fits.gz"
else:
self.swgpath=self.scwpath+"/swg.fits"
print("swgpath:",self.swgpath)
def get_isgri_events(self):
if hasattr(self,'isgrievents'):
return self.isgrievents.get_path()
return self.scwpath+"/isgri_events.fits.gz"
def get_telapse(self):
return fits.open(self.swgpath)[1].header['TELAPSE']
def get_t(self):
h=fits.open(self.swgpath)[1].header
return (h['TSTOP']+h['TSTART'])/2.,(h['TSTOP']-h['TSTART'])/2.
def get_t1_t2(self):
h=fits.open(self.swgpath)[1].header
return h['TSTART'],h['TSTOP']
def __repr__(self):
return "[%s:%s]"%(self.__class__.__name__,self.input_scwid)
def detect_rbp(scwver="001"):
rbp = os.environ["REP_BASE_PROD"]
if scwver=="001":
if "REP_BASE_PROD_CONS" in os.environ:
rbp = os.environ["REP_BASE_PROD_CONS"]
if scwver=="000":
if "REP_BASE_PROD_NRT" in os.environ:
rbp = os.environ["REP_BASE_PROD_NRT"]
return rbp
class ScWVersion(DataAnalysis):
scwver="000"
def get_version(self):
return DataAnalysis.get_version(self)+".ver"+self.scwver
class Revolution(DataAnalysis):
input_revid=None
input_scwver=da.NoAnalysis
scwver="001"
auxadpver="001"
def get_revid(self):
return self.input_revid.handle
def main(self):
if not isinstance(self.input_scwver,da.NoAnalysis) and not self.input_scwver == da.NoAnalysis:
self.scwver=self.input_scwver.scwver
rbp=detect_rbp(scwver=self.scwver)
self.revroot=rbp+"/scw/%s/"%self.get_revid()
self.revdir=self.revroot+"/rev.%s/"%self.scwver
self.auxadppath=rbp+"/aux/adp/"+self.get_revid()+"."+self.auxadpver
def get_ijd(self):
r1100=4306.5559396296
r100=1315.4808007407
r=int(self.get_revid())
return r100+(r1100-r100)/1000*(r-100)
def get_ijd_exact(self):
ijd_b = list(map(float, converttime("REVNUM",self.get_revid(),"IJD")))
return (ijd_b[1] + ijd_b[0]) / 2., (ijd_b[1] - ijd_b[0])
def __repr__(self):
return "[Revolution:%s:%s]"%(self.input_revid,self.scwver)
class RevForScW(DataAnalysis):
input_scw=ScWData
run_for_hashe=True
allow_alias=False
def __repr__(self):
return "[RevForScW:for %s]"%repr(self.input_scw)
def main(self):
revid=self.input_scw.input_scwid.handle[:4]
scwver=self.input_scw.input_scwid.handle[-3:]
print("revolution id for scw:",revid)
return Revolution(input_revid=revid,use_scwver=scwver)
#return Revolution(input_revid=revid,use_scwver=scwver)
class Rev4ScW(Revolution):
input_scw=ScWData
input_revid=da.NoAnalysis
def __repr__(self):
return "[Rev4ScW:for %s]"%repr(self.input_scw)
def get_revid(self):
revid=self.input_scw.input_scwid.handle[:4]
print("revolution id for scw:",revid)
return revid
class ICRoot(DataAnalysis):
cached=False
schema_hidden=True
version="v1"
ic_root_version="default-isdc"
def get_version(self):
return self.get_signature() + "." + self.version + "." + self.ic_root_version
def main(self):
# find ic tree for given version
ic_collection = os.environ.get('IC_COLLECTION', None)
if ic_collection:
icpath = os.path.join(ic_collection, self.ic_root_version)
self.icroot = icpath
if os.path.exists(icpath):
print("found IC as requested:", icpath)
# TODO ensure versions is good
# TODO understand how this reflects on versions of individual files
else:
raise RuntimeError(f"IC {self.ic_root_version} not found in IC_COLLECTION as {icpath}")
else:
if self.ic_root_version == "default-isdc":
default_ic = os.environ.get('CURRENT_IC', None)
if default_ic:
self.icroot = default_ic
else:
raise RuntimeError("no CURRENT_IC, or IC_COLLECTION")