forked from CMSCompOps/WmAgentScripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reqMgrClient.py
1282 lines (1139 loc) · 47 KB
/
reqMgrClient.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 python
"""
This client encapsulates several basic queries to request manager.
This uses ReqMgr rest api through HTTP
url parameter is normally 'cmsweb.cern.ch'
"""
import urllib
import httplib
import re
import os
import json
import dbs3Client as dbs3
import copy
import time
# default headers for PUT and POST methods
def_headers={"Content-type": "application/json", "Accept": "application/json"}
def_headers1={"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
CERT_FILE = os.getenv('X509_USER_PROXY')
#print CERT_FILE
KEY_FILE = os.getenv('X509_USER_PROXY')
#print KEY_FILE
#CERT_FILE = os.getenv('X509_USER_CERT')
#print CERT_FILE
#KEY_FILE = os.getenv('X509_USER_KEY')
#print KEY_FILE
class Workflow:
"""
Wraps all information available on ReqMgr
To avoid querying the same stuff multiple times
This is useful for closeout script
"""
def __init__(self, name, url='cmsweb.cern.ch', workflow=None):
"""
Initialization
"""
#true if a object for copy was provided
obj = (workflow is not None) and isinstance(workflow, Workflow)
self.name = name
self.url = url
#from the workflow Info
#if workflow object was provided, deep copy, otherwise pull info
if obj:
self.info = workflow.info
self.cache = workflow.cache
else:
self.info = getWorkflowInfo(url, name)
self.cache = getWorkloadCache(url, name)
self.status = self.info['RequestStatus']
self.type = self.info['RequestType']
if 'SubRequestType' in self.info:
self.subType = self.info['SubRequestType']
else:
self.subType = None
#if object was provided no need to pull the info
if obj:
self.outputDatasets = workflow.outputDatasets
else:
self.outputDatasets = outputdatasetsWorkflow(url, name)
if 'Teams' in self.info and len(self.info['Teams']) > 0 :
self.team = self.info['Teams'][0]
else:
self.team = 'NoTeam'
if 'FilterEfficiency' in self.info:
self.filterEfficiency = float(self.info['FilterEfficiency'])
self.outEvents = {}
self.outLumis = {}
def getInputEvents(self):
"""
Gets the inputs events of a given workflow
depending of the kind of workflow, by default gets
it from the workload cache.
"""
ev = 0
if 'TotalInputEvents' in self.cache:
ev = self.cache['TotalInputEvents']
if not ev:
ev = self.info['RequestNumEvents']/self.info['FilterEfficiency']
return ev
def getInputLumis(self):
"""
Gets the inputs lumis of a given workflow
depending of the kind of workflow, by default gets
it from the workload cache.
"""
if 'TotalInputLumis' in self.cache:
return self.cache['TotalInputLumis']
return 0
def getOutputEvents(self, ds, skipInvalid=False):
"""
gets the output events on one of the output datasets
"""
#We store the events to avoid checking them twice
if ds not in self.outEvents:
events = dbs3.getEventCountDataSet(ds, skipInvalid)
self.outEvents[ds] = events
else:
events = self.outEvents[ds]
return events
def getOutputLumis(self, ds, skipInvalid=False):
"""
Gets the numer of lumis in an output dataset
"""
#We store the events to avoid checking them twice
if ds not in self.outLumis:
lumis = dbs3.getLumiCountDataSet(ds, skipInvalid)
self.outLumis[ds] = lumis
else:
lumis = self.outLumis[ds]
return lumis
def percentageCompletion(self, ds, skipInvalid=False):
"""
Calculates Percentage of lumis produced for a given workflow
taking a particular output dataset
"""
inputEvents = self.getInputLumis()
outputEvents = self.getOutputLumis(ds, skipInvalid)
if inputEvents == 0:
return 0
if not outputEvents:
return 0
perc = outputEvents/float(inputEvents)
return perc
def __getattr__(self, value):
"""
To behave like a dictionary
"""
return self.info[value]
class MonteCarlo(Workflow):
"""
MonteCarlo from scratch (no dataset input needed).
"""
def __init__(self, name, url='cmsweb.cern.ch', workflow=None):
Workflow.__init__(self, name, url, workflow)
def getInputEvents(self):
#if request is montecarlo or Step0, the numer of
#input events is by the requsted events
if self.type == 'MonteCarlo' or self.type == 'LHEStepZero':
if 'RequestNumEvents' in self.info and self.info['RequestNumEvents']>0:
return self.info['RequestNumEvents']
elif 'RequestSizeEvents' in self.info:
return self.info['RequestSizeEvents']
else:
return 0
else:
raise Exception("Workflow with wrong type")
class StepZero(Workflow):
"""
Step0 MonteCarlo, no dataset input needed either.
"""
def __init__(self, name, url='cmsweb.cern.ch', workflow=None):
Workflow.__init__(self, name, url, workflow)
def getInputEvents(self):
#if request is montecarlo or Step0, the numer of
#input events is by the requsted events
if self.type == 'MonteCarlo' or self.type == 'LHEStepZero':
if 'RequestNumEvents' in self.info and self.info['RequestNumEvents']>0:
return self.info['RequestNumEvents']
elif 'RequestSizeEvents' in self.info:
return self.info['RequestSizeEvents']
else:
return 0
else:
raise Exception("Workflow with wrong type")
class WorkflowWithInput(Workflow):
"""
That needs at least one input dataset
"""
inputlists = ["RunWhitelist", "RunBlacklist", "BlockWhitelist"
, "BlockBlacklist", "LumiList"]
def __init__(self, name, url='cmsweb.cern.ch', workflow=None):
Workflow.__init__(self, name, url)
if 'InputDataset'in self.info and len(self.info['InputDataset']) > 0:
self.inputDataset = self.info['InputDataset']
else:
raise Exception("This workflow has no input %s"%name)
self.inputEvents = None
#fix lists
for li in self.inputlists:
#if empty list or no list
if li not in self.info or self.info[li]=='[]' or self.info[li]=='':
self.info[li] = []
#if there is not a list but some elements it creates a list
if type(self.info[li]) is not list:
#single element
if '[' not in self.info[li]:
self.info[li] = [self.info[li]]
#parse a list
else:
self.info[li]= eval(self.info[li])
#if not, an empty list will do
else:
self.info[li]=[]
self.inputLumisFromDset = None
def percentageCompletion(self, ds, skipInvalid=False, checkInput=False):
"""
Calculates the percentage of completion based on lumis
if checkInput=True, the ammount of lumis is taken from the input
dataset (take into account the white/blacklist are not calculated
"""
inputEvents = self.getInputLumis(checkInput=checkInput)
outputEvents = self.getOutputLumis(ds, skipInvalid)
if inputEvents == 0:
return 0
if not outputEvents:
return 0
perc = outputEvents/float(inputEvents)
return perc
def getInputLumis(self, checkList = False, checkInput=False):
"""
Checks against lumi list
"""
if not checkList and not checkInput:
return Workflow.getInputLumis(self)
if checkInput:
#retrieve lumis of the inpu dataset
return dbs3.getLumiCountDataSet(self.inputDataset)
if checkList:
runLumis = self.info['LumiList']
if runLumis:
total = 0
for run, lumiList in runLumis.items():
total += sum(l2 - l1 + 1 for l1, l2 in lumiList)
return total
return 0
class MonteCarloFromGen(WorkflowWithInput):
"""
Montecarlo using a GEN dataset as input
"""
def __init__(self, name, url='cmsweb.cern.ch', workflow=None):
WorkflowWithInput.__init__(self, name, url, workflow)
class ReReco(WorkflowWithInput):
"""
"""
def __init__(self, name, url='cmsweb.cern.ch', workflow=None):
WorkflowWithInput.__init__(self, name, url, workflow)
class ReDigi(WorkflowWithInput):
"""
Using a GEN-SIM dataset as input
"""
def __init__(self, name, url='cmsweb.cern.ch', workflow=None):
WorkflowWithInput.__init__(self, name, url, workflow)
class StoreResults(WorkflowWithInput):
"""
Uses a user dataset as input
"""
def __init__(self, name, url='cmsweb.cern.ch', workflow=None):
WorkflowWithInput.__init__(self, name, url, workflow)
class TaskChain(Workflow):
"""
Chained workflow. several steps
"""
def __init__(self, name, url='cmsweb.cern.ch', workflow=None):
Workflow.__init__(self, name, url, workflow)
def getInputDataset(self):
task1 = self.info['Task1']
if 'InputDataset' in task1:
return task1['InputDataset']
return None
def getInputEvents(self):
return getInputEventsTaskChain(self.info)
def getFilterEfficiency(self, task):
"""
Filter efficiency of a given task
"""
if task in self.info:
if 'FilterEfficiency' in self.info[task]:
filterEff = float(self.info[task]['FilterEfficiency'])
else:
filterEff = None
return filterEff
#if not found
return None
def createWorkflowObject(name, url='cmsweb.cern.ch'):
"""
Factory method
Creates a Workflow object casted to the
specific class to its type
"""
wf = Workflow(name , url)
if wf.type == "MonteCarlo" and re.search('.*/GEN$', wf.outputDatasets[0]):
wf = StepZero(name, url, wf)
elif wf.type == "MonteCarlo":
wf = MonteCarlo(name, url, wf)
elif wf.type == "MonteCarloFromGEN":
wf = MonteCarloFromGen(name, url, wf)
elif wf.type == "ReDigi":
wf = ReDigi(name, url, wf)
elif wf.type == "ReReco":
wf = ReReco(name, url, wf)
elif wf.type == "StoreResults":
wf = StoreResults(name, url, wf)
elif wf.type == "TaskChain":
wf = TaskChain(name, url, wf)
return wf
def requestManagerGet(url, request, retries=4):
"""
Queries ReqMgr through a HTTP GET method
in every request manager query
url: the instance used, i.e. url='cmsweb.cern.ch'
request: the request suffix url
retries: number of retries
"""
conn = httplib.HTTPSConnection(url, cert_file = CERT_FILE,
key_file = KEY_FILE)
headers = {"Accept": "application/json"}
r1=conn.request("GET",request, headers=headers)
r2=conn.getresponse()
request = json.loads(r2.read())
#try until no exception
while 'exception' in request and retries > 0:
conn = httplib.HTTPSConnection(url, cert_file = CERT_FILE,
key_file = KEY_FILE)
r1=conn.request("GET",request, headers=headers)
r2=conn.getresponse()
request = json.loads(r2.read())
retries-=1
if 'exception' in request:
raise Exception('Maximum queries to ReqMgr exceeded',str(request))
return request
#def _convertToRequestMgrPostCall(url, request, params, head):
# header = {"Content-type": "application/json", "Accept": "application/json"}
# if request == '/reqmgr/create/makeSchema':
# request = "/reqmgr2/data/request"
# data, status = _post(url, request, params, head=header, encode=json.dumps)
# else:
# raise Exception("no correspondonting reqmgr2 call for %s" % request)
# return data
def requestManager1Post(url, request, params, head = def_headers1, nested=False):
"""
Performs some operation on ReqMgr through
an HTTP POST method.
url: the instance used, i.e. url='cmsweb.cern.ch'
request: the request suffix url for the POST method
params: a dict with the POST parameters
nested: deep encode a json parameters
"""
if nested:
jsonEncodedParams ={}
for pKey in params:
jsonEncodedParams[pKey] = json.dumps(params[pKey])
encodedParams = urllib.urlencode(jsonEncodedParams)
else:
encodedParams = urllib.urlencode(params)
data, status = _post(url, request, encodedParams, head, encode=None)
return data
def requestManagerPost(url, request, params, head = def_headers):
"""
Performs some operation on ReqMgr through
an HTTP POST method.
url: the instance used, i.e. url='cmsweb.cern.ch'
request: the request suffix url for the POST method
params: a dict with the POST parameters
nested: deep encode a json parameters
"""
data, status = _post(url, request, params, head, encode=json.dumps)
return data
def _put(url, request, params, head=def_headers, encode=urllib.urlencode):
return _httpsRequest("PUT", url, request, params, head, encode)
def _post(url, request, params, head=def_headers, encode=urllib.urlencode):
return _httpsRequest("POST", url, request, params, head, encode)
def _httpsRequest(verb, url, request, params, head, encode):
conn = httplib.HTTPSConnection(url, cert_file = CERT_FILE,
key_file = KEY_FILE)
headers = head
if encode:
encodedParams = encode(params)
else:
encodedParams = params
conn.request(verb, request, encodedParams, headers)
response = conn.getresponse()
data = response.read()
conn.close()
return (data, response.status)
def requestManager1Put(url, request, params, head = def_headers1):
"""
Performs some operation on ReqMgr through
an HTTP PUT method.
url: the instance used, i.e. url='cmsweb.cern.ch'
request: the request suffix url for the POST method
params: a dict with the PUT parameters
head: optional headers param. If not given it takes default value (def_headers)
"""
data, status = _put(url, request, params, head)
return data
def requestManagerPut(url, request, params, head = def_headers):
"""
Performs some operation on ReqMgr through
an HTTP PUT method.
url: the instance used, i.e. url='cmsweb.cern.ch'
request: the request suffix url for the POST method
params: a dict with the PUT parameters
head: optional headers param. If not given it takes default value (def_headers)
"""
data, status = _put(url, request, params, head, encode=json.dumps)
return data
def getWorkflowWorkload(url, workflow, retries=4):
"""
Gets the workflow loaded, splitted by lines.
"""
print "getWorkflowWorkload is Deprecated"
return None
def getWorkflowInfo(url, workflow):
"""
Retrieves workflow information
"""
retries=10000
while retries:
try:
request = requestManagerGet(url,'/reqmgr2/data/request?name='+workflow)
return request['result'][0][workflow]
except:
time.sleep(1)
retries -=1
return None
def isRequestMgr2Request(url, workflow):
result = getWorkflowInfo(url, workflow)
return result.get("ReqMgr2Only", False)
def getWorkloadCache(url, workflow):
"""
Retrieves the ReqMgr Workfload Cache
"""
request = requestManagerGet(url, '/couchdb/reqmgr_workload_cache/'+workflow)
return request
def getWorkflowStatus(url, workflow):
"""
Retrieves workflow status
"""
request = getWorkflowInfo(url,workflow)
status = request['RequestStatus']
return status
def getWorkflowType(url, workflow):
request = getWorkflowInfo(url,workflow)
requestType = request['RequestType']
return requestType
def getWorkflowSubType(url, workflow):
request = getWorkflowInfo(url,workflow)
if 'SubRequestType' in request:
requestSubType=request['SubRequestType']
return requestSubType
else:
return None
def getWorkflowPriority(url, workflow):
request = getWorkflowInfo(url,workflow)
if 'RequestPriority' in request:
return request['RequestPriority']
else:
return 0
def getRunWhitelist(url, workflow):
request = getWorkflowInfo(url,workflow)
runWhitelist=request['RunWhitelist']
return runWhitelist
def getBlockWhitelist(url, workflow):
request = getWorkflowInfo(url,workflow)
BlockWhitelist=request['BlockWhitelist']
return BlockWhitelist
def getInputDataSet(url, workflow):
request = getWorkflowInfo(url,workflow)
inputDataSets=request['InputDataset']
if len(inputDataSets)<1:
#print "No InputDataSet for workflow " +workflow
return None
else:
return inputDataSets
def outputdatasetsWorkflow(url, workflow):
"""
returns the output datasets for a given workfow
"""
results = requestManagerGet(url,'/reqmgr2/data/request?name='+workflow)['result']
request = results[0][workflow]
datasets = []
if "OutputDatasets" in request:
datasets.extend(request['OutputDatasets'])
if "TaskChain" in request:
for num in range(request['TaskChain']):
if"OutputDatasets" in request["Task%i" % (num+1)]:
datasets.extend(request['OutputDatasets'])
if "StepChain" in request:
for num in range(request['StepChain']):
if "OutputDatasets" in request["Step%i" % (num+1)]:
datasets.extend(request['OutputDatasets'])
return datasets
def getRequestTeam(url, workflow):
"""
Retrieves the team on which the wf is assigned
"""
request = getWorkflowInfo(url,workflow)
if 'Teams' not in request:
return 'NoTeam'
teams = request['Teams']
if len(teams)<1:
return 'NoTeam'
else:
return teams[0]
def getInputEvents(url, workflow):
"""
Gets the inputs events of a given workflow
depending of the kind of workflow
TODO this can be replaced by getting the info from the workload cache
"""
request = getWorkflowInfo(url,workflow)
requestType=request['RequestType']
#if request is montecarlo or Step0, the numer of
#input events is by the requsted events
if requestType == 'MonteCarlo' or requestType == 'LHEStepZero':
if 'RequestNumEvents' in request:
if request['RequestNumEvents']>0:
return request['RequestNumEvents']
if 'RequestSizeEvents' in request:
return request['RequestSizeEvents']
else:
return 0
if requestType == 'TaskChain':
return getInputEventsTaskChain(request)
#if request is not montecarlo, then we need to check the size
#of input datasets
#This loops fixes the white and blacklists in the workflow
#information,
for listitem in ["RunWhitelist", "RunBlacklist",
"BlockWhitelist", "BlockBlacklist"]:
if listitem in request:
#if empty
if request[listitem]=='[]' or request[listitem]=='':
request[listitem]=[]
#if there is not a list but some elements it creates a list
if type(request[listitem]) is not list:
# if doesn't contain "[" is a single block
if '[' not in request[listitem]:
#wrap in a list
request[listitem] = [request[listitem]]
#else parse a list
else:
request[listitem]= eval(request[listitem])
#if not, an empty list will do
else:
request[listitem]=[]
inputDataSet=request['InputDataset']
#it the request is rereco, we valiate white/black lists
if requestType=='ReReco':
# if there is block whte list, count only the selected block
if request['BlockWhitelist']:
events = dbs3.getEventCountDataSetBlockList(inputDataSet,request['BlockWhitelist'])
# if there is block black list, substract them from the total
if request['BlockBlacklist']:
events = (dbs3.getEventCountDataSet(inputDataSet) -
dbs3.getEventCountDataSet(inputDataSet,request['BlockBlacklist']))
return events
# same if a run whitelist
if request['RunWhitelist']:
events = dbs3.getEventCountDataSetRunList(inputDataSet, request['RunWhitelist'])
return events
# otherwize, the full lumi count
else:
events = dbs3.getEventCountDataSet(inputDataSet)
return events
events = dbs3.getEventCountDataSet(inputDataSet)
# if black list, subsctract them
if request['BlockBlacklist']:
events=events-dbs3.getEventCountDataSetBlockList(inputDataSet, request['BlockBlacklist'])
# if white list, only the ones in the whitelist.
if request['RunWhitelist']:
events=dbs3.getEventCountDataSetRunList(inputDataSet, request['RunWhitelist'])
# if white list of blocks
if request['BlockWhitelist']:
events=dbs3.getEventCountDataSetBlockList(inputDataSet, request['BlockWhitelist'])
#TODO delete FilterEfficiency from here. TEST
#if 'FilterEfficiency' in request:
#return float(request['FilterEfficiency'])*events
#else:
return events
def getInputLumis(url, workflow):
"""
Gets the input lumis of a given workflow
depending of the kind of workflow
TODO this can be replaced by getting it from the workload cache
"""
request = getWorkflowInfo(url,workflow)
requestType=request['RequestType']
#if request is montecarlo or Step0, the numer of
#input events is by the requsted events
if requestType == 'MonteCarlo' or requestType == 'LHEStepZero':
raise Exception("This request has no input dataset")
if requestType == 'TaskChain':
return Exception("Not implemented yet")
#if request is not montecarlo, then we need to check the size
#of input datasets
#This loops fixes the white and blacklists in the workflow
#information,
for listitem in ["RunWhitelist", "RunBlacklist",
"BlockWhitelist", "BlockBlacklist"]:
if listitem in request:
#if empty
if request[listitem]=='[]' or request[listitem]=='':
request[listitem]=[]
#if there is not a list but some elements it creates a list
if type(request[listitem]) is not list:
# if doesn't contain "[" is a single block
if '[' not in request[listitem]:
#wrap in a list
request[listitem] = [request[listitem]]
#else parse a list
else:
request[listitem]= eval(request[listitem])
#if not, an empty list will do
else:
request[listitem]=[]
inputDataSet=request['InputDataset']
totalLumis = dbs3.getLumiCountDataSet(inputDataSet)
#it the request is rereco, we valiate white/black lists
if requestType=='ReReco':
# if there is block whte list, count only the selected block
if request['BlockWhitelist']:
lumis = dbs3.getLumiCountDataSetBlockList(inputDataSet,request['BlockWhitelist'])
# if there is block black list, substract them from the total
if request['BlockBlacklist']:
lumis = (totalLumis -
dbs3.getLumiCountDataSetBlockList(inputDataSet,request['BlockBlacklist']))
return lumis
# same if a run whitelist
if request['RunWhitelist']:
lumis = dbs3.getLumiCountDataSetRunList(inputDataSet, request['RunWhitelist'])
return lumis
# otherwize, the full lumi count
else:
lumis = totalLumis
return lumis
lumis = dbs3.getLumiCountDataSet(inputDataSet)
# if black list, subsctract them
if request['BlockBlacklist']:
lumis = totalLumis - dbs3.getLumiCountDataSetBlockList(inputDataSet, request['BlockBlacklist'])
# if white list, only the ones in the whitelist.
if request['RunWhitelist']:
lumis = totalLumis.getLumiCountDataSetRunList(inputDataSet, request['RunWhitelist'])
# if white list of blocks
if request['BlockWhitelist']:
lumis = dbs3.getLumiCountDataSetBlockList(inputDataSet, request['BlockWhitelist'])
return lumis
def retrieveSchema(workflowName, reqmgrCouchURL = "https://cmsweb.cern.ch/couchdb/reqmgr_workload_cache"):
"""
Creates the cloned specs for the original request
Updates parameters
"""
from WMCore.WMSpec.WMWorkload import WMWorkloadHelper
specURL = os.path.join(reqmgrCouchURL, workflowName, "spec")
helper = WMWorkloadHelper()
helper.load(specURL)
return helper
def getOutputEvents(url, workflow, dataset):
"""
Gets the output events depending on the type
of the request
"""
# request = getWorkflowInfo(url, workflow)
return dbs3.getEventCountDataSet(dataset)
def getFilterEfficiency(url, workflow, task=None):
"""
Gets the filter efficiency of a given request.
It can be used for the filter efficiency inside a given
Task. Returns None if the request has no filter efficiency.
"""
request = getWorkflowInfo(url, workflow)
if request["RequestType"] == "TaskChain":
#get the task with the given input dataset
if task in request:
if 'FilterEfficiency' in request[task]:
filterEff = float(request[task]['FilterEfficiency'])
else:
filterEff = None
return filterEff
#if not found
return None
else:
if 'FilterEfficiency' in request:
return float(request['FilterEfficiency'])
else:
return None
def getOutputLumis(url, workflow, dataset, skipInvalid=False):
"""
Gets the output lumis depending on the type
of the request
"""
# request = getWorkflowInfo(url, workflow)
return dbs3.getLumiCountDataSet(dataset, skipInvalid)
def assignWorkflow(url, workflowname, team, parameters ):
#local import so it doesn't screw with all other stuff
from utils import workflowInfo
defaults = copy.deepcopy( assignWorkflow.defaults )
defaults["Team"+team] = "checked"
defaults["checkbox"+workflowname] = "checked"
from utils import workflowInfo
wf = workflowInfo(url, workflowname)
# set the maxrss watchdog to what is specified in the request
defaults['MaxRSS'] = wf.request['Memory']*1024
defaults.update( parameters )
#if ('Multicore' in wf.request and wf.request['Multicore']>1):
# defaults['MaxRSS'] = int((wf.request['Memory']*1024+10) * 1.5 * wf.request['Multicore'])
# defaults['MaxVSize'] = int(10*defaults['MaxRSS'])
pop_useless = ['AcquisitionEra','ProcessingString']
for what in pop_useless:
if defaults[what] == None:
defaults.pop(what)
if not set(assignWorkflow.mandatories).issubset( set(parameters.keys())):
print "There are missing parameters"
print list(set(assignWorkflow.mandatories) - set(parameters.keys()))
return False
if wf.request['RequestType'] in ['ReDigi','ReReco']:
defaults['Dashboard'] = 'reprocessing'
elif 'SubRequestType' in wf.request and wf.request['SubRequestType'] in ['ReDigi']:
defaults['Dashboard'] = 'reprocessing'
if defaults['SiteBlacklist'] and defaults['SiteWhitelist']:
defaults['SiteWhitelist'] = list(set(defaults['SiteWhitelist']) - set(defaults['SiteBlacklist']))
defaults['SiteBlacklist'] = []
if not defaults['SiteWhitelist']:
print "Cannot assign with no site whitelist"
return False
for aux in assignWorkflow.auxiliaries:
if aux in defaults:
par = defaults.pop( aux )
if aux == 'EventsPerJob':
wf = workflowInfo(url, workflowname)
t = wf.firstTask()
par = int(float(par))
params = wf.getSplittings()[0]
if par < params['events_per_job']:
params.update({"requestName":workflowname,
"splittingTask" : '/%s/%s'%(workflowname,t),
"events_per_job": par,
"splittingAlgo":"EventBased"})
print setWorkflowSplitting(url, workflowname, params)
elif aux == 'EventsPerLumi':
wf = workflowInfo(url, workflowname)
t = wf.firstTask()
params = wf.getSplittings()[0]
if params['splittingAlgo'] != 'EventBased':
print "Ignoring changing events per lumi for",params['splittingAlgo']
continue
(_,prim,_,_) = wf.getIO()
if prim:
print "Ignoring changing events per lumi for wf that take input"
continue
if str(par).startswith('x'):
multiplier = float(str(par).replace('x',''))
par = int(params['events_per_lumi'] * multiplier)
else:
if 'FilterEfficiency' in wf.request and wf.request['FilterEfficiency']:
par = int(float(par)/wf.request['FilterEfficiency'])
else:
par = int(float(str(par)))
params.update({"requestName":workflowname,
"splittingTask" : '/%s/%s'%(workflowname,t),
"events_per_lumi": par})
print setWorkflowSplitting(url, workflowname, params)
elif aux == 'SplittingAlgorithm':
wf = workflowInfo(url, workflowname)
### do it for all major tasks
#for (t,params) in wf.getTaskAndSplittings():
# params.update({"requestName":workflowname,
# "splittingTask" : '/%s/%s'%(workflowname,t),
# "splittingAlgo" : par})
# setWorkflowSplitting(url, workflowname, params)
t = wf.firstTask()
params = wf.getSplittings()[0]
params.update({"requestName":workflowname,
"splittingTask" : '/%s/%s'%(workflowname,t),
"splittingAlgo" : par})
#swap values
if "avg_events_per_job" in params and not "events_per_job" in params:
params['events_per_job' ] = params.pop('avg_events_per_job')
print params
print setWorkflowSplitting(url, workflowname, params)
elif aux == 'LumisPerJob':
wf = workflowInfo(url, workflowname)
t = wf.firstTask()
#params = wf.getSplittings()[0]
params = {"requestName":workflowname,
"splittingTask" : '/%s/%s'%(workflowname,t),
"lumis_per_job" : int(par),
"halt_job_on_file_boundaries" : True,
"splittingAlgo" : "LumiBased"}
print setWorkflowSplitting(url, workflowname, params)
else:
print "No action for ",aux
if not 'execute' in defaults or not defaults['execute']:
print json.dumps( defaults ,indent=2)
return False
else:
defaults.pop('execute')
print json.dumps( defaults ,indent=2)
res = setWorkflowAssignment(url, workflowname, defaults)
if res:
print 'Assigned workflow:',workflowname,'to site:',defaults['SiteWhitelist'],'and team',team
return True
else:
print "error in assigning",workflowname
return False
assignWorkflow.defaults= {
"action": "Assign",
"SiteBlacklist": [],
"TrustSitelists" : False,
"TrustPUSitelists" : False,
#"useSiteListAsLocation" : False,
"UnmergedLFNBase": "/store/unmerged",
"MinMergeSize": 2147483648,
"MaxMergeSize": 4294967296,
"MaxMergeEvents" : 50000,
'BlockCloseMaxEvents' : 2000000,
"MaxRSS" : 3000000,
"MaxVSize": 4394967000,
"maxVSize": 4394967000,
"Dashboard": "production",
"SoftTimeout" : 159600,
"GracePeriod": 300,
'CustodialSites' : [], ## make a custodial copy of the output there
"CustodialSubType" : 'Replica', ## move will screw it over ?
'NonCustodialSites' : [],
"NonCustodialSubType" : 'Replica', ## that's the default, but let's be sure
'AutoApproveSubscriptionSites' : [],
#'Multicore' : 1
}
assignWorkflow.mandatories = ['SiteWhitelist',
'AcquisitionEra',
'ProcessingVersion',
'ProcessingString',
'MergedLFNBase',
#'CustodialSites', ## make a custodial copy of the output there
#'SoftTimeout',
#'BlockCloseMaxEvents',
#'MinMergeSize',
#'MaxMergeEvents',
#'MaxRSS'
]
assignWorkflow.auxiliaries = [ 'SplittingAlgorithm',
'EventsPerJob',
'EventsPerLumi',
'LumisPerJob',
]
assignWorkflow.keys = assignWorkflow.mandatories+assignWorkflow.defaults.keys() + assignWorkflow.auxiliaries
def changePriorityWorkflow(url, workflowname, priority):
"""
Change the priority of a workflow
"""
if isRequestMgr2Request(url, workflowname):
params = {"RequestPriority" : priority}
data = requestManagerPut(url,"/reqmgr2/data/request/%s"%workflowname, params)
else:
params = {workflowname + ":status": "", workflowname + ":priority": str(priority)}
data = requestManager1Post(url, "/reqmgr/view/doAdmin", params)
def forceCompleteWorkflow(url, workflowname):
"""
Moves a workflow from running-closed to force-complete
"""
if isRequestMgr2Request(url, workflowname):
params = {"RequestStatus" : "force-complete"}
data = requestManagerPut(url,"/reqmgr2/data/request/%s"%workflowname, params)
else:
params = {"requestName" : workflowname,"status" : "force-complete"}
data = requestManager1Put(url,"/reqmgr/reqMgr/request", params)
return data
def closeOutWorkflow(url, workflowname, cascade=False):
"""
Closes out a workflow by changing the state to closed-out
This does not care about cascade workflows
"""
if isRequestMgr2Request(url, workflowname):
params = {"RequestStatus" : "closed-out",
"cascade": cascade}
data = requestManagerPut(url,"/reqmgr2/data/request/%s"%workflowname, params)
else:
if cascade:
params = {"requestName" : workflowname,"cascade" : cascade}
data = requestManager1Post(url,"/reqmgr/reqMgr/closeout", params)
else:
params = {"requestName" : workflowname,"status" : "closed-out"}
data = requestManager1Put(url,"/reqmgr/reqMgr/request", params)
return data
def closeOutWorkflowCascade(url, workflowname):
return closeOutWorkflow(url, workflowname, True)
def announceWorkflow(url, workflowname, cascade=False):
"""
Sets a workflow state to announced
This does not care about cascade workflows
"""
if isRequestMgr2Request(url, workflowname):
params = {"RequestStatus" : "announced",
"cascade": cascade}
data = requestManagerPut(url,"/reqmgr2/data/request/%s"%workflowname, params)
else:
if cascade:
params = {"requestName" : workflowname,"cascade" : cascade}
data = requestManager1Post(url,"/reqmgr/reqMgr/announce", params)
else: