This repository has been archived by the owner on Jan 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathMover.py
5061 lines (4164 loc) · 225 KB
/
Mover.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
# Mover.py
# Used by runJob and pilot to transfer input and output files from and to the local SE
import os
import sys
import commands
import re
import urllib
from xml.dom import minidom
from time import time, sleep
from timed_command import timed_command
from pUtil import createPoolFileCatalog, tolog, addToSkipped, removeDuplicates, dumpOrderedItems,\
hasBeenTransferred, getLFN, makeTransRegReport, readpar, getMaxInputSize, headPilotErrorDiag, getCopysetup,\
getCopyprefixLists, getExperiment, getSiteInformation, stripDQ2FromLFN, extractPattern, dumpFile, updateInputFileWithTURLs, getPilotVersion
from FileHandling import getExtension, getTracingReportFilename, readJSON, getHashedBucketEndpoint, getDirectAccess, useDirectAccessWAN
from FileStateClient import updateFileState, dumpFileStates
from RunJobUtilities import updateCopysetups
from SysLog import sysLog, dumpSysLogTail
# Note: DEFAULT_TIMEOUT and MAX_RETRY are reset in get_data()
MAX_RETRY = 1
MAX_NUMBER_OF_RETRIES = 3
DEFAULT_TIMEOUT = 5*3600/MAX_RETRY # 1h40' if 3 retries # 5 hour total limit on rucio download/upload
from PilotErrors import PilotErrors
from futil import *
import SiteMoverFarm
from configSiteMover import config_sm
PERMISSIONS_DIR = config_sm.PERMISSIONS_DIR
PERMISSIONS_FILE = config_sm.PERMISSIONS_FILE
CMD_CHECKSUM = config_sm.COMMAND_MD5
# Default archival type
ARCH_DEFAULT = config_sm.ARCH_DEFAULT
class replica:
""" Replica """
sfn = None
setname = None
fs = None
filesize = None
csumvalue = None
rse = None
filetype = None
def createZippedDictionary(list1, list2):
""" Created a zipped dictionary from input lists """
# list1 = [a1, a2, ..]
# list2 = [b1, b2, ..]
# -> dict = {a1:b1, a2:b2, ..}
d = None
if len(list1) == len(list2):
try:
d = dict(zip(list1, list2))
except Exception,e:
tolog("Warning: Dictionary creation failed: %s" % str(e))
else:
tolog("Created dictionary: %s" % str(d))
else:
tolog("Warning: Cannot create zipped dictionary using: list1=%s, list2=%s (different lengths)" % (str(list1), str(list2)))
return d
def getProperDatasetNames(realDatasetsIn, prodDBlocks, inFiles):
""" Get all proper dataset names """
dsname = ""
dsdict = {}
rucio_dataset_dictionary = {}
# fill the dataset dictionary
if realDatasetsIn and len(realDatasetsIn) == 1 and realDatasetsIn[0] != 'NULL':
dsname = realDatasetsIn[0]
if not dsdict.has_key(dsname): dsdict[dsname] = []
dsdict[dsname].append(inFiles[0])
elif realDatasetsIn and len(realDatasetsIn) > 1:
for i in range(len(inFiles)):
inFile = inFiles[i]
dsname = realDatasetsIn[i]
if not dsdict.has_key(dsname):
dsdict[dsname] = []
dsdict[dsname].append(inFile)
# finally fill the proper dataset/container dictionary to be used for rucio traces
for i in range(len(inFiles)):
inFile = inFiles[i]
proper_dsname = prodDBlocks[i]
if not rucio_dataset_dictionary.has_key(proper_dsname):
rucio_dataset_dictionary[proper_dsname] = []
rucio_dataset_dictionary[proper_dsname].append(inFile)
return dsname, dsdict, rucio_dataset_dictionary
def getRSE(ddmEndPoints, fileid=0):
"""
Return the ddmEndPoint corresponding to the fileid number.
:param ddmEndPoints: list of ordered ddm endpoints (ddmEndPointIn or ddmEndPointOut)
:return: rse (strings)
"""
try:
rse = ddmEndPoints[fileid]
except Exception, e:
tolog("Failed to get RSE for fileid=%d from ddmEndPoints=%s: %s" % (fileid, str(ddmEndPoints), e))
rse = "unknown"
if rse == "":
tolog("!!WARNING!!1212!! RSE for fileid=%d could not be extracted from ddmEndPoints=%s: empty RSE (reset to unknown)" % (fileid, str(ddmEndPoints)))
rse = "unknown"
return rse
# new mover implementation
def put_data_new(job, jobSite, stageoutTries, log_transfer=False, special_log_transfer=False, workDir=None, pinitdir=""):
"""
Do jobmover.stageout_outfiles or jobmover.stageout_logfiles (if log_transfer=True)
or jobmover.stageout_logfiles_os (if special_log_transfer=True)
:backward compatible return: (rc, pilotErrorDiag, rf, "", filesNormalStageOut, filesAltStageOut)
"""
tolog("Mover put data started [new implementation]")
from PilotErrors import PilotException
from movers import JobMover
from movers.trace_report import TraceReport
si = getSiteInformation(job.experiment)
si.setQueueName(jobSite.computingElement) # WARNING: SiteInformation is singleton: may be used in other functions! FIX me later
workDir = workDir or os.path.dirname(job.workdir)
mover = JobMover(job, si, workDir=workDir, stageoutretry=stageoutTries)
eventType = "put_sm"
if log_transfer:
eventType += '_logs'
if special_log_transfer:
eventType += '_logs_os'
if job.isAnalysisJob():
eventType += "_a"
rse = getRSE(job.ddmEndPointOut) # at this point, get the RSE for the first file in the list, fileid=0
client = getClientVersionString(pinitdir)
mover.trace_report = TraceReport(pq=jobSite.sitename, localSite=rse, remoteSite=rse, dataset="", eventType=eventType, eventVersion=client)
mover.trace_report.init(job)
error = None
try:
do_stageout_func = mover.stageout_logfiles if log_transfer else mover.stageout_outfiles
if special_log_transfer:
do_stageout_func = mover.stageout_logfiles_os
transferred_files, failed_transfers = do_stageout_func()
except PilotException, e:
error = e
except Exception, e:
tolog("ERROR: Mover put data failed [stageout]: exception caught: %s" % e)
import traceback
tolog(traceback.format_exc())
error = PilotException('STAGEOUT FAILED, exception=%s' % e, code=PilotErrors.ERR_STAGEOUTFAILED, state='STAGEOUT_FAILED')
if error:
## send trace
mover.trace_report.update(clientState=error.state or 'STAGEOUT_FAILED', stateReason=error.message, timeEnd=time())
mover.sendTrace(mover.trace_report)
return error.code, error.message, [], "", 0, 0
tolog("Mover put data finished")
# prepare compatible output
# keep track of which files have been copied
fields = [''] * 7 # file info field used by job recovery in OLD compatible format
#errors = []
#for is_success, success_transfers, failed_transfers, exception in output:
# for fdata in success_transfers: # keep track of which files have been copied
# for i,v in enumerate(['surl', 'lfn', 'guid', 'filesize', 'checksum', 'farch', 'pfn']): # farch is not used
# value = fdata.get(v, '')
# if fields[i]:
# fields[i] += '+'
# fields[i] += '%s' % str(value)
# if exception:
# errors.append(str(exception))
# for err in failed_transfers:
# errors.append(str(err))
files = job.outData if not log_transfer else job.logData
if special_log_transfer:
files = job.logSpecialData
not_transferred = [e.lfn for e in files if e.status not in ['transferred']]
if not_transferred:
err_msg = 'STAGEOUT FAILED: not all output files have been copied: remain files=%s, errors=%s' % ('\n'.join(not_transferred), ';'.join([str(ee) for ee in failed_transfers]))
tolog("Mover put data finished: error_msg=%s" % err_msg)
return PilotErrors.ERR_STAGEOUTFAILED, err_msg, [], "", 0, 0
return 0, "", fields, "", len(transferred_files), 0
# new mover implementation
def put_data_es(job, jobSite, stageoutTries, files, workDir=None, activity=None, pinitdir=""):
"""
Do jobmover.stageout_outfiles or jobmover.stageout_logfiles (if log_transfer=True)
or jobmover.stageout_logfiles_os (if special_log_transfer=True)
:backward compatible return: (rc, pilotErrorDiag, rf, "", filesNormalStageOut, filesAltStageOut)
"""
tolog("Mover put data started [new implementation]")
from PilotErrors import PilotException
from movers import JobMover
from movers.trace_report import TraceReport
si = getSiteInformation(job.experiment)
si.setQueueName(jobSite.computingElement) # WARNING: SiteInformation is singleton: may be used in other functions! FIX me later
workDir = workDir or os.path.dirname(job.workdir)
mover = JobMover(job, si, workDir=workDir, stageoutretry=stageoutTries)
eventType = "put_es"
rse = getRSE(job.ddmEndPointOut) # at this point, get the RSE for the first file in the list, fileid=0
client = getClientVersionString(pinitdir)
mover.trace_report = TraceReport(pq=jobSite.sitename, localSite=rse, remoteSite=rse, dataset="", eventType=eventType, eventVersion=client)
mover.trace_report.init(job)
error = None
storageId = None
try:
if not activity:
activity = "es_events"
file = files[0]
if file.storageId and file.storageId != -1:
storageId = file.storageId
copytools = [('objectstore', {'setup': ''})]
else:
copytools = None
transferred_files, failed_transfers = mover.stageout(activity=activity, files=files, copytools=copytools)
except PilotException, e:
error = e
except Exception, e:
tolog("ERROR: Mover put data failed [stageout]: exception caught: %s" % e)
import traceback
tolog(traceback.format_exc())
error = PilotException('STAGEOUT FAILED, exception=%s' % e, code=PilotErrors.ERR_STAGEOUTFAILED, state='STAGEOUT_FAILED')
if error:
## send trace
mover.trace_report.update(clientState=error.state or 'STAGEOUT_FAILED', stateReason=error.message, timeEnd=time())
mover.sendTrace(mover.trace_report)
return error.code, error.message, None
tolog("Mover put data finished")
# prepare compatible output
# keep track of which files have been copied
not_transferred = [e.lfn for e in files if e.status not in ['transferred']]
if not_transferred:
err_msg = 'STAGEOUT FAILED: not all output files have been copied: remain files=%s, errors=%s' % ('\n'.join(not_transferred), ';'.join([str(ee) for ee in failed_transfers]))
tolog("Mover put data finished: error_msg=%s" % err_msg)
return PilotErrors.ERR_STAGEOUTFAILED, err_msg, None
return 0, "", storageId
def getClientVersionString(pinitdir):
"""
:param pinitdir:
:return:
"""
pilot_version = getPilotVersion(pinitdir)
rucio_version = os.environ.get('ATLAS_LOCAL_RUCIOCLIENTS_VERSION', '')
return pilot_version + '+' + rucio_version
# new mover implementation:
# keep the list of input arguments as is for smooth migration
def get_data_new(job,
jobSite,
ins=None, # ignored, not used anymore, use job.inData instead
stageinTries=2,
analysisJob=False, # ignored, not used anymore (use job.isAnalysisJob instead)
usect=True, # ignored, not used anymore
pinitdir="", # not used??
proxycheck=True, # TODO
inputDir="", # for mv mover?? not used??
workDir="", # pilot work dir used to check/update file states
files=None, # input files to stagein
pfc_name="PoolFileCatalog.xml"
):
"""
call the mover and stage-in input files
:backward compatible return: (ec, pilotErrorDiag, None (statusPFCTurl), FAX_dictionary)
"""
tolog("Mover get data started [new implementation]")
# new implementation
from PilotErrors import PilotException
from movers import JobMover
from movers.trace_report import TraceReport
from pUtil import getPilotVersion
si = getSiteInformation(job.experiment)
si.setQueueName(jobSite.computingElement) # WARNING: SiteInformation is singleton: may be used in other functions! FIX me later
mover = JobMover(job, si, workDir=workDir, stageinretry=stageinTries)
eventType = "get_sm"
if job.isAnalysisJob():
eventType += "_a"
rse = getRSE(job.ddmEndPointIn) # at this point, get the RSE for the first file in the list, fileid=0
client = getClientVersionString(pinitdir)
mover.trace_report = TraceReport(pq=jobSite.sitename, localSite=rse, remoteSite=rse, dataset="", eventType=eventType, eventVersion=client)
mover.trace_report.init(job)
error = None
try:
output = mover.stagein(files=files, analyjob=job.isAnalysisJob())
except PilotException, e:
error = e
tolog("!!WARNING!!4545!! Caught exception: %s" % (e))
except Exception, e:
tolog("ERROR: Mover get data failed [stagein]: exception caught: %s" % e)
error = PilotException('STAGEIN FAILED, exception=%s' % e, code=PilotErrors.ERR_STAGEINFAILED, state='STAGEIN_FAILED')
import traceback
tolog(traceback.format_exc())
if error:
## send trace
mover.trace_report.update(clientState=error.state or 'STAGEIN_FAILED', stateReason=error.message, timeEnd=time())
mover.sendTrace(mover.trace_report)
return error.code, error.message, None, {}
tolog("Mover get data finished")
# prepare compatible output
not_transferred = [e.lfn for e in job.inData if e.status not in ['transferred', 'remote_io', 'no_transfer']]
if not_transferred:
return PilotErrors.ERR_STAGEINFAILED, 'STAGEIN FAILED: not all input files have been copied: remain=%s' % '\n'.join(not_transferred), None, {}
tfiles = [e for e in job.inData if e.status == 'transferred']
job.bytesWithoutFAX = reduce(lambda x, y: x + y.filesize, tfiles, 0)
job.filesWithoutFAX = len(tfiles)
job.filesWithFAX = 0
job.bytesWithFAX = 0
# backward compatible dict
FAX_dictionary = dict(N_filesWithFAX=job.filesWithFAX, bytesWithFAX=job.bytesWithFAX,
N_filesWithoutFAX=job.filesWithoutFAX, bytesWithoutFAX=job.bytesWithoutFAX)
#FAX_dictionary['usedFAXandDirectIO'] = False
### reuse usedFAXandDirectIO variable as special meaning attribute to form command option list later
### FIX ME LATER
FAX_dictionary['usedFAXandDirectIO'] = 'newmover'
used_direct_access = [e for e in job.inData if e.status == 'remote_io']
if used_direct_access:
FAX_dictionary['usedFAXandDirectIO'] = 'newmover-directaccess'
# create PoolFileCatalog.xml / PFC.xml
# (turl based for Prefetcher)
files, lfns = {}, []
for fspec in job.inData:
pfn = fspec.lfn
if fspec.status == 'remote_io':
pfn = fspec.turl
files[fspec.guid] = pfn or ''
lfns.append(fspec.lfn)
createPoolFileCatalog(files, lfns, pfc_name)
# createPoolFileCatalog(files, lfns, pfc_name, forceLogical=True)
return 0, "", None, FAX_dictionary
import functools
# new Movers integration
def use_newmover(newfunc):
def dec(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
use_newmover = readpar('use_newmover')
if str(use_newmover).lower() in ["1", "true"]:
print ("INFO: Will try to use new SiteMover(s) implementation since queuedata.use_newmover=%s" % use_newmover)
try:
ret = newfunc(*args, **kwargs)
#if ret and ret[0]: # new function return NON success code => temporary failover to old implementation
# raise Exception("new SiteMover return NON success code=%s .. do failover to old implementation.. r=%s" % (ret[0], ret))
return ret
except Exception, e:
#print ("INFO: Failed to execute new SiteMover(s): caught an exception: %s .. ignored. Continue execution using old implementation" % e)
import traceback
tolog(traceback.format_exc())
raise # disable failover to old implementation
return func(*args, **kwargs) # failover to old implementation
return wrapper
return dec
@use_newmover(get_data_new)
def get_data(job, jobSite, ins, stageinTries, analysisJob=False, usect=True, pinitdir="", proxycheck=True, inputDir="", workDir="", pfc_name="PoolFileCatalog.xml"):
""" call the mover and stage-in input files """
error = PilotErrors()
pilotErrorDiag = ""
ec = 0
# The relevant FAX variables will be stored in a dictionary, to be returned by this function
FAX_dictionary = {}
# if mover_get_data() fails to create a TURL based PFC, the returned statusPFCTurl will be False, True if succeeded and None if not used
statusPFCTurl = None
# create the local access and scope dictionaries
access_dict = createZippedDictionary(job.inFiles, job.prodDBlockToken)
scope_dict = createZippedDictionary(job.inFiles, job.scopeIn)
# create the handler for the potential DBRelease file (the DBRelease file will not be transferred on CVMFS)
from DBReleaseHandler import DBReleaseHandler
dbh = DBReleaseHandler(workdir=job.workdir)
try:
# get all proper dataset names
dsname, dsdict, rucio_dataset_dictionary = getProperDatasetNames(job.realDatasetsIn, job.prodDBlocks, job.inFiles)
# define the Pool File Catalog name, which can be different for event service jobs (PFC.xml vs PoolFileCatalog.xml)
inputpoolfcstring = "xmlcatalog_file:%s" % (pfc_name)
tolog("Calling get function with dsname=%s, dsdict=%s" % (dsname, str(dsdict)))
rc, pilotErrorDiag, statusPFCTurl, FAX_dictionary = \
mover_get_data(ins, job.workdir, jobSite.sitename, jobSite.computingElement, stageinTries, dsname=dsname, sourceSite=job.sourceSite,\
dsdict=dsdict, guids=job.inFilesGuids, analysisJob=analysisJob, usect=usect, pinitdir=pinitdir,\
proxycheck=proxycheck, spsetup=job.spsetup, tokens=job.dispatchDBlockToken, userid=job.prodUserID,\
access_dict=access_dict, inputDir=inputDir, jobId=job.jobId, jobsetID=job.jobsetID, DN=job.prodUserID, workDir=workDir,\
scope_dict=scope_dict, jobDefId=job.jobDefinitionID, dbh=dbh, jobPars=job.jobPars, cmtconfig=job.cmtconfig,\
filesizeIn=job.filesizeIn, checksumIn=job.checksumIn, transferType=job.transferType, experiment=job.experiment,\
eventService=job.eventService, inputpoolfcstring=inputpoolfcstring, rucio_dataset_dictionary=rucio_dataset_dictionary,\
pandaProxySecretKey=job.pandaProxySecretKey, job=job)
tolog("Get function finished with exit code %d" % (rc))
except SystemError, e:
pilotErrorDiag = "Get function for input files is interrupted by SystemError: %s" % str(e)
tolog("!!FAILED!!3000!! Exception caught: %s" % (pilotErrorDiag))
ec = error.ERR_KILLSIGNAL
except Exception, e:
pilotErrorDiag = "Get function can not be called for staging input files: %s" % str(e)
tolog("!!FAILED!!3000!! Exception caught: %s" % (pilotErrorDiag))
if str(e).find("No space left on device") >= 0:
tolog("!!FAILED!!3000!! Get error: No space left on local disk (%s)" % (pinitdir))
ec = error.ERR_NOLOCALSPACE
else:
ec = error.ERR_GETDATAEXC
# write traceback info to stderr
import traceback
exc, msg, tb = sys.exc_info()
traceback.print_tb(tb)
else:
if pilotErrorDiag != "":
# pilotErrorDiag = 'abcdefghijklmnopqrstuvwxyz0123456789'
# -> 'Get error: lmnopqrstuvwxyz0123456789'
pilotErrorDiag = "Get error: " + headPilotErrorDiag(pilotErrorDiag, size=256-len("Get error: "))
if rc: # get failed, non-zero return code
# this error is currently not being sent from Mover (see next error code)
if rc == error.ERR_FILEONTAPE:
tolog("!!WARNING!!3000!! Get error: Input file is on tape (will be skipped for analysis job)")
if analysisJob:
tolog("Skipping input file")
ec = 0
else:
pass # a prod job should not generate this error
else:
ec = rc
if pilotErrorDiag == "":
pilotErrorDiag = error.getPilotErrorDiag(ec)
tolog("!!FAILED!!3000!! %s" % (pilotErrorDiag))
if ec:
tolog("!!FAILED!!3000!! Get returned a non-zero exit code (%d), will now update local pilot TCP server" % (ec))
else:
# get_data finished correctly
tolog("Input file(s):")
for inputFile in ins:
try:
_ec, rs = commands.getstatusoutput("ls -l %s/%s" % (job.workdir, inputFile))
except Exception, e:
tolog(str(e))
else:
if "No such file or directory" in rs:
tolog("File %s was not transferred" % (inputFile))
else:
tolog(rs)
return ec, pilotErrorDiag, statusPFCTurl, FAX_dictionary
def getGuids(fileList):
""" extracts the guids from the file list """
guids = []
# loop over all files
for thisfile in fileList:
guids.append(str(thisfile.getAttribute("ID")))
return guids
def getReplicasLFC(guids, lfchost):
""" get the replicas list from the LFC """
ec = 0
pilotErrorDiag = ""
error = PilotErrors()
replica_list = []
try:
import lfc
except Exception, e:
pilotErrorDiag = "getReplicasLFC() could not import lfc module: %s" % str(e)
ec = error.ERR_GETLFCIMPORT
tolog("Get function using LFC_HOST: %s" % (lfchost))
os.environ['LFC_HOST'] = lfchost
os.environ['LFC_CONNTIMEOUT'] = '60'
os.environ['LFC_CONRETRY'] = '2'
os.environ['LFC_CONRETRYINT'] = '60'
try:
ret, replica_list = lfc.lfc_getreplicas(guids, "")
except Exception, e:
pilotErrorDiag = "Failed to get LFC replicas: Exception caught: %s" % str(e)
tolog("!!FAILED!!2999!! %s" % (pilotErrorDiag))
tolog("getReplicasLFC() finished (failed)")
ec = error.ERR_FAILEDLFCGETREPS
if ret != 0:
err_num = lfc.cvar.serrno
err_string = lfc.sstrerror(err_num)
pilotErrorDiag = "Failed to get LFC replicas: %d (lfc_getreplicas failed with: %d, %s)" %\
(ret, err_num, err_string)
tolog("!!WARNING!!2999!! %s" % (pilotErrorDiag))
tolog("getReplicas() finished (failed)")
ec = error.ERR_FAILEDLFCGETREPS
return ec, pilotErrorDiag, replica_list
def getReplicaDictionary(thisExperiment, guids, lfn_dict, scope_dict, replicas_dict, host):
""" Return a replica dictionary from the LFC or via Rucio methods """
error = PilotErrors()
ec = 0
# Is there an alternative to using LFC lookups?
if thisExperiment.willDoAlternativeFileLookups():
ec, pilotErrorDiag, replicas_dict = getReplicaDictionaryRucio(lfn_dict, scope_dict, replicas_dict, host)
else:
# Get file replicas directly from LFC
try:
ec, pilotErrorDiag, replicas_list = getReplicasLFC(guids, host)
except Exception, e:
pilotErrorDiag = "getReplicas threw an exception: %s" % str(e)
tolog("!!FAILED!!2999!! %s" % (pilotErrorDiag))
ec = error.ERR_FAILEDLFCGETREP
else:
# the replicas_list is a condense list containing all guids and all sfns, one after the other.
# there might be several identical guids followed by the corresponding sfns. we will not reformat
# this list into a sorted dictionary
# replicas_dict[guid] = [ rep1, .. ] where repN is an object of class replica (defined above)
try:
ec, pilotErrorDiag, replicas_dict = getReplicaDictionaryLFC(replicas_list, lfn_dict)
except Exception, e:
pilotErrorDiag = "%s" % str(e)
tolog("!!WARNING!!2999!! %s" % (pilotErrorDiag))
ec = error.ERR_FAILEDLFCGETREP
else:
if ec != 0:
tolog("!!WARNING!!2999!! %s" % (pilotErrorDiag))
return ec, pilotErrorDiag, replicas_dict
def verifySURLGUIDDictionary(surl_guid_dictionary, pilotErrorDiag):
""" Verify that all SURLs are set in the dictionary """
# A lost file will show up as an empty list in the dictionary
# Return status True if there are at least one valid SURL
status = False
tolog("Verifying SURLs")
if surl_guid_dictionary != {}:
for guid in surl_guid_dictionary.keys():
if surl_guid_dictionary[guid] == []:
pilotErrorDiag = "Encountered an empty SURL list for GUID=%s (replica is missing in catalog)" % (guid)
tolog("!!WARNING!!2222!! %s" % (pilotErrorDiag))
else:
# Found a valid SURL
status = True
tolog("GUID=%s has a valid (set) SURL list" % (guid))
else:
if pilotErrorDiag == "":
pilotErrorDiag = "Rucio returned an empty replica dictionary"
tolog("!!WARNING!!2222!! %s" % (pilotErrorDiag))
return status, pilotErrorDiag
def getFiletypeAndRSE(surl, surl_dictionary):
""" Get the filetype and RSE for a surl from the surl dictionary """
filetype = None
rse = None
try:
d = surl_dictionary[surl]
filetype = d['type'].upper() # the pilot will always assume upper case (either DISK or TAPE)
rse = d['rse'] # Corresponding Rucio site name
except Exception, e:
tolog("!!WARNING!!2238!! Failed to extract filetype and rse from rucio_surl_dictionary: %s" % (e))
return filetype, rse
def getReplicaDictionaryRucio(lfn_dict, scope_dict, replicas_dic, host):
""" Create a dictionary of the guids and replica objects """
pilotErrorDiag = ""
ec = 0
# we first need to build a dictionary with guid+LFN (including scopes)
file_dictionary = getRucioFileDictionary(lfn_dict, scope_dict)
tolog("file_dictionary=%s" % (file_dictionary))
# then get the replica dictionary from Rucio
rucio_replica_dictionary, rucio_surl_dictionary, pilotErrorDiag = getRucioReplicaDictionary(host, file_dictionary)
tolog("rucio_replica_dictionary=%s" % str(rucio_replica_dictionary))
tolog("rucio_surl_dictionary=%s" % str(rucio_surl_dictionary))
# then sort the rucio dictionary into a replica dictionary exptected by the pilot
# Rucio format: { guid1: {'surls': [surl1, ..], 'lfn':LFN, 'fsize':FSIZE, 'checksum':CHECKSUM}, ..}
# Pilot format: { guid1: [replica1, ..]}
# first build a SURL guid dictionary
surl_guid_dictionary = {}
for guid in rucio_replica_dictionary.keys():
surl_guid_dictionary[guid] = rucio_replica_dictionary[guid]['surls'] # SURL list
tolog("surl_guid_dictionary=%s"%str(surl_guid_dictionary))
# verify the rucio replica dictionary (only fail at this point if there were no valid SURLs - if there are at least one valid SURL, continue)
status, pilotErrorDiag = verifySURLGUIDDictionary(surl_guid_dictionary, pilotErrorDiag)
if not status and pilotErrorDiag != "":
tolog("!!WARNING!!1234!! %s" % (pilotErrorDiag))
ec = -1
return ec, pilotErrorDiag, replicas_dic
# loop over guids
# for g in range(len(rucio_replica_dictionary.keys())):
# guid = rucio_replica_dictionary.keys()[g]
for guid in rucio_replica_dictionary.keys():
# Skip missing SURLs
if len(surl_guid_dictionary[guid]) == 0:
tolog("GUID does not have a valid SURL (continue loop over GUIDs)")
continue
# loop over SURLs
for s in range(len(surl_guid_dictionary[guid])):
surl = surl_guid_dictionary[guid][s]
# create a new replica object
rep = replica()
rep.sfn = surl
rep.filesize = rucio_replica_dictionary[guid]['fsize']
rep.csumvalue = rucio_replica_dictionary[guid]['checksum']
# deprecated
rep.setname = ""
rep.fs = ""
# get the filetype and rse
rep.filetype, rep.rse = getFiletypeAndRSE(surl, rucio_surl_dictionary)
# add the replica object to the dictionary for the corresponding guid
if replicas_dic.has_key(guid):
replicas_dic[guid].append(rep)
else:
replicas_dic[guid] = [rep]
if replicas_dic == {}:
pilotErrorDiag = "Empty replicas dictionary"
tolog("!!WARNING!!1234!! %s" % (pilotErrorDiag))
ec = -1
return ec, pilotErrorDiag, replicas_dic
def getReplicaDictionaryLFC(replicas_list, lfn_dict):
""" Create a dictionary of the guids and replica objects """
error = PilotErrors()
pilotErrorDiag = ""
ec = 0
replicas_dic = {} # FORMAT: { guid1: [replica1, .. ], .. } where replica1 is of type replica
# replicas_list is a linear list of all guids and sfns
for _replica in replicas_list:
guid = _replica.guid
rep = replica()
rep.sfn = _replica.sfn
rep.filesize = _replica.filesize
rep.csumvalue = _replica.csumvalue
# empty sfn's should only happen if there was a timeout in the lfc_getreplicas call, which in
# turn could be caused by a large distance between the client and server, or if there were many
# guids in the batch call. should be fixed in later LFC server versions (from 1.7.0)
if rep.sfn == "":
if lfn_dict.has_key(guid):
filename = lfn_dict[guid]
else:
tolog("No such guid, continue")
continue
if "DBRelease" in filename:
ec = error.ERR_DBRELNOTYETTRANSFERRED
pilotErrorDiag = "%s has not been transferred yet (%s)" % (filename, guid)
else:
ec = error.ERR_NOLFCSFN
pilotErrorDiag = "SFN not set in LFC for guid %s (%s, LFC entry erased or file not yet transferred)" % (guid, filename)
break
# setname and fs might not exist
try:
rep.setname = _replica.setname
except:
rep.setname = None
try:
rep.fs = _replica.fs
except:
rep.fs = None
# add the replica object to the dictionary for the corresponding guid
if replicas_dic.has_key(guid):
replicas_dic[guid].append(rep)
else:
replicas_dic[guid] = [rep]
return ec, pilotErrorDiag, replicas_dic
def getReplicaDictionaryFile(workdir):
""" Get the replica dictionary from file (used when the primary replica can not be staged due to some temporary error) """
fileName = getMatchedReplicasFileName(workdir)
if os.path.exists(fileName):
# matched replicas dictionary file already exists, read it back
try:
f = open(fileName, "r")
except Exception, e:
tolog("!!WARNING!!1001!! Could not open file: %s, %s" % (fileName, e))
replica_dictionary = {}
else:
# is the file a pickle or a json file?
if fileName.endswith('json'):
from json import load
else:
from pickle import load
try:
# load the dictionary
replica_dictionary = load(f)
except Exception, e:
tolog("!!WARNING!!1001!! Could not read back replica dictionary: %s" % str(e))
replica_dictionary = {}
else:
# tolog("Successfully read back replica dictionary containing %d key(s)" % len(replica_dictionary.keys()))
pass
# done with the file
f.close()
else:
tolog("Creating initial replica dictionary")
replica_dictionary = {}
return replica_dictionary
def getInitialTracingReport(userid, sitename, dsname, eventType, analysisJob, jobId, jobDefId, dn, taskID):
""" setup the dictionary necessary for all instrumentation """
if analysisJob:
eventType = eventType + "_a"
try:
# for python 2.6
import hashlib
hash_pilotid = hashlib.md5()
hash_userid = hashlib.md5()
except:
# for python 2.4
import md5
hash_pilotid = md5.new()
hash_userid = md5.new()
# anonymise user and pilot id's
hash_userid.update(userid)
hash_pilotid.update('ppilot_%s' % jobDefId)
report = {'eventType': eventType, # sitemover
'eventVersion': 'pilot3', # pilot version
'protocol': None, # set by specific sitemover
'clientState': 'INIT_REPORT',
'localSite': sitename, # localsite
'remoteSite': sitename, # equals remotesite (pilot does not do remote copy?)
'timeStart': time(), # time to start
'catStart': None,
'relativeStart': None,
'transferStart': None,
'validateStart': None,
'timeEnd': None,
'dataset': dsname,
'version': None,
'duid': None,
'filename': None,
'guid': None,
'filesize': None,
'usr': hash_userid.hexdigest(),
'appid': jobId,
'hostname': '',
'ip': '',
'suspicious': '0',
'usrdn': dn,
'url': None,
'stateReason': None,
'taskid': taskID
}
if jobDefId == "":
report['uuid'] = commands.getoutput('uuidgen -t 2> /dev/null').replace('-',''), # all LFNs of one request have the same uuid
else:
report['uuid'] = hash_pilotid.hexdigest()
if jobDefId != "":
tolog("Using job definition id: %s" % (jobDefId))
# add DN etc
tolog("Trying to add additional info to tracing report")
try:
import socket
report['hostname'] = socket.gethostbyaddr(socket.gethostname())[0]
report['ip'] = socket.gethostbyaddr(socket.gethostname())[2][0]
except Exception, e:
tolog("!!WARNING!!2999!! Tracing report could not add some info: %s" % str(e))
tolog("Tracing report initialised with: %s" % str(report))
return report
def getFileListFromXML(xml_file):
""" Get the file list from the PFC """
xmldoc = minidom.parse(xml_file)
return xmldoc.getElementsByTagName("File")
def getFileInfoFromXML(thisfile):
""" Get the PFN from the XML """
pfn = thisfile.getElementsByTagName("pfn")[0].getAttribute("name")
# lfn will not be present in XML any longer, get it from the PFN - possible problem with LFN file name extensions
# lfn = thisfile.getElementsByTagName("lfn")[0].getAttribute("name")
lfn = os.path.basename(pfn)
guid = thisfile.getAttribute("ID")
return lfn, pfn, guid
def getFileInfoDictionaryFromXML(xml_file):
""" Create a file info dictionary from the PoolFileCatalog """
tolog("Get file catalog from: %s" % xml_file)
# Format: { lfn : [pfn, guid] }
# Example:
# lfn = "EVNT.01461041._000001.pool.root.1"
# pfn = file_info_dictionary[lfn][0]
# guid = file_info_dictionary[lfn][1]
file_info_dictionary = {}
file_list = getFileListFromXML(xml_file)
for f in file_list:
lfn, pfn, guid = getFileInfoFromXML(f)
file_info_dictionary[lfn] = [pfn, guid]
return file_info_dictionary
def getFileInfo(region, ub, queuename, guids, dsname, dsdict, lfns, pinitdir, analysisJob, tokens, DN, sitemover, error, workdir, dbh, DBReleaseIsAvailable, \
scope_dict, prodDBlockToken, computingSite="", sourceSite="", pfc_name="PoolFileCatalog.xml", filesizeIn=[], checksumIn=[], thisExperiment=None, ddmEndPointIn=None):
""" Build the file info dictionary """
fileInfoDic = {} # FORMAT: fileInfoDic[file_nr] = (guid, pfn, size, checksum, filetype, copytool, os_bucket_id) - note: copytool not necessarily the same for all file (e.g. FAX case)
replicas_dic = {} # FORMAT: { guid1: [replica1, .. ], .. } where replica1 is of type replica
surl_filetype_dictionary = {} # FORMAT: { sfn1: filetype1, .. } (sfn = surl, filetype = DISK/TAPE)
copytool_dictionary = {} # FORMAT: { surl1: copytool1, .. }
totalFileSize = 0L
ec = 0
pilotErrorDiag = ""
xml_source = ""
tolog("Preparing to build paths for input files")
# Get the site information object
si = getSiteInformation(thisExperiment.getExperiment())
# In case we are staging in files from an object store, we can do a short cut and skip the catalog lookups below
copytool, dummy = getCopytool(mode="get")
if "objectstore" in copytool:
tolog("Objectstore stage-in: cutting a few corners")
# Format: fileInfoDic[file_nr] = (guid, gpfn, size, checksum, filetype, copytool, os_bucket_id)
# replicas_dic[guid1] = [replica1, ..]
# Convert the OS bucket ID:s to integers
status, os_bucket_ids = si.hasOSBucketIDs(prodDBlockToken)
tolog("os_bucket_ids=%s"%str(os_bucket_ids))
if not status:
# Get the default ddm endpoint from the normal queuedata
ddmendpoint = si.getObjectstoreDDMEndpoint(os_bucket_name='eventservice')
os_bucket_id = si.getObjectstoreBucketID(ddmendpoint)
tolog("Will create a list using the default bucket ID: %s" % (os_bucket_id))
os_bucket_ids = [os_bucket_id]*len(prodDBlockToken)
tolog("os_bucket_ids=%s"%str(os_bucket_ids))
i = 0
try:
for lfn in lfns:
path = si.getObjectstorePath(os_bucket_id=os_bucket_ids[i], label='r') # Should be the last item
fullpath = os.path.join(path, lfns[i])
tolog("OS path = %s" % (fullpath))
fileInfoDic[i] = (guids[i], fullpath, filesizeIn[i], checksumIn[i], 'DISK', copytool, os_bucket_ids[i]) # filetype is always DISK on objectstores
replicas_dic[guids[i]] = [fullpath]
surl_filetype_dictionary[fullpath] = 'DISK' # filetype is always DISK on objectstores
i += 1
except Exception, e:
tolog("!!WARNING!!2233!! Failed to create replica and file dictionaries: %s" % (e))
ec = -1
return ec, pilotErrorDiag, fileInfoDic, totalFileSize, replicas_dic, xml_source
# If the pilot is running on a Tier 3 site, then neither LFC nor PFC should be used
if si.isTier3():
tolog("Getting file info on a Tier 3 site")
# Create file path to local SE (not used for scope based paths)
path = sitemover.getTier3Path(dsname, DN) # note: dsname will only be correct for lib files, otherwise fix dsdict, currently empty for single lib file input?
file_nr = -1
for lfn in lfns:
file_nr += 1
se_path = os.path.join(path, lfn)
# Get the file info
ec, pilotErrorDiag, fsize, fchecksum = sitemover.getLocalFileInfo(se_path, csumtype="default")
if ec != 0:
return ec, pilotErrorDiag, fileInfoDic, totalFileSize, replicas_dic, xml_source
# Fill the dictionaries
fileInfoDic[file_nr] = (guids[file_nr], se_path, fsize, fchecksum, 'DISK', copytool, -1) # no tape on T3s, so filetype is always DISK; set os_bucketId=-1 for non-OS files
surl_filetype_dictionary[fullpath] = 'DISK' # filetype is always DISK on T3s
# Check total file sizes to avoid filling up the working dir, add current file size
try:
totalFileSize += long(fsize)
except:
pass
else:
# Get the PFC from the proper source
ec, pilotErrorDiag, xml_from_PFC, xml_source, replicas_dic, surl_filetype_dictionary, copytool_dictionary = \
getPoolFileCatalog(ub, guids, lfns, pinitdir, analysisJob, tokens, workdir, dbh,\
DBReleaseIsAvailable, scope_dict, filesizeIn, checksumIn, sitemover,\
computingSite=computingSite, sourceSite=sourceSite, pfc_name=pfc_name, thisExperiment=thisExperiment, ddmEndPointIn=ddmEndPointIn)
if ec != 0:
return ec, pilotErrorDiag, fileInfoDic, totalFileSize, replicas_dic, xml_source
tolog("Using XML source %s" % (xml_source))