This repository was archived by the owner on Sep 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathcheckor.py
More file actions
executable file
·1717 lines (1491 loc) · 84.9 KB
/
checkor.py
File metadata and controls
executable file
·1717 lines (1491 loc) · 84.9 KB
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 python
from assignSession import *
from utils import getWorkflows, workflowInfo, getDatasetEventsAndLumis, getDatasetEventsPerLumi, siteInfo, campaignInfo, \
getWorkflowById, forceComplete, getDatasetSize, sendLog, reqmgr_url, dbs_url, dbs_url_writer, display_time, \
checkMemory, ThreadHandler, wtcInfo
from utils import componentInfo, unifiedConfiguration, userLock, moduleLock, dataCache, unified_url, \
getDatasetLumisAndFiles, getDatasetRuns, duplicateAnalyzer, invalidateFiles, findParent, do_html_in_each_module, \
getDatasetFileArray
import dbs3Client
dbs3Client.dbs3_url = dbs_url
dbs3Client.dbs3_url_writer = dbs_url_writer
import reqMgrClient
import json
from collections import defaultdict
import optparse
import os
import copy
import time
import random
import math
from RucioClient import RucioClient
from McMClient import McMClient
from JIRAClient import JIRAClient
from utils import sendEmail
from utils import closeoutInfo
from showError import parse_one, showError_options
import threading
import sys
def get_campaign(output, wfi):
## this should be a perfect matching of output->task->campaign
campaign = None
era = None
wf_campaign = None
if 'Campaign' in wfi.request: wf_campaign = wfi.request['Campaign']
try:
era = output.split('/')[2].split('-')[0]
except:
era = None
if wfi.isRelval():
campaign = wf_campaign
else:
campaign = era if era else wf_campaign
return campaign
def getDatasetFiles(url, dataset, without_invalid=True):
# VK TODO: can be replaced with list of files API
# JRV: done through getDatasetFileArray
files = getDatasetFileArray(dataset, validFileOnly=without_invalid, detail=True)
dbs_filenames = [f['logical_file_name'] for f in files]
# conn = make_x509_conn(url)
# conn = httplib.HTTPSConnection(url, cert_file = os.getenv('X509_USER_PROXY'), key_file = os.getenv('X509_USER_PROXY'))
# r1=conn.request("GET",'/phedex/datasvc/json/prod/filereplicas?dataset=%s'%(dataset))
# r2=conn.getresponse()
# result = json.loads(r2.read())
# items=result['phedex']['block']
# phedex_filenames = []
# for block in items:
# for f in block['file']:
# phedex_filenames.append(f['name'])
rucioClient = RucioClient()
rucio_filenames = rucioClient.getFileNamesDataset(dataset)
# return dbs_filenames, phedex_filenames, list(set(dbs_filenames) - set(phedex_filenames)), list(set(phedex_filenames)-set(dbs_filenames))
return dbs_filenames, rucio_filenames, list(set(dbs_filenames) - set(rucio_filenames)), list(
set(rucio_filenames) - set(dbs_filenames))
def checkor(url, spec=None, options=None):
if userLock(): return
mlock = moduleLock(locking=False)
ml = mlock()
fDB = closeoutInfo()
UC = unifiedConfiguration()
use_mcm = True
up = componentInfo(ignore=['mcm', 'wtc'])
if not up.check(): return
up_mcm = componentInfo(ignore=['wtc'])
up_mcm.check()
use_mcm = up_mcm.status['mcm']
now_s = time.mktime(time.gmtime())
def time_point(label="", sub_lap=False, percent=None, is_end=False):
now = time.mktime(time.gmtime())
nows = time.asctime(time.gmtime())
print("[checkor] Time check (%s) point at : %s" % (label, nows))
if percent:
print("[checkor] finishing in about %.2f [s]" % ((now - time_point.start) / percent))
if is_end:
print("[checkor] The checkor cycle for the given workflow has finished, in total it took: %s [s]" % (now - time_point.start))
else:
print("[checkor] Since start: %s [s]" % (now - time_point.start))
if sub_lap:
print("[checkor] Sub Lap : %s [s]" % (now - time_point.sub_lap))
time_point.sub_lap = now
else:
print("[checkor] Lap : %s [s]" % (now - time_point.lap))
time_point.lap = now
time_point.sub_lap = now
time_point.sub_lap = time_point.lap = time_point.start = time.mktime(time.gmtime())
runnings = session.query(Workflow).filter(Workflow.status == 'away').all()
standings = session.query(Workflow).filter(Workflow.status.startswith('assistance')).all()
## intersect with what is actually in completed status in request manager now
all_completed = set(getWorkflows(url, 'completed'))
wfs = []
exceptions = []
if options.strict:
## the one which were running and now have completed
print("strict option is on: checking workflows that freshly completed")
wfs.extend([wfo for wfo in runnings if wfo.name in all_completed])
if options.update:
print("update option is on: checking workflows that have not completed yet")
wfs.extend([wfo for wfo in runnings if not wfo.name in all_completed])
if options.clear:
print("clear option is on: checking workflows that are ready to toggle closed-out")
wfs.extend([wfo for wfo in standings if 'custodial' in wfo.status])
if options.review:
# print "review option is on: checking the workflows that needed intervention"
these = [wfo for wfo in standings if not 'custodial' in wfo.status]
if options.recovering:
print("review-recovering is on: checking only the workflows that had been already acted on")
these = [wfo for wfo in these if not 'manual' in wfo.status]
wfs.extend(these)
if options.manual:
print("review-manual is on: checking the workflows to be acted on")
these = [wfo for wfo in these if 'manual' in wfo.status]
wfs.extend(these)
custodials = defaultdict(list) # sites : dataset list
# transfers = defaultdict(list) #sites : dataset list
invalidations = [] # a list of files
SI = siteInfo()
CI = campaignInfo()
mcm = McMClient(dev=False) if use_mcm else None
JC = JIRAClient() if up.status.get('jira', False) else None
## retrieve bypass and onhold configuration
bypasses = []
forcings = []
holdings = []
WI = wtcInfo()
actors = [a for a, _ in UC.get('allowed_bypass')]
for user, extending in list(WI.getHold().items()):
if not user in actors:
print(user, "is not allowed to hold")
continue
print(user, "is holding", extending)
holdings.extend(extending)
for user, extending in list(WI.getBypass().items()):
if not user in actors:
print(user, "is not allowed to bypass")
continue
print(user, "is bypassing", extending)
bypasses.extend(extending)
overrides = defaultdict(list)
for user, extending in list(WI.getForce().items()):
if not user in actors:
print(user, "is not allowed to force complete")
continue
print(user, "is force-completing", extending)
bypasses.extend(extending)
overrides[user].extend(extending)
if JC:
force_complete_jira_string = "cmsunified please do force-complete"
to_check = JC.find({'text': force_complete_jira_string, "status": "!CLOSED"})
for j in to_check:
jira = JC.get(j.key)
for c in jira.fields.comment.comments:
if force_complete_jira_string in c.body:
user = c.author.name
prepid = jira.fields.summary.split()[0]
keyword = \
c.body[(c.body.find(force_complete_jira_string) + len(force_complete_jira_string)):].split()[0]
if keyword and user in actors:
print(user, "is force-completing", keyword, "from JIRA")
bypasses.append(keyword)
overrides[user].append(keyword)
break
bypass_jira_string = "cmsunified please do bypass"
to_check = JC.find({'text': bypass_jira_string, "status": "!CLOSED"})
for j in to_check:
jira = JC.get(j.key)
for c in jira.fields.comment.comments:
if bypass_jira_string in c.body:
user = c.author.name
prepid = jira.fields.summary.split()[0]
keyword = c.body[(c.body.find(bypass_jira_string) + len(bypass_jira_string)):].split()[0]
if keyword and user in actors:
print(user, "is bypassing", keyword, "from JIRA")
bypasses.append(keyword)
break
if use_mcm:
## this is a list of prepids that are good to complete
forcings = mcm.get('/restapi/requests/forcecomplete')
if not forcings: forcings = []
## remove empty entries ...
bypasses = [_f for _f in bypasses if _f]
# pattern_fraction_pass = UC.get('pattern_fraction_pass')
# cumulative_fraction_pass = UC.get('cumulative_fraction_pass')
# timeout_for_damping_fraction = UC.get('damping_fraction_pass')
# damping_time = UC.get('damping_fraction_pass_rate')
# damping_fraction_pass_max = float(UC.get('damping_fraction_pass_max')/ 100.)
# acdc_rank_for_truncate = UC.get('acdc_rank_for_truncate')
random.shuffle(wfs)
in_manual = 0
## now you have a record of what file was invalidated globally from TT
TMDB_invalid = dataCache.get('file_invalidation')
print("considering", len(wfs), "before any limitation")
max_per_round = UC.get('max_per_round').get('checkor', None)
if options.limit:
print("command line to limit to", options.limit)
max_per_round = options.limit
if max_per_round and not spec:
print("limiting to", max_per_round, "this round")
##should be ordering by priority if you can
## order wfs with rank of wfname
all_completed_plus = sorted(getWorkflows(url, 'completed' , details=True), key = lambda r : r['RequestPriority'])
all_completed_plus = [r['RequestName'] for r in all_completed_plus]
def rank( wfn ):
return all_completed_plus.index( wfn ) if wfn in all_completed_plus else 0
wfs = sorted( wfs, key = lambda wfo : rank( wfo.name ),reverse=True)
if options.update: random.shuffle( wfs )
wfs = wfs[:max_per_round]
print("Going to process the following workflows:")
for w in wfs:
print(w.name)
total_running_time = 1. * 60.
will_do_that_many = len(wfs)
## record all evolution
full_picture = defaultdict(dict)
report_created = 0
checkers = []
for iwfo, wfo in enumerate(wfs):
## do the check other one workflow
if spec and not (spec in wfo.name): continue
if not spec and ('cmsunified_task_HIG-RunIIFall17wmLHEGS-05036__v1_T_200712_005621_4159'.lower() in (
wfo.name).lower() or 'pdmvserv_task_HIG-RunIISummer16NanoAODv7-03979__v1_T_200915_013748_1986'.lower() in (
wfo.name).lower()): continue
checkers.append(CheckBuster(
will_do_that_many=will_do_that_many,
url=url,
wfo=wfo,
iwfo=iwfo,
bypasses=bypasses,
overrides=overrides,
holdings=holdings,
forcings=forcings,
exceptions=exceptions,
TMDB_invalid=TMDB_invalid,
UC=UC,
CI=CI,
SI=SI,
JC=JC,
use_mcm=use_mcm,
mcm=mcm
))
## run the threads
run_threads = ThreadHandler(threads=checkers,
n_threads=options.threads,
sleepy=10,
timeout=360,
verbose=True,
label='checkor'
)
run_threads.start()
## waiting on all to complete
while run_threads.is_alive():
time.sleep(5)
print(len(run_threads.threads), "finished thread to gather information from")
## then wrap up from the threads
failed_threads = 0
for to in run_threads.threads:
if to.failed:
failed_threads += 1
continue
report_created += to.report_created
## change status
if to.put_record:
fDB.update(to.wfo.name, to.put_record)
if to.to_status:
to.wfo.status = to.to_status
if 'manual' in to.to_status:
in_manual += 1
session.commit()
if to.to_status == 'close':
fDB.pop(wfo.name)
if use_mcm and to.force_by_mcm:
for pid in to.pids:
mcm.delete('/restapi/requests/forcecomplete/%s' % pid)
if to.custodials:
for site, items in list(to.custodials.items()):
custodials[site].extend(items)
n_wfs = len(run_threads.threads)
if n_wfs and float(failed_threads / n_wfs) > 0:
sendLog('checkor', '%d/%d threads have failed, better check this out' % (failed_threads, n_wfs),
level='critical')
## remove once it's all good
sendEmail('checkor', '%d/%d threads have failed, better check this out' % (failed_threads, n_wfs))
## conclude things, the good old way
print(report_created, "reports created in this run")
## warn us if the process took a bit longer than usual
if wfs:
now = time.mktime(time.gmtime())
time_spend_per_workflow = float(now - time_point.start) / float(float(len(wfs)))
print("Average time spend per workflow is", time_spend_per_workflow)
## set a threshold to it
if time_spend_per_workflow > 120:
sendLog('checkor', 'The module checkor took %.2f [s] per workflow' % (time_spend_per_workflow),
level='critical')
if not spec and in_manual != 0:
some_details = ""
if options.strict:
some_details += "Workflows which just got in completed were looked at. Look in manual.\n"
if options.update:
some_details += "Workflows that are still running (and not completed) got looked at.\n"
if options.clear:
some_details += "Workflows that just need to close-out were verified. Nothing too new a-priori.\n"
if options.review:
some_details += "Workflows under intervention got review.\n"
count_statuses = defaultdict(int)
for wfo in session.query(Workflow).filter(Workflow.status.startswith('assistance')).all():
count_statuses[wfo.status] += 1
some_details += '\n'.join(
['%3d in status %s' % (count_statuses[st], st) for st in sorted(count_statuses.keys())])
# sendLog('checkor',"Fresh status are available at %s/assistance.html\n%s"%(unified_url, some_details))
# sendEmail("fresh assistance status available","Fresh status are available at %s/assistance.html\n%s"%(unified_url, some_details),destination=['katherine.rozo@cern.ch'])
pass
print("File Invalidation")
print(invalidations)
## a hook to halt checkor nicely at this stage
if os.path.isfile('.checkor_stop'):
print("The loop on workflows was shortened")
sendEmail('checkor', 'Checkor loop was shortened artificially using .checkor_stop')
os.system('rm -f .checkor_stop')
class CheckBuster(threading.Thread):
def __init__(self, **args):
threading.Thread.__init__(self)
## a bunch of other things
for k, v in list(args.items()):
setattr(self, k, v)
## actions
self.to_status = None
self.put_record = None
self.force_by_mcm = None
self.pids = None
self.report_created = 0
self.custodials = defaultdict(list)
self.failed = False
## need to find a way to redirect the printouts
# self.log_file = '%s/%s.checkout'%(cache_dir,self.wfo.name)
def run(self):
try:
# with open(self.log_file, 'w') as sys.stdout:
self.check()
except Exception as e:
# print "failed on", self.wfo.name
# print "due to"
# print str(e)
## there should be a warning at this point
import traceback
sendLog('checkor', 'failed on %s due to %s and %s' % (self.wfo.name, str(e), traceback.format_exc()),
level='critical')
self.failed = True
def check(self):
## a hook to halt checkor nicely at this stage
if os.path.isfile('.checkor_stop'):
print("The check on workflows is shortened")
return
UC = self.UC
CI = self.CI
SI = self.SI
JC = self.JC
url = self.url
bypasses = self.bypasses
overrides = self.overrides
holdings = self.holdings
forcings = self.forcings
exceptions = self.exceptions
TMDB_invalid = self.TMDB_invalid
use_mcm = self.use_mcm
mcm = self.mcm
will_do_that_many = self.will_do_that_many
wfo = self.wfo
iwfo = self.iwfo
pattern_fraction_pass = UC.get('pattern_fraction_pass')
cumulative_fraction_pass = UC.get('cumulative_fraction_pass')
timeout_for_damping_fraction = UC.get('damping_fraction_pass')
damping_time = UC.get('damping_fraction_pass_rate')
damping_fraction_pass_max = float(UC.get('damping_fraction_pass_max') / 100.)
acdc_rank_for_truncate = UC.get('acdc_rank_for_truncate')
use_recoveror = UC.get('use_recoveror')
def time_point(label="", sub_lap=False, percent=None, is_end=False):
now = time.mktime(time.gmtime())
nows = time.asctime(time.gmtime())
print("[checkor] Time check (%s) point at : %s" % (label, nows))
if percent:
print("[checkor] finishing in about %.2f [s]" % ((now - time_point.start) / percent))
if is_end:
print("[checkor] The checkor cycle for the given workflow has finished, in total it took: %s [s]" % (now - time_point.start))
else:
print("[checkor] Since start: %s [s]" % (now - time_point.start))
if sub_lap:
print("[checkor] Sub Lap : %s [s]" % (now - time_point.sub_lap))
time_point.sub_lap = now
else:
print("[checkor] Lap : %s [s]" % (now - time_point.lap))
time_point.lap = now
time_point.sub_lap = now
time_point.sub_lap = time_point.lap = time_point.start = time.mktime(time.gmtime())
now_s = time.mktime(time.gmtime())
time_point("Starting checkor with %s Progress [%d/%d]" % (wfo.name, iwfo, will_do_that_many),
percent=float(iwfo) / will_do_that_many)
usage = checkMemory()
print("memory so far", usage)
## get info
wfi = workflowInfo(url, wfo.name)
wfi.sendLog('checkor', "checking on %s %s" % (wfo.name, wfo.status))
## make sure the wm status is up to date.
# and send things back/forward if necessary.
wfo.wm_status = wfi.request['RequestStatus']
if wfo.wm_status in ['closed-out', 'announced'] and not wfo.name in exceptions:
## manually closed-out
wfi.sendLog('checkor', "%s is already %s, setting close" % (wfo.name, wfo.wm_status))
self.to_status = 'close'
return
elif wfo.wm_status in ['failed', 'aborted', 'aborted-archived', 'rejected', 'rejected-archived',
'aborted-completed']:
## went into trouble
if wfi.isRelval():
wfi.sendLog('checkor', "%s is %s, but will not be set in trouble to find a replacement." % (
wfo.name, wfo.wm_status))
self.to_status = 'forget'
else:
self.to_status = 'trouble'
wfi.sendLog('checkor', "%s is in trouble %s" % (wfo.name, wfo.wm_status))
return
elif wfo.wm_status in ['assigned', 'acquired']:
## not worth checking yet
wfi.sendLog('checkor', "%s is not running yet" % wfo.name)
return
if wfo.wm_status != 'completed' and not wfo.name in exceptions:
## for sure move on with closeout check if in completed
wfi.sendLog('checkor', "no need to check on %s in status %s" % (wfo.name, wfo.wm_status))
return
# session.commit()
# sub_assistance="" # if that string is filled, there will be need for manual assistance
existing_assistance_tags = set(wfo.status.split('-')[1:]) # [0] should be assistance
assistance_tags = set()
is_closing = True
stop_duplicate_check = True
## get it from somewhere
bypass_checks = False
for bypass in bypasses:
# if bypass and bypass in wfo.name:
if bypass == wfo.name:
wfi.sendLog('checkor', "we can bypass checks on %s because of keyword %s " % (wfo.name, bypass))
bypass_checks = True
break
pids = wfi.getPrepIDs()
self.pids = pids
force_by_mcm = False
force_by_user = False
for force in forcings:
if force in pids:
wfi.sendLog('checkor',
"we can bypass checks and force complete %s because of prepid %s " % (wfo.name, force))
bypass_checks = True
force_by_mcm = True
break
for user in overrides:
for force in overrides[user]:
if force in wfo.name:
wfi.sendLog('checkor',
"we can bypass checks and force complete %s because of keyword %s of user %s" % (
wfo.name, force, user))
bypass_checks = True
force_by_user = True
break
delays = [(now_s - completed_log[-1]['UpdateTime']) / (60. * 60. * 24.) if completed_log else 0 for
completed_log in
[[change for change in m['RequestTransition'] if change["Status"] in ["completed"]] for m in
wfi.getFamilly(details=True, and_self=True)]]
delays = [_f for _f in delays if _f]
min_completed_delays = min(delays) ## take the shortest time since a member of the familly completed
completed_log = [change for change in wfi.request['RequestTransition'] if change["Status"] in ["completed"]]
delay = (now_s - completed_log[-1]['UpdateTime']) / (60. * 60. * 24.) if completed_log else 0 ## in days
completed_delay = delay ## this is for the workflow itself
# onhold_completed_delay = delay
onhold_completed_delay = min_completed_delays ## this is for any workflows (itself, and ACDC)
onhold_timeout = UC.get('onhold_timeout')
if '-onhold' in wfo.status:
print("onhold since", onhold_completed_delay, "timeout at", onhold_timeout)
if onhold_timeout > 0 and onhold_timeout < onhold_completed_delay:
bypass_checks = True
wfi.sendLog('checkor',
"%s is on hold and stopped for %.2f days, letting this through with current statistics" % (
wfo.name, onhold_completed_delay))
else:
if wfo.name in holdings and not bypass_checks:
wfi.sendLog('checkor', "%s is on hold" % wfo.name)
return
if wfo.name in holdings and not bypass_checks:
if onhold_timeout > 0 and onhold_timeout < onhold_completed_delay:
bypass_checks = True
wfi.sendLog('checkor',
"%s is on hold and stopped for %.2f days, letting this through with current statistics" % (
wfo.name, onhold_completed_delay))
else:
self.to_status = 'assistance-onhold'
wfi.sendLog('checkor', "setting %s on hold" % wfo.name)
return
tiers_with_no_check = copy.deepcopy(UC.get('tiers_with_no_check')) # dqm*
vetoed_custodial_tier = copy.deepcopy(
UC.get('tiers_with_no_custodial')) if not wfi.isRelval() else [] # no veto for relvals
to_ddm_tier = copy.deepcopy(UC.get('tiers_to_DDM'))
campaigns = {} ## this mapping of campaign per output dataset assumes era==campaing, which is not true for relval
expected_outputs = copy.deepcopy(wfi.request['OutputDatasets'])
### NEEDS A BUG FIX : find campaign per dataset
## probably best to get outpuut per task, then campaign per task
for out in wfi.request['OutputDatasets']:
c = get_campaign(out, wfi)
campaigns[out] = c
wf_campaigns = wfi.getCampaigns()
## override the previous if there is only one campaign in the workflow
if len(wf_campaigns) == 1:
for out in campaigns:
campaigns[out] = wf_campaigns[0]
for out, c in list(campaigns.items()):
if c in CI.campaigns and 'custodial_override' in CI.campaigns[c]:
if type(CI.campaigns[c]['custodial_override']) == list:
vetoed_custodial_tier = list(
set(vetoed_custodial_tier) - set(CI.campaigns[c]['custodial_override']))
## add those that we need to check for custodial copy
tiers_with_no_check = list(set(tiers_with_no_check) - set(
CI.campaigns[c]['custodial_override'])) ## would remove DQM from the vetoed check
elif CI.campaigns[c]['custodial_override'] == 'notape':
vetoed_custodial_tier = sorted(set([o.split('/')[-1] for o in wfi.request['OutputDatasets']]))
print(campaigns)
check_output_text = "Initial outputs:" + ",".join(sorted(wfi.request['OutputDatasets']))
wfi.request['OutputDatasets'] = [out for out in wfi.request['OutputDatasets'] if not any(
[out.split('/')[-1] == veto_tier for veto_tier in tiers_with_no_check])]
check_output_text += "\nWill check on:" + ",".join(sorted(wfi.request['OutputDatasets']))
check_output_text += "\ntiers out:" + ",".join(sorted(tiers_with_no_check))
check_output_text += "\ntiers no custodial:" + ",".join(sorted(vetoed_custodial_tier))
wfi.sendLog('checkor', check_output_text)
## anything running on acdc : getting the real prepid is not worth it
familly = getWorkflowById(url, wfi.request['PrepID'], details=True)
acdc = []
acdc_failed = []
acdc_inactive = []
forced_already = False
acdc_bads = []
acdc_order = -1
true_familly = []
for member in familly:
if member['RequestType'] != 'Resubmission': continue
if member['RequestName'] == wfo.name: continue
if member['RequestDate'] < wfi.request['RequestDate']: continue
if member['PrepID'] != wfi.request['PrepID']: continue
# if 'OriginalRequestName' in member and (not 'ACDC' in member['OriginalRequestName']) and member['OriginalRequestName'] != wfo.name: continue
if member['RequestStatus'] == None: continue
if not set(member['OutputDatasets']).issubset(set(expected_outputs)):
if not member['RequestStatus'] in ['rejected-archived', 'rejected', 'aborted', 'aborted-archived']:
##this is not good at all
wfi.sendLog('checkor', 'inconsistent ACDC %s' % member['RequestName'])
acdc_bads.append(member['RequestName'])
is_closing = False
assistance_tags.add('manual')
assistance_tags.add('inconsistent')
continue
true_familly.append(member['RequestName'])
for irank in range(10):
if 'ACDC%d' % irank in member['RequestName']:
acdc_order = max(irank, acdc_order)
if member['RequestStatus'] in ['running-open', 'running-closed', 'assigned', 'acquired', 'staging',
'staged']:
print(wfo.name, "still has an ACDC running", member['RequestName'])
acdc.append(member['RequestName'])
## cannot be bypassed!
is_closing = False
assistance_tags.add('recovering')
if (force_by_mcm or force_by_user) and not forced_already:
wfi.sendLog('checkor', '%s is being forced completed while recovering' % wfo.name)
wfi.notifyRequestor("The workflow %s was force completed" % wfo.name, do_batch=False)
forceComplete(url, wfi)
forced_already = True
elif member['RequestStatus'] in ['failed']:
acdc_failed.append(member['RequestName'])
# set this or not assistance_tags.add('inconsistent')
else:
acdc_inactive.append(member['RequestName'])
assistance_tags.add('recovered')
if acdc_failed:
sendLog('checkor', 'For %s, ACDC %s failed' % (wfo.name, ','.join(acdc_failed)), level='critical')
if acdc_bads:
sendLog('checkor', 'For %s, ACDC %s is inconsistent, preventing from closing or will create a mess.' % (
wfo.name, ','.join(acdc_bads)), level='critical')
time_point("checked workflow familly", sub_lap=True)
## completion check
percent_completions = {}
percent_avg_completions = {}
fractions_pass = {}
fractions_announce = {}
fractions_truncate_recovery = {}
events_per_lumi = {}
over_100_pass = True
(lhe, prim, _, _) = wfi.getIO()
if lhe or prim: over_100_pass = False
## this will create funky issue with LHEGS where the two output of a task can have different expected #of events ... as predicted this is a major complication
event_expected_per_task = {}
output_per_task = wfi.getOutputPerTask()
task_outputs = {}
for task, outs in list(output_per_task.items()):
for out in outs:
# task_outputs[out] = task
task_outputs[out] = wfi.request.get(task, {}).get('TaskName', task)
## lumi_expected is constant over all tasks
## event_expected is only valid for the "first task" and one needs to consider all efficiency on the way
event_expected, lumi_expected = wfi.request.get('TotalInputEvents', None), wfi.request.get('TotalInputLumis',
None)
if event_expected == None:
sendEmail("missing member of the request", "TotalInputEvents is missing from the workload of %s" % wfo.name)
sendLog('checkor', "TotalInputEvents is missing from the workload of %s" % wfo.name, level='critical')
event_expected = 0
assistance_tags.add('missingParam')
ttype = 'Task' if 'TaskChain' in wfi.request else 'Step'
it = 1
tname_dict = {}
while True:
tt = '%s%d' % (ttype, it)
it += 1
if tt in wfi.request:
tname = wfi.request[tt]['%sName' % ttype]
tname_dict[tname] = tt
if not 'Input%s' % ttype in wfi.request[tt] and 'RequestNumEvents' in wfi.request[tt]:
## pick up the value provided by the requester, that will work even if the filter effiency is broken
event_expected = wfi.request[tt]['RequestNumEvents']
else:
break
if '%sChain' % ttype in wfi.request:
## go on and make the accounting
it = 1
while True:
tt = '%s%d' % (ttype, it)
it += 1
if tt in wfi.request:
tname = wfi.request[tt]['%sName' % ttype]
event_expected_per_task[tname] = event_expected
### then go back up all the way to the root task to count filter-efficiency
a_task = wfi.request[tt]
while 'Input%s' % ttype in a_task:
event_expected_per_task[tname] *= a_task.get('FilterEfficiency', 1)
mother_task = a_task['Input%s' % ttype]
## go up
a_task = wfi.request[tname_dict[mother_task]]
else:
break
print(event_expected_per_task)
print(task_outputs)
time_point("expected statistics", sub_lap=True)
running_log = [change for change in wfi.request['RequestTransition'] if change["Status"] in ["running-open", "running-closed"]]
running_delay = (now_s - (min(l['UpdateTime'] for l in running_log))) / (
60. * 60. * 24.) if running_log else 0 ## in days
print(delay, "since completed")
default_fraction_overdoing = UC.get('default_fraction_overdoing')
for output in wfi.request['OutputDatasets']:
default_pass = UC.get('default_fraction_pass')
fractions_pass[output] = default_pass
fractions_announce[output] = 1.0
# fractions_truncate_recovery[output] = 0.98 ## above this threshold if the request will pass stats check, we close the acdc
c = campaigns[output]
if c in CI.campaigns and 'earlyannounce' in CI.campaigns[c]:
wfi.sendLog('checkor', "Allowed to announce the output %s over %.2f by campaign requirement" % (
out, CI.campaigns[c]['earlyannounce']))
fractions_announce[output] = CI.campaigns[c]['earlyannounce']
if c in CI.campaigns and 'damping' in CI.campaigns[c]:
## allow to decrease the pass threshold
pass
if c in CI.campaigns and 'fractionpass' in CI.campaigns[c]:
if type(CI.campaigns[c]['fractionpass']) == dict:
tier = output.split('/')[-1]
priority = str(wfi.request['RequestPriority'])
## defined per tier
fractions_pass[output] = CI.campaigns[c]['fractionpass'].get('all', default_pass)
if tier in CI.campaigns[c]['fractionpass']:
tier_pass_content = CI.campaigns[c]['fractionpass'][tier]
if type(tier_pass_content) == dict:
fractions_pass[output] = CI.campaigns[c]['fractionpass'][tier].get('all', default_pass)
for exp, pass_exp in list(CI.campaigns[c]['fractionpass'][tier].items()):
if output.startswith(exp):
fractions_pass[output] = pass_exp
else:
fractions_pass[output] = CI.campaigns[c]['fractionpass'][tier]
if priority in CI.campaigns[c]['fractionpass']:
fractions_pass[output] = CI.campaigns[c]['fractionpass'][priority]
else:
fractions_pass[output] = CI.campaigns[c]['fractionpass']
wfi.sendLog('checkor', "overriding fraction to %s for %s by campaign requirement" % (
fractions_pass[output], output))
if options.fractionpass:
fractions_pass[output] = options.fractionpass
print("overriding fraction to", fractions_pass[output], "by command line for", output)
for key in pattern_fraction_pass:
if key in output:
fractions_pass[output] = pattern_fraction_pass[key]
print("overriding fraction to", fractions_pass[output], "by dataset key", key)
pass_percent_below = fractions_pass[output] - 0.02
weight_full = 7.
weight_pass = delay
weight_under_pass = 2 * delay if int(
wfi.request['RequestPriority']) < 80000 else 0. ## allow to drive it below the threshold
weight_under_pass = 0. ## otherwise we can end-up having request at 94% waiting for 95%
fractions_truncate_recovery[output] = (fractions_pass[
output] * weight_pass + 1. * weight_full + pass_percent_below * weight_under_pass) / (
weight_pass + weight_full + weight_under_pass)
if c in CI.campaigns and 'truncaterecovery' in CI.campaigns[c]:
wfi.sendLog('checkor', "Allowed to truncate recovery of %s over %.2f by campaign requirement" % (
out, CI.campaigns[c]['truncaterecovery']))
fractions_truncate_recovery[output] = CI.campaigns[c]['truncaterecovery']
else:
wfi.sendLog('checkor',
"Can truncate recovery of %s over %.2f" % (out, fractions_truncate_recovery[output]))
if fractions_truncate_recovery[output] < fractions_pass[output]:
print("This is not going to end well if you truncate at a lower threshold than passing", \
fractions_truncate_recovery[output], fractions_pass[output])
## floor truncating
fractions_truncate_recovery[output] = fractions_pass[output]
##### OR
##wfi.sendLog('checkor', "Lowering the pass bar since recovery is being truncated")
#
# fractions_pass[output] = fractions_truncate_recovery[output]
# introduce a reduction factor on very old requests
# 1% every damping_time days after > timeout_for_damping_fraction in completed. Not more than damping_fraction_pass_max
# fraction_damping = min(0.01*(max(running_delay - timeout_for_damping_fraction,0)/damping_time),damping_fraction_pass_max)
fraction_damping = min(0.01 * (max(completed_delay - timeout_for_damping_fraction, 0) / damping_time),
damping_fraction_pass_max)
print("We could reduce the passing fraction by", fraction_damping, "given it's been in for long")
long_lasting_choped = False
for out in fractions_pass:
if fractions_pass[out] != 1.0 and fraction_damping: ## strictly ones cannot be set less than one
if timeout_for_damping_fraction:
fractions_pass[out] -= fraction_damping
fractions_truncate_recovery[out] -= fraction_damping
long_lasting_choped = True
if long_lasting_choped:
msg = 'Reducing pass thresholds by %.3f%% for long lasting workflow %s ' % (
100 * fraction_damping, wfi.request['RequestName'])
wfi.sendLog('checkor', msg)
# sendLog('checkor', msg, level='critical')
## do something about workflow with high order ACDC
# acdc_order == -1 None
# acdc_order == 0 ACDC0 first round
if acdc_order > acdc_rank_for_truncate:
## there is high order acdc on-going. chop the output at the pass fraction
wfi.sendLog('checkor', 'Truncating at pass threshold because of ACDC of rank %d' % acdc_order)
fractions_truncate_recovery[out] = fractions_pass[out]
# and then make the fraction multiplicative per child
parentage = {} ## a daugther: parents kind of thing
for out in list(fractions_pass.keys()):
parentage[out] = findParent(out)
def upward(ns):
r = set(ns)
for n in ns:
if n in parentage:
r.update(upward(parentage[n]))
return r
for out in fractions_pass:
ancestors = upward(parentage.get(out, []))
initial_pass = fractions_pass[out]
descending_pass = fractions_pass[out]
descending_truncate = fractions_truncate_recovery[out]
for a in ancestors:
descending_pass *= fractions_pass.get(a, 1.) ## multiply by fraction of all ancestors
descending_truncate *= fractions_pass.get(a, 1.)
if cumulative_fraction_pass:
fractions_pass[out] = descending_pass
fractions_truncate_recovery[out] = descending_truncate
print("For", out, "previously passing at", initial_pass, "is now passing at", descending_pass)
else:
print("For", out, "isntead of passing at", initial_pass, "could be done with", descending_pass)
time_point("statistics thresholds", sub_lap=True)
expectedL = defaultdict(int)
expectedN = defaultdict(int)
producedL = defaultdict(int)
producedN = defaultdict(int)
for output in wfi.request['OutputDatasets']:
event_count, lumi_count = getDatasetEventsAndLumis(dataset=output)
producedL[output] = lumi_count
producedN[output] = event_count
events_per_lumi[output] = event_count / float(lumi_count) if lumi_count else 100
percent_completions[output] = 0.
if lumi_expected:
wfi.sendLog('checkor', "lumi completion %s expected %d for %s" % (lumi_count, lumi_expected, output))
percent_completions[output] = lumi_count / float(lumi_expected)
expectedL[output] = lumi_expected
# output_event_expected = event_expected_per_task.get(task_outputs.get(output,'NoTaskFound'), event_expected)
# if output_event_expected:
# expectedN[output] = output_event_expected
# e_fraction = float(event_count) / float( output_event_expected )
# if e_fraction > percent_completions[output]:
# percent_completions[output] = e_fraction
# wfi.sendLog('checkor', "overiding : event completion real %s expected %s for %s"%(event_count, output_event_expected, output))
percent_avg_completions[output] = percent_completions[output]
time_point("observed statistics", sub_lap=True)
pass_stats_check = dict(
[(out, bypass_checks or (percent_completions[out] >= fractions_pass[out])) for out in fractions_pass])
lumis_per_run = {} # a dict of dict run:[lumis]
files_per_rl = {} # a dict of dict "run:lumi":[files]
fetched = dict([(out, False) for out in pass_stats_check])
blocks = wfi.getBlockWhiteList()
rwl = wfi.getRunWhiteList()
lwl = wfi.getLumiWhiteList()
## need to come to a way to do this "fast" so that it can be done more often
if not all(pass_stats_check.values()): # and False:
n_runs = 1
## should recalculate a couple of things to be able to make a better check on expected fraction
for p in prim:
nr = getDatasetRuns(p)
if len(nr) > 1:
print("fecthing input lumis and files for", p)
lumis_per_run[p], files_per_rl[p] = getDatasetLumisAndFiles(p, runs=rwl, lumilist=lwl)
n_runs = len(set(lumis_per_run[p].keys()))
for out in pass_stats_check:
if prim and n_runs > 1:
## do only for multiple runs output and something in input
lumis_per_run[out], files_per_rl[out] = getDatasetLumisAndFiles(out)
fetched[out] = True
## now do a better check of fractions
fraction_per_run = {}
a_primary = list(prim)[0]
all_runs = sorted(set(list(lumis_per_run[a_primary].keys()) + list(lumis_per_run[out].keys())))
for run in all_runs:
denom = lumis_per_run[a_primary].get(run, [])
numer = lumis_per_run[out].get(run, [])
if denom:
fraction_per_run[run] = float(len(numer)) / len(denom)
else:
print("for run", run, "in output, there isnt any run in input/output...")
if fraction_per_run:
lowest_fraction = min(fraction_per_run.values())
highest_fraction = max(fraction_per_run.values())
average_fraction = sum(fraction_per_run.values()) / len(list(fraction_per_run.values()))
print("the lowest completion fraction per run for", out, " is", lowest_fraction)
print("the highest completion fraction per run for", out, " is", highest_fraction)
print("the average completion fraction per run for", out, " is", average_fraction)
percent_avg_completions[out] = average_fraction
percent_completions[out] = lowest_fraction
time_point("more detailed observed statistics", sub_lap=True)
pass_stats_check = dict(
[(out, bypass_checks or (percent_completions[out] >= fractions_pass[out])) for out in fractions_pass])
pass_stats_check_to_announce = dict(
[(out, (percent_avg_completions[out] >= fractions_announce[out])) for out in fractions_pass])
pass_stats_check_to_truncate_recovery = dict(
[(out, (percent_avg_completions[out] >= fractions_truncate_recovery[out])) for out in
fractions_truncate_recovery])
pass_stats_check_over_completion = dict(
[(out, (percent_completions[out] >= default_fraction_overdoing)) for out in percent_completions])
print("announce checks")
should_announce = False
if pass_stats_check_to_announce and all(pass_stats_check_to_announce.values()):
wfi.sendLog('checkor',
"The output of this workflow are essentially good to be announced while we work on the rest\n%s \n%s" % (
json.dumps(percent_avg_completions, indent=2), json.dumps(fractions_announce, indent=2)))
assistance_tags.add('announced' if 'announced' in wfo.status else 'announce')
should_announce = True
if not all(pass_stats_check.values()):
possible_recoveries = wfi.getRecoveryDoc()
if possible_recoveries == [] or possible_recoveries == None:
wfi.sendLog('checkor',
'%s has missing statistics \n%s \n%s, but nothing is recoverable. passing through to annoucement' % (
wfo.name, json.dumps(percent_completions, indent=2),
json.dumps(fractions_pass, indent=2)))