forked from DIRACGrid/DIRAC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dirac.py
executable file
·2549 lines (2147 loc) · 101 KB
/
Dirac.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
"""
DIRAC API Class
All DIRAC functionality is exposed through the DIRAC API and this
serves as a source of documentation for the project via EpyDoc.
The DIRAC API provides the following functionality:
- A transparent and secure way for users
to submit jobs to the Grid, monitor them and
retrieve outputs
- Interaction with Grid storage and file catalogues
via the DataManagement public interfaces (more to be added)
- Local execution of workflows for testing purposes.
"""
import glob
import io
import os
import re
import shlex
import shutil
import sys
import tarfile
import tempfile
import time
import datetime
from urllib.parse import unquote
import DIRAC
from DIRAC import gConfig, gLogger, S_OK, S_ERROR
from DIRAC.Core.Base.API import API
from DIRAC.Core.Base.Client import Client
from DIRAC.Core.Utilities.File import mkDir
from DIRAC.Core.Utilities.List import breakListIntoChunks
from DIRAC.Core.Utilities.SiteSEMapping import getSEsForSite
from DIRAC.Core.Utilities.PrettyPrint import printTable, printDict
from DIRAC.Core.Utilities.ClassAd.ClassAdLight import ClassAd
from DIRAC.Core.Utilities.Subprocess import systemCall
from DIRAC.Core.Utilities.ModuleFactory import ModuleFactory
from DIRAC.ConfigurationSystem.Client.PathFinder import getSystemSection, getServiceURL
from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations
from DIRAC.Interfaces.API.JobRepository import JobRepository
from DIRAC.DataManagementSystem.Client.DataManager import DataManager
from DIRAC.Resources.Storage.StorageElement import StorageElement
from DIRAC.Resources.Catalog.FileCatalog import FileCatalog
from DIRAC.WorkloadManagementSystem.Client import JobStatus
from DIRAC.WorkloadManagementSystem.Client.WMSClient import WMSClient
from DIRAC.WorkloadManagementSystem.Client.SandboxStoreClient import SandboxStoreClient
from DIRAC.WorkloadManagementSystem.Client.JobMonitoringClient import JobMonitoringClient
COMPONENT_NAME = "DiracAPI"
try:
# Python 2: "file" is built-in
file_types = file, io.IOBase
except NameError:
# Python 3: "file" fully replaced with IOBase
file_types = (io.IOBase,)
def parseArguments(args):
argList = []
for arg in args:
argList += [a.strip() for a in arg.split(",") if a.strip()]
return argList
class Dirac(API):
"""
DIRAC API Class
"""
#############################################################################
def __init__(self, withRepo=False, repoLocation="", useCertificates=False, vo=None):
"""Internal initialization of the DIRAC API."""
super().__init__()
self.section = "/LocalSite/"
self.jobRepo = False
if withRepo:
self.jobRepo = JobRepository(repoLocation)
if not self.jobRepo.isOK():
gLogger.error("Unable to write to supplied repository location")
self.jobRepo = False
self.useCertificates = useCertificates
# Determine the default file catalog
self.defaultFileCatalog = gConfig.getValue(self.section + "/FileCatalog", None)
self.vo = vo
def _checkFileArgument(self, fnList, prefix=None, single=False):
if prefix is None:
prefix = "LFN"
if isinstance(fnList, str):
otherPrefix = "LFN:" if prefix == "PFN" else "PFN:"
if otherPrefix in fnList:
return self._errorReport("Expected %s string, not %s") % (prefix, otherPrefix)
return S_OK(fnList.replace(f"{prefix}:", ""))
elif isinstance(fnList, list):
if single:
return self._errorReport(f"Expected single {prefix} string")
try:
return S_OK([fn.replace(f"{prefix}:", "") for fn in fnList])
except Exception as x:
return self._errorReport(str(x), f"Expected strings in list of {prefix}s")
else:
return self._errorReport(f"Expected single string or list of strings for {prefix}(s)")
def _checkJobArgument(self, jobID, multiple=False):
try:
if isinstance(jobID, (str, int)):
jobID = int(jobID)
if multiple:
jobID = [jobID]
elif isinstance(jobID, (list, dict)):
if multiple:
jobID = [int(job) for job in jobID]
else:
return self._errorReport("Expected int or string, not list")
return S_OK(jobID)
except Exception as x:
return self._errorReport(
str(x), f"Expected {'(list of) '} integer or string for existing jobID" if multiple else ""
)
#############################################################################
# Repository specific methods
#############################################################################
def getRepositoryJobs(self, printOutput=False):
"""Retrieve all the jobs in the repository
Example Usage:
>>> print(dirac.getRepositoryJobs())
{'OK': True, 'Value': [1,2,3,4]}
:return: S_OK,S_ERROR
"""
if not self.jobRepo:
gLogger.warn("No repository is initialised")
return S_OK()
jobIDs = list(self.jobRepo.readRepository()["Value"])
if printOutput:
print(self.pPrint.pformat(jobIDs))
return S_OK(jobIDs)
def monitorRepository(self, printOutput=False):
"""Monitor the jobs present in the repository
Example Usage:
>>> print(dirac.monitorRepository())
{'OK': True, 'Value': ''}
:returns: S_OK,S_ERROR
"""
if not self.jobRepo:
gLogger.warn("No repository is initialised")
return S_OK()
jobs = self.jobRepo.readRepository()["Value"]
jobIDs = list(jobs)
res = self.getJobStatus(jobIDs)
if not res["OK"]:
return self._errorReport(res["Message"], "Failed to get status of jobs from WMS")
statusDict = {}
for jobDict in jobs.values():
state = jobDict.get("State", "Unknown")
statusDict[state] = statusDict.setdefault(state, 0) + 1
if printOutput:
print(self.pPrint.pformat(statusDict))
return S_OK(statusDict)
def retrieveRepositorySandboxes(self, requestedStates=None, destinationDirectory=""):
"""Obtain the output sandbox for the jobs in requested states in the repository
Example Usage:
>>> print(dirac.retrieveRepositorySandboxes(requestedStates=['Done','Failed'],destinationDirectory='sandboxes'))
{'OK': True, 'Value': ''}
:param requestedStates: List of jobs states to be considered
:type requestedStates: list of strings
:param destinationDirectory: The target directory
to place sandboxes (each jobID will have a directory created beneath this)
:type destinationDirectory: string
:returns: S_OK,S_ERROR
"""
if not self.jobRepo:
gLogger.warn("No repository is initialised")
return S_OK()
if requestedStates is None:
requestedStates = [
JobStatus.DONE,
JobStatus.FAILED,
JobStatus.COMPLETED,
] # because users dont care about completed
jobs = self.jobRepo.readRepository()["Value"]
for jobID in sorted(jobs):
jobDict = jobs[jobID]
if jobDict.get("State") in requestedStates:
# # Value of 'Retrieved' is a string, e.g. '0' when read from file
if not int(jobDict.get("Retrieved")):
res = self.getOutputSandbox(jobID, destinationDirectory)
if not res["OK"]:
return res
return S_OK()
def retrieveRepositoryData(self, requestedStates=None, destinationDirectory=""):
"""Obtain the output data for the jobs in requested states in the repository
Example Usage:
>>> print(dirac.retrieveRepositoryData(requestedStates=['Done'],destinationDirectory='outputData'))
{'OK': True, 'Value': ''}
:param requestedStates: List of jobs states to be considered
:type requestedStates: list of strings
:param destinationDirectory: The target directory to place sandboxes (a directory is created for each JobID)
:type destinationDirectory: string
:returns: S_OK,S_ERROR
"""
if not self.jobRepo:
gLogger.warn("No repository is initialised")
return S_OK()
if requestedStates is None:
requestedStates = ["Done"]
jobs = self.jobRepo.readRepository()["Value"]
for jobID in sorted(jobs):
jobDict = jobs[jobID]
if jobDict.get("State") in requestedStates:
# # Value of 'OutputData' is a string, e.g. '0' when read from file
if not int(jobDict.get("OutputData")):
destDir = jobID
if destinationDirectory:
destDir = f"{destinationDirectory}/{jobID}"
self.getJobOutputData(jobID, destinationDir=destDir)
return S_OK()
def removeRepository(self):
"""Removes the job repository and all sandboxes and output data retrieved
Example Usage:
>>> print(dirac.removeRepository())
{'OK': True, 'Value': ''}
:returns: S_OK,S_ERROR
"""
if not self.jobRepo:
gLogger.warn("No repository is initialised")
return S_OK()
jobs = self.jobRepo.readRepository()["Value"]
for jobID in sorted(jobs):
jobDict = jobs[jobID]
if os.path.exists(jobDict.get("Sandbox", "")):
shutil.rmtree(jobDict["Sandbox"], ignore_errors=True)
if "OutputFiles" in jobDict:
for fileName in eval(jobDict["OutputFiles"]):
if os.path.exists(fileName):
os.remove(fileName)
self.deleteJob(sorted(jobs))
os.remove(self.jobRepo.getLocation()["Value"])
self.jobRepo = False
return S_OK()
def resetRepository(self, jobIDs=None):
"""Reset all the status of the (optionally supplied) jobs in the repository
Example Usage:
>>> print(dirac.resetRepository(jobIDs = [1111,2222,'3333']))
{'OK': True, 'Value': ''}
:returns: S_OK,S_ERROR
"""
if not self.jobRepo:
gLogger.warn("No repository is initialised")
return S_OK()
if jobIDs is None:
jobIDs = []
if not isinstance(jobIDs, list):
return self._errorReport("The jobIDs must be a list of (strings or ints).")
self.jobRepo.resetRepository(jobIDs=jobIDs)
return S_OK()
#############################################################################
def submitJob(self, job, mode="wms"):
"""Submit jobs to DIRAC (by default to the Workload Management System).
These can be either:
- Instances of the Job Class
- VO Application Jobs
- Inline scripts
- Scripts as executables
- Scripts inside an application environment
- JDL File
- JDL String
Example usage:
>>> print(dirac.submitJob(job))
{'OK': True, 'Value': '12345'}
:param job: Instance of Job class or JDL string
:type job: ~DIRAC.Interfaces.API.Job.Job or str
:param mode: Submit job to WMS with mode = 'wms' (default),
'local' to run the workflow locally
:type mode: str
:returns: S_OK,S_ERROR
"""
self.__printInfo()
if isinstance(job, str):
if os.path.exists(job):
self.log.verbose(f"Found job JDL file {job}")
with open(job) as fd:
jdlAsString = fd.read()
else:
self.log.verbose("Job is a JDL string")
jdlAsString = job
jobDescriptionObject = None
else: # we assume it is of type "DIRAC.Interfaces.API.Job.Job"
try:
formulationErrors = job.errorDict
except AttributeError as x:
self.log.verbose(f"Could not obtain job errors:{x}")
formulationErrors = {}
if formulationErrors:
for method, errorList in formulationErrors.items(): # can be an iterator
self.log.error(">>>> Error in {}() <<<<\n{}".format(method, "\n".join(errorList)))
return S_ERROR(formulationErrors)
# Run any VO specific checks if desired prior to submission, this may or may not be overridden
# in a derived class for example
try:
result = self.preSubmissionChecks(job, mode)
if not result["OK"]:
self.log.error(f"Pre-submission checks failed for job with message: \"{result['Message']}\"")
return result
except Exception as x:
msg = f'Error in VO specific function preSubmissionChecks: "{x}"'
self.log.error(msg)
return S_ERROR(msg)
jobDescriptionObject = io.StringIO(job._toXML()) # pylint: disable=protected-access
jdlAsString = job._toJDL(jobDescriptionObject=jobDescriptionObject) # pylint: disable=protected-access
if mode.lower() == "local":
result = self.runLocal(job)
elif mode.lower() == "wms":
self.log.verbose("Will submit job to WMS") # this will happen by default anyway
result = WMSClient(useCertificates=self.useCertificates).submitJob(jdlAsString, jobDescriptionObject)
if not result["OK"]:
self.log.error("Job submission failure", result["Message"])
elif self.jobRepo:
jobIDList = result["Value"]
if not isinstance(jobIDList, list):
jobIDList = [jobIDList]
for jobID in jobIDList:
result = self.jobRepo.addJob(jobID, "Submitted")
return result
#############################################################################
def __cleanTmp(self, cleanPath):
"""Remove tmp file or directory"""
if not cleanPath:
return
if os.path.isfile(cleanPath):
os.unlink(cleanPath)
return
if os.path.isdir(cleanPath):
shutil.rmtree(cleanPath, ignore_errors=True)
return
self.__printOutput(sys.stdout, f"Could not remove {str(cleanPath)}")
return
#############################################################################
def preSubmissionChecks(self, job, mode):
"""Internal function. The pre-submission checks method allows VOs to
make their own checks before job submission. To make use of this the
method should be overridden in a derived VO-specific Dirac class.
"""
return S_OK("Nothing to do")
#############################################################################
def getInputDataCatalog(self, lfns, siteName="", fileName="pool_xml_catalog.xml", ignoreMissing=False):
"""This utility will create a pool xml catalogue slice for the specified LFNs using
the full input data resolution policy plugins for the VO.
If not specified the site is assumed to be the DIRAC.siteName() from the local
configuration. The fileName can be a full path.
Example usage:
>>> print(getInputDataCatalog('/lhcb/a/b/c/00001680_00000490_5.dst',None,'myCat.xml'))
{'Successful': {'<LFN>': {'pfntype': 'ROOT', 'protocol': 'SRM2',
'pfn': '<PFN>', 'turl': '<TURL>', 'guid': '3E3E097D-0AC0-DB11-9C0A-00188B770645',
'se': 'CERN-disk'}}, 'Failed': [], 'OK': True, 'Value': ''}
:param lfns: Logical File Name(s) to query
:type lfns: LFN str or python:list []
:param siteName: DIRAC site name
:type siteName: string
:param fileName: Catalogue name (can include path)
:type fileName: string
:returns: S_OK,S_ERROR
"""
ret = self._checkFileArgument(lfns, "LFN")
if not ret["OK"]:
return ret
lfns = ret["Value"]
if not siteName:
siteName = DIRAC.siteName()
if ignoreMissing:
self.log.verbose("Ignore missing flag is enabled")
localSEList = getSEsForSite(siteName)
if not localSEList["OK"]:
return localSEList
self.log.verbose(localSEList)
inputDataPolicy = Operations().getValue("InputDataPolicy/InputDataModule")
if not inputDataPolicy:
return self._errorReport("Could not retrieve /DIRAC/Operations/InputDataPolicy/InputDataModule for VO")
self.log.info(f"Attempting to resolve data for {siteName}")
self.log.verbose("%s" % ("\n".join(lfns)))
replicaDict = self.getReplicasForJobs(lfns)
if not replicaDict["OK"]:
return replicaDict
catalogFailed = replicaDict["Value"].get("Failed", {})
guidDict = self.getLfnMetadata(lfns)
if not guidDict["OK"]:
return guidDict
for lfn, reps in replicaDict["Value"]["Successful"].items(): # can be an iterator
guidDict["Value"]["Successful"][lfn].update(reps)
resolvedData = guidDict
diskSE = gConfig.getValue(self.section + "/DiskSE", ["-disk", "-DST", "-USER", "-FREEZER"])
tapeSE = gConfig.getValue(self.section + "/TapeSE", ["-tape", "-RDST", "-RAW"])
# Add catalog path / name here as well as site name to override the standard policy of resolving automatically
configDict = {
"JobID": None,
"LocalSEList": localSEList["Value"],
"DiskSEList": diskSE,
"TapeSEList": tapeSE,
"SiteName": siteName,
"CatalogName": fileName,
}
self.log.verbose(configDict)
argumentsDict = {"FileCatalog": resolvedData, "Configuration": configDict, "InputData": lfns}
if ignoreMissing:
argumentsDict["IgnoreMissing"] = True
self.log.verbose(argumentsDict)
moduleFactory = ModuleFactory()
self.log.verbose(f"Input Data Policy Module: {inputDataPolicy}")
moduleInstance = moduleFactory.getModule(inputDataPolicy, argumentsDict)
if not moduleInstance["OK"]:
self.log.warn("Could not create InputDataModule")
return moduleInstance
module = moduleInstance["Value"]
result = module.execute()
self.log.debug(result)
if not result["OK"]:
if "Failed" in result:
self.log.error("Input data resolution failed for the following files:\n", "\n".join(result["Failed"]))
if catalogFailed:
self.log.error("Replicas not found for the following files:")
for key, value in catalogFailed.items(): # can be an iterator
self.log.error(f"{key} {value}")
if "Failed" in result:
result["Failed"] = list(catalogFailed)
return result
#############################################################################
def runLocal(self, job):
"""Internal function. This method is called by DIRAC API function submitJob(job,mode='Local').
All output files are written to the local directory.
This is a method for running local tests. It skips the creation of a JobWrapper,
but preparing an environment that mimics it.
:param job: a job object
:type job: ~DIRAC.Interfaces.API.Job.Job
"""
self.log.notice("Executing workflow locally")
curDir = os.getcwd()
self.log.info(f"Executing from {curDir}")
jobDir = tempfile.mkdtemp(suffix="_JobDir", prefix="Local_", dir=curDir)
os.chdir(jobDir)
self.log.info(f"Executing job at temp directory {jobDir}")
tmpdir = tempfile.mkdtemp(prefix="DIRAC_")
self.log.verbose(f"Created temporary directory for submission {tmpdir}")
jobXMLFile = tmpdir + "/jobDescription.xml"
self.log.verbose(f"Job XML file description is: {jobXMLFile}")
with open(jobXMLFile, "w+") as fd:
fd.write(job._toXML()) # pylint: disable=protected-access
shutil.copy(jobXMLFile, f"{os.getcwd()}/{os.path.basename(jobXMLFile)}")
res = self.__getJDLParameters(job)
if not res["OK"]:
self.log.error("Could not extract job parameters from job")
return res
parameters = res["Value"]
self.log.debug("Extracted job parameters from JDL", parameters)
arguments = parameters.get("Arguments", "")
# Replace argument placeholders for parametric jobs
# if we have Parameters then we have a parametric job
if "Parameters" in parameters:
for par, value in parameters.items(): # can be an iterator
if par.startswith("Parameters."):
# we just use the first entry in all lists to run one job
parameters[par[len("Parameters.") :]] = value[0]
arguments = arguments % parameters
self.log.verbose(f"Job parameters: {printDict(parameters)}")
inputDataRes = self._getLocalInputData(parameters)
if not inputDataRes["OK"]:
return inputDataRes
inputData = inputDataRes["Value"]
if inputData:
self.log.verbose(f"Job has input data: {inputData}")
localSEList = gConfig.getValue("/LocalSite/LocalSE", "")
if not localSEList:
return self._errorReport("LocalSite/LocalSE should be defined in your config file")
localSEList = localSEList.replace(" ", "").split(",")
self.log.debug(f"List of local SEs: {localSEList}")
inputDataPolicy = Operations().getValue("InputDataPolicy/InputDataModule")
if not inputDataPolicy:
return self._errorReport("Could not retrieve DIRAC/Operations/InputDataPolicy/InputDataModule for VO")
self.log.info(f"Job has input data requirement, will attempt to resolve data for {DIRAC.siteName()}")
self.log.verbose("\n".join(inputData if isinstance(inputData, (list, tuple)) else [inputData]))
replicaDict = self.getReplicasForJobs(inputData)
if not replicaDict["OK"]:
return replicaDict
guidDict = self.getLfnMetadata(inputData)
if not guidDict["OK"]:
return guidDict
for lfn, reps in replicaDict["Value"]["Successful"].items(): # can be an iterator
guidDict["Value"]["Successful"][lfn].update(reps)
resolvedData = guidDict
diskSE = gConfig.getValue(self.section + "/DiskSE", ["-disk", "-DST", "-USER", "-FREEZER"])
tapeSE = gConfig.getValue(self.section + "/TapeSE", ["-tape", "-RDST", "-RAW"])
configDict = {"JobID": None, "LocalSEList": localSEList, "DiskSEList": diskSE, "TapeSEList": tapeSE}
self.log.verbose(configDict)
argumentsDict = {
"FileCatalog": resolvedData,
"Configuration": configDict,
"InputData": inputData,
"Job": parameters,
}
self.log.verbose(argumentsDict)
moduleFactory = ModuleFactory()
moduleInstance = moduleFactory.getModule(inputDataPolicy, argumentsDict)
if not moduleInstance["OK"]:
self.log.warn("Could not create InputDataModule")
return moduleInstance
module = moduleInstance["Value"]
result = module.execute()
if not result["OK"]:
self.log.warn("Input data resolution failed")
return result
softwarePolicy = Operations().getValue("SoftwareDistModule")
if softwarePolicy:
moduleFactory = ModuleFactory()
moduleInstance = moduleFactory.getModule(softwarePolicy, {"Job": parameters})
if not moduleInstance["OK"]:
self.log.warn("Could not create SoftwareDistModule")
return moduleInstance
module = moduleInstance["Value"]
result = module.execute()
if not result["OK"]:
self.log.warn(f"Software installation failed with result:\n{result}")
return result
else:
self.log.verbose("Could not retrieve SoftwareDistModule for VO")
self.log.debug("Looking for resolving the input sandbox, if it is present")
sandbox = parameters.get("InputSandbox")
if sandbox:
self.log.verbose(f"Input Sandbox is {sandbox}")
if isinstance(sandbox, str):
sandbox = [isFile.strip() for isFile in sandbox.split(",")]
for isFile in sandbox:
self.log.debug(f"Resolving Input Sandbox {isFile}")
if isFile.lower().startswith("lfn:"): # isFile is an LFN
isFile = isFile[4:]
# Attempt to copy into job working directory, unless it is already there
if os.path.exists(os.path.join(os.getcwd(), os.path.basename(isFile))):
self.log.debug(f"Input Sandbox {isFile} found in the job directory, no need to copy it")
else:
if os.path.isabs(isFile) and os.path.exists(isFile):
self.log.debug(f"Input Sandbox {isFile} is a file with absolute path, copying it")
shutil.copy(isFile, os.getcwd())
elif os.path.isdir(isFile):
self.log.debug(
f"Input Sandbox {isFile} is a directory, found in the user working directory, copying it"
)
shutil.copytree(isFile, os.path.basename(isFile), symlinks=True)
elif os.path.exists(os.path.join(curDir, os.path.basename(isFile))):
self.log.debug(f"Input Sandbox {isFile} found in the submission directory, copying it")
shutil.copy(os.path.join(curDir, os.path.basename(isFile)), os.getcwd())
elif os.path.exists(os.path.join(tmpdir, isFile)): # if it is in the tmp dir
self.log.debug(f"Input Sandbox {isFile} is a file, found in the tmp directory, copying it")
shutil.copy(os.path.join(tmpdir, isFile), os.getcwd())
else:
self.log.verbose(f"perhaps the file {isFile} is in an LFN, so we attempt to download it.")
getFile = self.getFile(isFile)
if not getFile["OK"]:
self.log.warn(f"Failed to download {isFile} with error: {getFile['Message']}")
return S_ERROR(f"Can not copy InputSandbox file {isFile}")
isFileInCWD = os.getcwd() + os.path.sep + isFile
basefname = os.path.basename(isFileInCWD)
if tarfile.is_tarfile(basefname):
try:
with tarfile.open(basefname, "r") as tf:
for member in tf.getmembers():
tf.extract(member, os.getcwd())
except (tarfile.ReadError, tarfile.CompressionError, tarfile.ExtractError) as x:
return S_ERROR(f"Could not untar or extract {basefname} with exception {repr(x)}")
self.log.info(f"Attempting to submit job to local site: {DIRAC.siteName()}")
# DIRACROOT is used for finding dirac-jobexec in python2 installations
# (it is normally set by the JobWrapper)
# We don't use DIRAC.rootPath as we assume that a DIRAC installation is already done at this point
# DIRAC env variable is only set for python2 installations
if "DIRAC" in os.environ:
os.environ["DIRACROOT"] = os.environ["DIRAC"]
self.log.verbose(f"DIRACROOT = {os.environ['DIRACROOT']}")
if "Executable" in parameters:
executable = os.path.expandvars(parameters["Executable"])
else:
return self._errorReport('Missing job "Executable"')
if "-o LogLevel" in arguments:
dArguments = arguments.split()
logLev = dArguments.index("-o") + 1
dArguments[logLev] = "LogLevel=DEBUG"
arguments = " ".join(dArguments)
else:
arguments += " -o LogLevel=DEBUG"
command = f"{executable} {arguments}"
self.log.info(f"Executing: {command}")
executionEnv = dict(os.environ)
variableList = parameters.get("ExecutionEnvironment")
if variableList:
self.log.verbose("Adding variables to execution environment")
if isinstance(variableList, str):
variableList = [variableList]
for var in variableList:
nameEnv = var.split("=")[0]
valEnv = unquote(var.split("=")[1]) # this is needed to make the value contain strange things
executionEnv[nameEnv] = valEnv
self.log.verbose(f"{nameEnv} = {valEnv}")
result = systemCall(0, cmdSeq=shlex.split(command), env=executionEnv, callbackFunction=self.__printOutput)
if not result["OK"]:
return result
status = result["Value"][0]
self.log.verbose(f"Status after execution is {status}")
# FIXME: if there is an callbackFunction, StdOutput and StdError will be empty soon
outputFileName = parameters.get("StdOutput")
errorFileName = parameters.get("StdError")
if outputFileName:
stdout = result["Value"][1]
if os.path.exists(outputFileName):
os.remove(outputFileName)
self.log.info(f"Standard output written to {outputFileName}")
with open(outputFileName, "w") as outputFile:
print(stdout, file=outputFile)
else:
self.log.warn("Job JDL has no StdOutput file parameter defined")
if errorFileName:
stderr = result["Value"][2]
if os.path.exists(errorFileName):
os.remove(errorFileName)
self.log.verbose(f"Standard error written to {errorFileName}")
with open(errorFileName, "w") as errorFile:
print(stderr, file=errorFile)
sandbox = None
else:
self.log.warn("Job JDL has no StdError file parameter defined")
sandbox = parameters.get("OutputSandbox")
if sandbox:
if isinstance(sandbox, str):
sandbox = [osFile.strip() for osFile in sandbox.split(",")]
for i in sandbox:
globList = glob.glob(i)
for osFile in globList:
if os.path.isabs(osFile):
# if a relative path, it is relative to the user working directory
osFile = os.path.basename(osFile)
# Attempt to copy back from job working directory
if os.path.isdir(osFile):
shutil.copytree(osFile, curDir, symlinks=True)
elif os.path.exists(osFile):
shutil.copy(osFile, curDir)
else:
return S_ERROR(f"Can not copy OutputSandbox file {osFile}")
os.chdir(curDir)
if status: # if it fails, copy content of execution dir in current directory
destDir = os.path.join(curDir, os.path.basename(os.path.dirname(tmpdir)))
self.log.verbose(f"Copying outputs from {tmpdir} to {destDir}")
if os.path.exists(destDir):
shutil.rmtree(destDir)
shutil.copytree(tmpdir, destDir)
self.log.verbose(f"Cleaning up {tmpdir}...")
self.__cleanTmp(tmpdir)
if status:
return S_ERROR(f"Execution completed with non-zero status {status}")
return S_OK("Execution completed successfully")
@staticmethod
def _getLocalInputData(parameters):
"""Resolve input data for locally run jobs.
Here for reason of extensibility
"""
inputData = parameters.get("InputData")
if inputData:
if isinstance(inputData, str):
inputData = [inputData]
return S_OK(inputData)
#############################################################################
@staticmethod
def __printOutput(fd=None, message=""):
"""Internal callback function to return standard output when running locally."""
if fd:
if isinstance(fd, int):
if fd == 0:
print(message, file=sys.stdout)
elif fd == 1:
print(message, file=sys.stderr)
else:
print(message)
elif isinstance(fd, file_types):
print(message, file=fd)
else:
print(message)
#############################################################################
def listCatalogDirectory(self, directoryLFN, printOutput=False):
"""lists the contents of a directory in the DFC
Example usage:
>>> res = dirac.listCatalogDir("/lz/data/test", printOutput=True)
Listing content of: /lz/data/test
Subdirectories:
/lz/data/test/reconstructed
/lz/data/test/BACCARAT_release-2.1.1_geant4.9.5.p02
/lz/data/test/BACCARAT_release-2.1.0_geant4.9.5.p02
Files:
/lz/data/test/sites.log
/lz/data/test/sites2.log
>>> print(res)
{'OK': True, 'Value': {'Successful': {'/lz/data/test': {'Files': {'/lz/data/test/sites.log':
{'MetaData': {'Status': 'AprioriGood', 'GUID': 'AD81AD07-3BC0-A9FE-1D82-786C4DC9D380',
'ChecksumType': 'Adler32', 'Checksum': '8b994dd5', 'Size': 1100L, 'UID': 2,
'OwnerGroup': 'lz_production', 'Owner': 'daniela.bauer', 'GID': 24, 'Mode': 509,
'ModificationDate': datetime.datetime(2021, 6, 11, 14, 23, 51),
'CreationDate': datetime.datetime(2021, 6, 11, 14, 23, 51), 'Type': 'File', 'FileID': 27519475L}},
'/lz/data/test/sites2.log': {'MetaData': {'Status': 'AprioriGood',
'GUID': 'AD81AD07-3BC0-A9FE-1D82-786C4DC9D380', 'ChecksumType': 'Adler32', 'Checksum': '8b994dd5',
'Size': 1100L, 'UID': 2, 'OwnerGroup': 'lz_production', 'Owner': 'daniela.bauer', 'GID': 24,
'Mode': 509, 'ModificationDate': datetime.datetime(2021, 6, 16, 15, 26, 21),
'CreationDate': datetime.datetime(2021, 6, 16, 15, 26, 21), 'Type': 'File', 'FileID': 27601076L}}},
'Datasets': {}, 'SubDirs': {'/lz/data/test/reconstructed': True,
'/lz/data/test/BACCARAT_release-2.1.1_geant4.9.5.p02': True,
'/lz/data/test/BACCARAT_release-2.1.0_geant4.9.5.p02': True}, 'Links': {}}}, 'Failed': {}}}
:param directoryLFN: LFN of the directory to be listed
:type directoryLFN: string or list in LFN format
:param printOutput: prints output in a more human readable form
:type printOutput: bool
:returns: S_OK,S_ERROR. S_OK returns a dictionary. Please see the example for its structure.
"""
ret = self._checkFileArgument(directoryLFN, "LFN")
if not ret["OK"]:
return ret
res = FileCatalog().listDirectory(directoryLFN)
if not res["OK"]:
self.log.warn(res["Message"])
return res
if not res["Value"]["Successful"]:
self.log.warn(f"listCatalogDir failed for all LFNs ({directoryLFN}).")
return res
# now deal with the case where *some* of the LFNs are OK
if res["Value"]["Failed"]:
self.log.warn(f"listCatalogDir failed for: {res['Value']['Failed']}")
# do not return, we still want to process the good ones
if printOutput:
# treat a string as array with a single entry
if isinstance(directoryLFN, str):
directoryLFN = [directoryLFN]
for directory in directoryLFN:
if directory in res["Value"]["Successful"]:
print(f"Listing content of: {directory}")
subdirs = res["Value"]["Successful"][directory]["SubDirs"]
files = res["Value"]["Successful"][directory]["Files"]
print("Subdirectories:")
print("\n".join(subdirs))
print("Files:")
print("\n".join(files))
return res
#############################################################################
# def listCatalog( self, directory, printOutput = False ):
# """ Under development.
# Obtain listing of the specified directory.
# """
# rm = ReplicaManager()
# listing = rm.listCatalogDirectory( directory )
# if re.search( '\/$', directory ):
# directory = directory[:-1]
#
# if printOutput:
# for fileKey, metaDict in listing['Value']['Successful'][directory]['Files'].items(): # can be an iterator
# print '#' * len( fileKey )
# print fileKey
# print '#' * len( fileKey )
# print self.pPrint.pformat( metaDict )
#############################################################################
def getReplicas(self, lfns, active=True, preferDisk=False, diskOnly=False, printOutput=False):
"""Obtain replica information from file catalogue client. Input LFN(s) can be string or list.
Example usage:
>>> print(dirac.getReplicas('/lhcb/data/CCRC08/RDST/00000106/0000/00000106_00006321_1.rdst'))
{'OK': True, 'Value': {'Successful': {'/lhcb/data/CCRC08/RDST/00000106/0000/00000106_00006321_1.rdst':
{'CERN-RDST':
'srm://srm-lhcb.cern.ch/castor/cern.ch/grid/lhcb/data/CCRC08/RDST/00000106/0000/00000106_00006321_1.rdst'}},
'Failed': {}}}
:param lfns: Logical File Name(s) to query
:type lfns: LFN str or python:list []
:param active: restrict to only replicas at SEs that are not banned
:type active: boolean
:param preferDisk: give preference to disk replicas if True
:type preferDisk: boolean
:param diskOnly: restrict to only disk replicas if True
:type diskOnly: boolean
:param printOutput: Optional flag to print result
:type printOutput: boolean
:returns: S_OK,S_ERROR
"""
ret = self._checkFileArgument(lfns, "LFN")
if not ret["OK"]:
return ret
lfns = ret["Value"]
start = time.time()
dm = DataManager()
repsResult = dm.getReplicas(lfns, active=active, preferDisk=preferDisk, diskOnly=diskOnly)
timing = time.time() - start
self.log.info(f"Replica Lookup Time: {timing:.2f} seconds ")
self.log.debug(repsResult)
if not repsResult["OK"]:
self.log.warn(repsResult["Message"])
return repsResult
if printOutput:
fields = ["LFN", "StorageElement", "URL"]
records = []
for lfn in repsResult["Value"]["Successful"]:
lfnPrint = lfn
for se, url in repsResult["Value"]["Successful"][lfn].items(): # can be an iterator
records.append((lfnPrint, se, url))
lfnPrint = ""
for lfn in repsResult["Value"]["Failed"]:
records.append((lfn, "Unknown", str(repsResult["Value"]["Failed"][lfn])))
if records:
printTable(fields, records, numbering=False)
else:
self.log.info("No replicas found")
return repsResult
def getReplicasForJobs(self, lfns, diskOnly=False, printOutput=False):
"""Obtain replica information from file catalogue client. Input LFN(s) can be string or list.
Example usage:
>>> print(dirac.getReplicasForJobs('/lhcb/data/CCRC08/RDST/00000106/0000/00000106_00006321_1.rdst'))
{'OK': True, 'Value': {'Successful': {'/lhcb/data/CCRC08/RDST/00000106/0000/00000106_00006321_1.rdst':
{'CERN-RDST':
'srm://srm-lhcb.cern.ch/castor/cern.ch/grid/lhcb/data/CCRC08/RDST/00000106/0000/00000106_00006321_1.rdst'}},
'Failed': {}}}
:param lfns: Logical File Name(s) to query
:type lfns: LFN str or python:list []
:param diskOnly: restrict to only disk replicas if True
:type diskOnly: boolean
:param printOutput: Optional flag to print result
:type printOutput: boolean
:returns: S_OK,S_ERROR
"""
ret = self._checkFileArgument(lfns, "LFN")
if not ret["OK"]:
return ret
lfns = ret["Value"]
start = time.time()
dm = DataManager()
repsResult = dm.getReplicasForJobs(lfns, diskOnly=diskOnly)
timing = time.time() - start
self.log.info(f"Replica Lookup Time: {timing:.2f} seconds ")
self.log.debug(repsResult)
if not repsResult["OK"]:
self.log.warn(repsResult["Message"])
return repsResult
if printOutput:
fields = ["LFN", "StorageElement", "URL"]
records = []
for lfn in repsResult["Value"]["Successful"]:
lfnPrint = lfn
for se, url in repsResult["Value"]["Successful"][lfn].items(): # can be an iterator
records.append((lfnPrint, se, url))
lfnPrint = ""
for lfn in repsResult["Value"]["Failed"]:
records.append((lfn, "Unknown", str(repsResult["Value"]["Failed"][lfn])))
printTable(fields, records, numbering=False)
return repsResult
#############################################################################
def getAllReplicas(self, lfns, printOutput=False):
"""Only differs from getReplicas method in the sense that replicas on banned SEs
will be included in the result.
Obtain replica information from file catalogue client. Input LFN(s) can be string or list.
Example usage:
>>> print(dirac.getAllReplicas('/lhcb/data/CCRC08/RDST/00000106/0000/00000106_00006321_1.rdst'))
{'OK': True, 'Value': {'Successful': {'/lhcb/data/CCRC08/RDST/00000106/0000/00000106_00006321_1.rdst':
{'CERN-RDST':
'srm://srm-lhcb.cern.ch/castor/cern.ch/grid/lhcb/data/CCRC08/RDST/00000106/0000/00000106_00006321_1.rdst'}},
'Failed': {}}}
:param lfns: Logical File Name(s) to query
:type lfns: LFN str or python:list
:param printOutput: Optional flag to print result
:type printOutput: bool
:returns: S_OK,S_ERROR
"""
ret = self._checkFileArgument(lfns, "LFN")
if not ret["OK"]:
return ret
lfns = ret["Value"]