ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/cmscp.py
Revision: 1.56.2.1
Committed: Wed Sep 16 13:26:24 2009 UTC (15 years, 7 months ago) by spiga
Content type: text/x-python
Branch: CRAB_2_6_X_br
CVS Tags: CRAB_2_6_3_pre1
Changes since 1.56: +25 -1 lines
Log Message:
sync with head

File Contents

# User Rev Content
1 edelmann 1.56 #!/usr/bin/env python
2 mcinquil 1.16 import sys, os
3 ewv 1.7 from ProdCommon.Storage.SEAPI.SElement import SElement, FullPath
4 spiga 1.1 from ProdCommon.Storage.SEAPI.SBinterface import *
5 spiga 1.11 from ProdCommon.Storage.SEAPI.Exceptions import *
6 spiga 1.1
7    
8     class cmscp:
9 spiga 1.8 def __init__(self, args):
10 spiga 1.1 """
11     cmscp
12 spiga 1.46 safe copy of local file to/from remote SE via lcg_cp/srmcp,
13 spiga 1.1 including success checking version also for CAF using rfcp command to copy the output to SE
14     input:
15     $1 middleware (CAF, LSF, LCG, OSG)
16 spiga 1.2 $2 local file (the absolute path of output file or just the name if it's in top dir)
17     $3 if needed: file name (the output file name)
18     $5 remote SE (complete endpoint)
19 ewv 1.7 $6 srm version
20 fanzago 1.38 --lfn $LFNBaseName
21 spiga 1.1 output:
22     return 0 if all ok
23     return 60307 if srmcp failed
24     return 60303 if file already exists in the SE
25     """
26 spiga 1.8
27 spiga 1.1 #set default
28 spiga 1.24 self.params = {"source":'', "destination":'','destinationDir':'', "inputFileList":'', "outputFileList":'', \
29 fanzago 1.38 "protocol":'', "option":'', "middleware":'', "srm_version":'srmv2', "lfn":'' }
30 ewv 1.14 self.debug = 0
31 spiga 1.46 self.local_stage = 0
32 spiga 1.8 self.params.update( args )
33 ewv 1.7
34 spiga 1.1 return
35    
36 spiga 1.8 def processOptions( self ):
37 spiga 1.1 """
38 spiga 1.8 check command line parameter
39 spiga 1.1 """
40 ewv 1.14 if 'help' in self.params.keys(): HelpOptions()
41     if 'debug' in self.params.keys(): self.debug = 1
42 spiga 1.45 if 'local_stage' in self.params.keys(): self.local_stage = 1
43 ewv 1.7
44     # source and dest cannot be undefined at same time
45 spiga 1.8 if not self.params['source'] and not self.params['destination'] :
46 spiga 1.36 HelpOptions()
47 ewv 1.7 # if middleware is not defined --> protocol cannot be empty
48 spiga 1.8 if not self.params['middleware'] and not self.params['protocol'] :
49     HelpOptions()
50    
51 ewv 1.7 # input file must be defined
52 spiga 1.35 if not self.params['inputFileList'] :
53 spiga 1.36 HelpOptions()
54 spiga 1.1 else:
55 spiga 1.8 file_to_copy=[]
56 ewv 1.14 if self.params['inputFileList'].find(','):
57 spiga 1.8 [file_to_copy.append(x.strip()) for x in self.params['inputFileList'].split(',')]
58 ewv 1.7 else:
59 spiga 1.8 file_to_copy.append(self.params['inputFileList'])
60     self.params['inputFileList'] = file_to_copy
61 ewv 1.7
62 spiga 1.46 if not self.params['lfn'] and self.local_stage == 1 : HelpOptions()
63 fanzago 1.38
64 spiga 1.1 ## TO DO:
65     #### add check for outFiles
66     #### add map {'inFileNAME':'outFileNAME'} to change out name
67    
68    
69 ewv 1.7 def run( self ):
70 spiga 1.1 """
71 ewv 1.7 Check if running on UI (no $middleware) or
72     on WN (on the Grid), and take different action
73 spiga 1.1 """
74 mcinquil 1.37 self.processOptions()
75 spiga 1.30 if self.debug: print 'calling run() : \n'
76 spiga 1.8 # stage out from WN
77     if self.params['middleware'] :
78 spiga 1.36 results = self.stager(self.params['middleware'],self.params['inputFileList'])
79 spiga 1.35 self.finalReport(results)
80 spiga 1.8 # Local interaction with SE
81 spiga 1.1 else:
82 spiga 1.36 results = self.copy(self.params['inputFileList'], self.params['protocol'], self.params['option'] )
83 spiga 1.35 return results
84 spiga 1.1
85 spiga 1.56.2.1 def checkLcgUtils( self ):
86     """
87     _checkLcgUtils_
88     check the lcg-utils version and report
89     """
90     import commands
91     cmd = "lcg-cp --version | grep lcg_util"
92     status, output = commands.getstatusoutput( cmd )
93     num_ver = -1
94     if output.find("not found") == -1 or status == 0:
95     temp = output.split("-")
96     version = ""
97     if len(temp) >= 2:
98     version = output.split("-")[1]
99     temp = version.split(".")
100     if len(temp) >= 1:
101     num_ver = int(temp[0])*10
102     num_ver += int(temp[1])
103     return num_ver
104    
105 spiga 1.8 def setProtocol( self, middleware ):
106 spiga 1.1 """
107     define the allowed potocols based on $middlware
108 ewv 1.7 which depend on scheduler
109 spiga 1.1 """
110 spiga 1.8 # default To be used with "middleware"
111 fanzago 1.38 if self.debug:
112     print 'setProtocol() :\n'
113     print '\tmiddleware = %s utils \n'%middleware
114    
115 spiga 1.13 lcgOpt={'srmv1':'-b -D srmv1 -t 2400 --verbose',
116     'srmv2':'-b -D srmv2 -t 2400 --verbose'}
117 spiga 1.56.2.1 if self.checkLcgUtils() >= 17:
118     lcgOpt={'srmv1':'-b -D srmv1 --srm-timeout 2400 --sendreceive-timeout 240 --connect-timeout 240 --verbose',
119     'srmv2':'-b -D srmv2 --srm-timeout 2400 --sendreceive-timeout 240 --connect-timeout 240 --verbose'}
120    
121 spiga 1.13 srmOpt={'srmv1':' -report ./srmcp.report -retry_timeout 480000 -retry_num 3 -streams_num=1 ',
122 ewv 1.33 'srmv2':' -report=./srmcp.report -retry_timeout=480000 -retry_num=3 '}
123 spiga 1.8 rfioOpt=''
124    
125 ewv 1.14 supported_protocol = None
126 spiga 1.40 if middleware.lower() in ['osg','lcg','condor','sge']:
127 spiga 1.12 supported_protocol = [('srm-lcg',lcgOpt[self.params['srm_version']]),\
128 spiga 1.30 (self.params['srm_version'],srmOpt[self.params['srm_version']])]
129 spiga 1.8 elif middleware.lower() in ['lsf','caf']:
130 ewv 1.14 supported_protocol = [('rfio',rfioOpt)]
131 edelmann 1.53 elif middleware.lower() in ['arc']:
132     supported_protocol = [('srmv2','-debug'),('srmv1','-debug')]
133 spiga 1.1 else:
134 ewv 1.7 ## here we can add support for any kind of protocol,
135 spiga 1.1 ## maybe some local schedulers need something dedicated
136     pass
137     return supported_protocol
138 spiga 1.28
139 fanzago 1.41
140     def checkCopy (self, copy_results, len_list_files, prot, lfn='', se=''):
141     """
142     Checks the status of copy and update result dictionary
143 spiga 1.28 """
144     list_retry = []
145 fanzago 1.55 list_retry_localSE = []
146 fanzago 1.41 list_not_existing = []
147 spiga 1.28 list_ok = []
148 fanzago 1.41
149     if self.debug:
150     print 'in checkCopy() :\n'
151     for file, dict in copy_results.iteritems():
152     er_code = dict['erCode']
153     if er_code == '0':
154     list_ok.append(file)
155     reason = 'Copy succedeed with %s utils'%prot
156     dict['reason'] = reason
157     elif er_code == '60302':
158     list_not_existing.append( file )
159 mcinquil 1.50 elif er_code == '10041':
160 fanzago 1.41 list_retry.append( file )
161 mcinquil 1.50 ## WHAT TO DO IN GENERAL FAILURE CONDITION
162 fanzago 1.55 else:
163     list_retry_localSE.append( file )
164 fanzago 1.41
165     if self.debug:
166     print "\t file %s \n"%file
167     print "\t dict['erCode'] %s \n"%dict['erCode']
168     print "\t dict['reason'] %s \n"%dict['reason']
169    
170     if (lfn != '') and (se != ''):
171     upDict = self.updateReport(file, er_code, dict['reason'], lfn, se)
172 spiga 1.28 else:
173 fanzago 1.41 upDict = self.updateReport(file, er_code, dict['reason'])
174    
175     copy_results.update(upDict)
176    
177     msg = ''
178     if len(list_ok) != 0:
179     msg += '\tCopy of %s succedeed with %s utils\n'%(str(list_ok),prot)
180     if len(list_ok) != len_list_files :
181     msg += '\tCopy of %s failed using %s for files \n'%(str(list_retry),prot)
182     msg += '\tCopy of %s failed using %s : files not found \n'%(str(list_not_existing),prot)
183     if self.debug : print msg
184    
185 fanzago 1.55 return copy_results, list_ok, list_retry, list_retry_localSE
186 fanzago 1.41
187 spiga 1.45 def LocalCopy(self, list_retry, results):
188 fanzago 1.41 """
189 spiga 1.45 Tries the stage out to the CloseSE
190 fanzago 1.38 """
191 fanzago 1.41 if self.debug:
192 spiga 1.45 print 'in LocalCopy() :\n'
193 fanzago 1.41 print '\t list_retry %s utils \n'%list_retry
194     print '\t len(list_retry) %s \n'%len(list_retry)
195    
196     list_files = list_retry
197     self.params['inputFilesList']=list_files
198    
199     ### copy backup
200     from ProdCommon.FwkJobRep.SiteLocalConfig import loadSiteLocalConfig
201     siteCfg = loadSiteLocalConfig()
202     seName = siteCfg.localStageOut.get("se-name", None)
203     catalog = siteCfg.localStageOut.get("catalog", None)
204     implName = siteCfg.localStageOut.get("command", None)
205     if (implName == 'srm'):
206     implName='srmv1'
207     self.params['srm_version']=implName
208     ##### to be improved ###############
209     if (implName == 'rfcp'):
210     self.params['middleware']='lsf'
211     ####################################
212    
213     self.params['protocol']=implName
214     tfc = siteCfg.trivialFileCatalog()
215    
216     if self.debug:
217     print '\t siteCFG %s \n'%siteCfg
218     print '\t seName %s \n'%seName
219     print '\t catalog %s \n'%catalog
220     print "\t self.params['protocol'] %s \n"%self.params['protocol']
221     print '\t tfc %s '%tfc
222     print "\t self.params['inputFilesList'] %s \n"%self.params['inputFilesList']
223    
224     file_backup=[]
225     for input in self.params['inputFilesList']:
226     file = self.params['lfn'] + os.path.basename(input)
227     surl = tfc.matchLFN(tfc.preferredProtocol, file)
228     file_backup.append(surl)
229     if self.debug:
230     print '\t lfn %s \n'%self.params['lfn']
231     print '\t file %s \n'%file
232     print '\t surl %s \n'%surl
233    
234     destination=os.path.dirname(file_backup[0])
235     self.params['destination']=destination
236    
237     if self.debug:
238     print "\t self.params['destination']%s \n"%self.params['destination']
239     print "\t self.params['protocol'] %s \n"%self.params['protocol']
240     print "\t self.params['option']%s \n"%self.params['option']
241    
242     for prot, opt in self.setProtocol( self.params['middleware'] ):
243 spiga 1.45 if self.debug: print '\tIn LocalCopy trying the stage out with %s utils \n'%prot
244     localCopy_results = self.copy( self.params['inputFileList'], prot, opt )
245     if localCopy_results.keys() == [''] or localCopy_results.keys() == '' :
246     results.update(localCopy_results)
247 fanzago 1.41 else:
248 fanzago 1.55 localCopy_results, list_ok, list_retry, list_retry_localSE = self.checkCopy(localCopy_results, len(list_files), prot, self.params['lfn'], seName)
249 spiga 1.45 results.update(localCopy_results)
250 fanzago 1.41 if len(list_ok) == len(list_files) :
251     break
252     if len(list_retry):
253     list_files = list_retry
254     else: break
255     if self.debug:
256 spiga 1.45 print "\t localCopy_results = %s \n"%localCopy_results
257 spiga 1.28
258 fanzago 1.41 return results
259    
260 spiga 1.8 def stager( self, middleware, list_files ):
261 spiga 1.1 """
262     Implement the logic for remote stage out
263     """
264 spiga 1.30
265 fanzago 1.38 if self.debug:
266     print 'stager() :\n'
267     print '\tmiddleware %s\n'%middleware
268 spiga 1.45 print '\tlist_files %s\n'%list_files
269 fanzago 1.38
270 spiga 1.6 results={}
271 spiga 1.8 for prot, opt in self.setProtocol( middleware ):
272 spiga 1.30 if self.debug: print '\tTrying the stage out with %s utils \n'%prot
273 spiga 1.8 copy_results = self.copy( list_files, prot, opt )
274 spiga 1.30 if copy_results.keys() == [''] or copy_results.keys() == '' :
275 spiga 1.13 results.update(copy_results)
276     else:
277 fanzago 1.55 copy_results, list_ok, list_retry, list_retry_localSE = self.checkCopy(copy_results, len(list_files), prot)
278 spiga 1.13 results.update(copy_results)
279     if len(list_ok) == len(list_files) :
280     break
281 fanzago 1.41 if len(list_retry):
282     list_files = list_retry
283     else: break
284    
285 spiga 1.45 if self.local_stage:
286 fanzago 1.55 if len(list_retry_localSE):
287     results = self.LocalCopy(list_retry_localSE, results)
288 fanzago 1.38
289     if self.debug:
290     print "\t results %s \n"%results
291 spiga 1.1 return results
292    
293     def initializeApi(self, protocol ):
294     """
295 ewv 1.7 Instantiate storage interface
296 spiga 1.1 """
297 spiga 1.30 if self.debug : print 'initializeApi() :\n'
298 spiga 1.20 self.source_prot = protocol
299     self.dest_prot = protocol
300     if not self.params['source'] : self.source_prot = 'local'
301     Source_SE = self.storageInterface( self.params['source'], self.source_prot )
302     if not self.params['destination'] : self.dest_prot = 'local'
303     Destination_SE = self.storageInterface( self.params['destination'], self.dest_prot )
304 spiga 1.1
305     if self.debug :
306 spiga 1.30 msg = '\t(source=%s, protocol=%s)'%(self.params['source'], self.source_prot)
307     msg += '\t(destination=%s, protocol=%s)'%(self.params['destination'], self.dest_prot)
308 mcinquil 1.32 print msg
309 spiga 1.1
310     return Source_SE, Destination_SE
311    
312 spiga 1.8 def copy( self, list_file, protocol, options ):
313 spiga 1.1 """
314 ewv 1.7 Make the real file copy using SE API
315 spiga 1.1 """
316 mcinquil 1.37 msg = ""
317 spiga 1.1 if self.debug :
318 spiga 1.30 msg = 'copy() :\n'
319     msg += '\tusing %s protocol\n'%protocol
320     print msg
321 spiga 1.13 try:
322     Source_SE, Destination_SE = self.initializeApi( protocol )
323     except Exception, ex:
324     return self.updateReport('', '-1', str(ex))
325 ewv 1.14
326 ewv 1.7 # create remote dir
327 mcinquil 1.32 if Destination_SE.protocol in ['gridftp','rfio','srmv2']:
328 spiga 1.13 try:
329 mcinquil 1.32 self.createDir( Destination_SE, Destination_SE.protocol )
330 mcinquil 1.47 except OperationException, ex:
331 spiga 1.13 return self.updateReport('', '60316', str(ex))
332 mcinquil 1.50 ## when the client commands are not found (wrong env or really missing)
333     except MissingCommand, ex:
334     msg = "ERROR %s %s" %(str(ex), str(ex.detail))
335     return self.updateReport('', '10041', msg)
336 spiga 1.1
337     ## prepare for real copy ##
338 spiga 1.8 try :
339     sbi = SBinterface( Source_SE, Destination_SE )
340     sbi_dest = SBinterface(Destination_SE)
341 spiga 1.20 sbi_source = SBinterface(Source_SE)
342 spiga 1.11 except ProtocolMismatch, ex:
343 spiga 1.30 msg = "ERROR : Unable to create SBinterface with %s protocol"%protocol
344     msg += str(ex)
345     return self.updateReport('', '-1', msg)
346 spiga 1.1
347     results = {}
348 ewv 1.7 ## loop over the complete list of files
349     for filetocopy in list_file:
350 spiga 1.30 if self.debug : print '\tStart real copy for %s'%filetocopy
351 spiga 1.13 try :
352 spiga 1.34 ErCode, msg = self.checkFileExist( sbi_source, sbi_dest, filetocopy, options )
353 spiga 1.13 except Exception, ex:
354 spiga 1.56.2.1 ErCode = '60307'
355 spiga 1.18 msg = str(ex)
356 ewv 1.7 if ErCode == '0':
357 spiga 1.19 ErCode, msg = self.makeCopy( sbi, filetocopy , options, protocol,sbi_dest )
358 spiga 1.30 if self.debug : print '\tCopy results for %s is %s'%( os.path.basename(filetocopy), ErCode)
359 spiga 1.1 results.update( self.updateReport(filetocopy, ErCode, msg))
360     return results
361 ewv 1.7
362 spiga 1.1
363     def storageInterface( self, endpoint, protocol ):
364     """
365 ewv 1.7 Create the storage interface.
366 spiga 1.1 """
367 spiga 1.30 if self.debug : print 'storageInterface():\n'
368 spiga 1.1 try:
369     interface = SElement( FullPath(endpoint), protocol )
370 spiga 1.11 except ProtocolUnknown, ex:
371 spiga 1.30 msg = "ERROR : Unable to create interface with %s protocol"%protocol
372     msg += str(ex)
373 spiga 1.13 raise Exception(msg)
374 spiga 1.1
375     return interface
376    
377     def createDir(self, Destination_SE, protocol):
378     """
379 spiga 1.8 Create remote dir for gsiftp REALLY TEMPORARY
380 ewv 1.7 this should be transparent at SE API level.
381 spiga 1.1 """
382 spiga 1.30 if self.debug : print 'createDir():\n'
383 ewv 1.14 msg = ''
384 spiga 1.1 try:
385     action = SBinterface( Destination_SE )
386     action.createDir()
387 spiga 1.30 if self.debug: print "\tThe directory has been created using protocol %s"%protocol
388 spiga 1.11 except TransferException, ex:
389 spiga 1.30 msg = "ERROR: problem with the directory creation using %s protocol "%protocol
390     msg += str(ex)
391 spiga 1.11 if self.debug :
392 spiga 1.30 dbgmsg = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
393     dbgmsg += '\t'+str(ex.output)+'\n'
394     print dbgmsg
395 spiga 1.29 raise Exception(msg)
396 spiga 1.11 except OperationException, ex:
397 spiga 1.30 msg = "ERROR: problem with the directory creation using %s protocol "%protocol
398     msg += str(ex)
399     if self.debug : print '\t'+msg+'\n\t'+str(ex.detail)+'\n'
400 spiga 1.29 raise Exception(msg)
401 spiga 1.31 except MissingDestination, ex:
402     msg = "ERROR: problem with the directory creation using %s protocol "%protocol
403     msg += str(ex)
404     if self.debug : print '\t'+msg+'\n\t'+str(ex.detail)+'\n'
405     raise Exception(msg)
406     except AlreadyExistsException, ex:
407     if self.debug: print "\tThe directory already exist"
408     pass
409 spiga 1.13 return msg
410 spiga 1.1
411 spiga 1.34 def checkFileExist( self, sbi_source, sbi_dest, filetocopy, option ):
412 spiga 1.1 """
413 spiga 1.20 Check both if source file exist AND
414     if destination file ALREADY exist.
415 ewv 1.7 """
416 spiga 1.30 if self.debug : print 'checkFileExist():\n'
417 spiga 1.8 ErCode = '0'
418     msg = ''
419 spiga 1.20 f_tocopy=filetocopy
420     if self.source_prot != 'local':f_tocopy = os.path.basename(filetocopy)
421 spiga 1.1 try:
422 spiga 1.34 checkSource = sbi_source.checkExists( f_tocopy , opt=option )
423 spiga 1.30 if self.debug : print '\tCheck for local file %s exist succeded \n'%f_tocopy
424 spiga 1.20 except OperationException, ex:
425 spiga 1.30 msg ='ERROR: problems checkig if source file %s exist'%filetocopy
426     msg += str(ex)
427 spiga 1.20 if self.debug :
428 spiga 1.30 dbgmsg = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
429     dbgmsg += '\t'+str(ex.output)+'\n'
430     print dbgmsg
431 spiga 1.20 raise Exception(msg)
432     except WrongOption, ex:
433 spiga 1.30 msg ='ERROR problems checkig if source file % exist'%filetocopy
434     msg += str(ex)
435 spiga 1.20 if self.debug :
436 spiga 1.30 dbgmsg = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
437     dbgmsg += '\t'+str(ex.output)+'\n'
438     print dbgmsg
439 spiga 1.20 raise Exception(msg)
440 spiga 1.31 except MissingDestination, ex:
441     msg ='ERROR problems checkig if source file % exist'%filetocopy
442     msg += str(ex)
443     if self.debug : print '\t'+msg+'\n\t'+str(ex.detail)+'\n'
444     raise Exception(msg)
445 mcinquil 1.50 ## when the client commands are not found (wrong env or really missing)
446     except MissingCommand, ex:
447     ErCode = '10041'
448     msg = "ERROR %s %s" %(str(ex), str(ex.detail))
449     return ErCode, msg
450 spiga 1.20 if not checkSource :
451     ErCode = '60302'
452     msg = "ERROR file %s do not exist"%os.path.basename(filetocopy)
453     return ErCode, msg
454     f_tocopy=filetocopy
455     if self.dest_prot != 'local':f_tocopy = os.path.basename(filetocopy)
456     try:
457 spiga 1.34 check = sbi_dest.checkExists( f_tocopy, opt=option )
458 spiga 1.30 if self.debug : print '\tCheck for remote file %s exist succeded \n'%f_tocopy
459 spiga 1.11 except OperationException, ex:
460 spiga 1.30 msg = 'ERROR: problems checkig if file %s already exist'%filetocopy
461     msg += str(ex)
462 spiga 1.11 if self.debug :
463 spiga 1.30 dbgmsg = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
464     dbgmsg += '\t'+str(ex.output)+'\n'
465     print dbgmsg
466 spiga 1.13 raise Exception(msg)
467 spiga 1.11 except WrongOption, ex:
468 spiga 1.30 msg = 'ERROR problems checkig if file % already exist'%filetocopy
469     msg += str(ex)
470 spiga 1.11 if self.debug :
471 spiga 1.30 msg += '\t'+msg+'\n\t'+str(ex.detail)+'\n'
472     msg += '\t'+str(ex.output)+'\n'
473 spiga 1.13 raise Exception(msg)
474 spiga 1.31 except MissingDestination, ex:
475     msg ='ERROR problems checkig if source file % exist'%filetocopy
476     msg += str(ex)
477     if self.debug : print '\t'+msg+'\n\t'+str(ex.detail)+'\n'
478     raise Exception(msg)
479 mcinquil 1.50 ## when the client commands are not found (wrong env or really missing)
480     except MissingCommand, ex:
481     ErCode = '10041'
482     msg = "ERROR %s %s" %(str(ex), str(ex.detail))
483     return ErCode, msg
484 ewv 1.14 if check :
485 ewv 1.7 ErCode = '60303'
486 spiga 1.20 msg = "file %s already exist"%os.path.basename(filetocopy)
487 ewv 1.14
488 spiga 1.13 return ErCode, msg
489 spiga 1.1
490 spiga 1.19 def makeCopy(self, sbi, filetocopy, option, protocol, sbi_dest ):
491 spiga 1.1 """
492 ewv 1.7 call the copy API.
493 spiga 1.1 """
494 spiga 1.30 if self.debug : print 'makeCopy():\n'
495 ewv 1.7 path = os.path.dirname(filetocopy)
496 spiga 1.1 file_name = os.path.basename(filetocopy)
497     source_file = filetocopy
498     dest_file = file_name ## to be improved supporting changing file name TODO
499 spiga 1.8 if self.params['source'] == '' and path == '':
500 spiga 1.1 source_file = os.path.abspath(filetocopy)
501 spiga 1.8 elif self.params['destination'] =='':
502 spiga 1.24 destDir = self.params.get('destinationDir',os.getcwd())
503     dest_file = os.path.join(destDir,file_name)
504 spiga 1.8 elif self.params['source'] != '' and self.params['destination'] != '' :
505 ewv 1.7 source_file = file_name
506 spiga 1.8
507 spiga 1.1 ErCode = '0'
508     msg = ''
509 ewv 1.7
510 spiga 1.1 try:
511 spiga 1.8 sbi.copy( source_file , dest_file , opt = option)
512 spiga 1.11 except TransferException, ex:
513 spiga 1.30 msg = "Problem copying %s file" % filetocopy
514     msg += str(ex)
515 spiga 1.11 if self.debug :
516 spiga 1.30 dbgmsg = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
517     dbgmsg += '\t'+str(ex.output)+'\n'
518 mcinquil 1.32 print dbgmsg
519 spiga 1.1 ErCode = '60307'
520 spiga 1.11 except WrongOption, ex:
521 spiga 1.30 msg = "Problem copying %s file" % filetocopy
522     msg += str(ex)
523 spiga 1.11 if self.debug :
524 spiga 1.30 dbgmsg = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
525     dbgmsg += '\t'+str(ex.output)+'\n'
526 fanzago 1.48 print dbgmsg
527 spiga 1.44 except SizeZeroException, ex:
528     msg = "Problem copying %s file" % filetocopy
529     msg += str(ex)
530     if self.debug :
531     dbgmsg = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
532     dbgmsg += '\t'+str(ex.output)+'\n'
533 fanzago 1.48 print dbgmsg
534 spiga 1.13 ErCode = '60307'
535 mcinquil 1.50 ## when the client commands are not found (wrong env or really missing)
536     except MissingCommand, ex:
537     ErCode = '10041'
538     msg = "Problem copying %s file" % filetocopy
539     msg += str(ex)
540     if self.debug :
541     dbgmsg = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
542     dbgmsg += '\t'+str(ex.output)+'\n'
543     print dbgmsg
544 mcinquil 1.54 except AuthorizationException, ex:
545     ErCode = '60307'
546     msg = "Problem copying %s file" % filetocopy
547     msg += str(ex)
548     if self.debug :
549     dbgmsg = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
550     dbgmsg += '\t'+str(ex.output)+'\n'
551     print dbgmsg
552 spiga 1.24 if ErCode == '0' and protocol.find('srmv') == 0:
553 spiga 1.19 remote_file_size = -1
554     local_file_size = os.path.getsize( source_file )
555     try:
556 spiga 1.34 remote_file_size = sbi_dest.getSize( dest_file, opt=option )
557 spiga 1.30 if self.debug : print '\t Check of remote size succeded for file %s\n'%dest_file
558 spiga 1.19 except TransferException, ex:
559 spiga 1.30 msg = "Problem checking the size of %s file" % filetocopy
560     msg += str(ex)
561 spiga 1.19 if self.debug :
562 spiga 1.30 dbgmsg = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
563     dbgmsg += '\t'+str(ex.output)+'\n'
564     print dbgmsg
565 spiga 1.19 ErCode = '60307'
566     except WrongOption, ex:
567 spiga 1.30 msg = "Problem checking the size of %s file" % filetocopy
568     msg += str(ex)
569 spiga 1.19 if self.debug :
570 spiga 1.30 dbgmsg = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
571     dbgmsg += '\t'+str(ex.output)+'\n'
572     print dbgmsg
573 spiga 1.19 ErCode = '60307'
574     if local_file_size != remote_file_size:
575     msg = "File size dosn't match: local size = %s ; remote size = %s " % (local_file_size, remote_file_size)
576     ErCode = '60307'
577 ewv 1.14
578 spiga 1.27 if ErCode != '0':
579     try :
580 spiga 1.34 self.removeFile( sbi_dest, dest_file, option )
581 spiga 1.27 except Exception, ex:
582     msg += '\n'+str(ex)
583 spiga 1.1 return ErCode, msg
584 ewv 1.7
585 spiga 1.34 def removeFile( self, sbi_dest, filetocopy, option ):
586 spiga 1.30 """
587     """
588     if self.debug : print 'removeFile():\n'
589 spiga 1.21 f_tocopy=filetocopy
590     if self.dest_prot != 'local':f_tocopy = os.path.basename(filetocopy)
591     try:
592 spiga 1.34 sbi_dest.delete( f_tocopy, opt=option )
593 spiga 1.30 if self.debug : '\t deletion of file %s succeeded\n'%str(filetocopy)
594 spiga 1.21 except OperationException, ex:
595 spiga 1.30 msg ='ERROR: problems removing partially staged file %s'%filetocopy
596     msg += str(ex)
597 spiga 1.21 if self.debug :
598 spiga 1.30 dbgmsg = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
599     dbgmsg += '\t'+str(ex.output)+'\n'
600     print dbgmsg
601 spiga 1.21 raise Exception(msg)
602    
603     return
604    
605 spiga 1.8 def updateReport(self, file, erCode, reason, lfn='', se='' ):
606     """
607     Update the final stage out infos
608     """
609     jobStageInfo={}
610     jobStageInfo['erCode']=erCode
611     jobStageInfo['reason']=reason
612     jobStageInfo['lfn']=lfn
613     jobStageInfo['se']=se
614 spiga 1.1
615 spiga 1.8 report = { file : jobStageInfo}
616     return report
617 ewv 1.7
618 spiga 1.8 def finalReport( self , results ):
619     """
620     It a list of LFNs for each SE where data are stored.
621     allow "crab -copyLocal" or better "crab -copyOutput". TO_DO.
622 spiga 1.1 """
623 spiga 1.8 outFile = open('cmscpReport.sh',"a")
624     cmscp_exit_status = 0
625     txt = ''
626 ewv 1.14 for file, dict in results.iteritems():
627 spiga 1.52 reason = str(dict['reason'])
628     if str(reason).find("'") > -1:
629     reason = " ".join(reason.split("'"))
630     reason="'%s'"%reason
631 ewv 1.14 if file:
632 spiga 1.11 if dict['lfn']=='':
633     lfn = '$LFNBaseName/'+os.path.basename(file)
634     se = '$SE'
635     else:
636 mcinquil 1.16 lfn = dict['lfn']+os.path.basename(file)
637 spiga 1.11 se = dict['se']
638     #dict['lfn'] # to be implemented
639 fanzago 1.39 txt += 'echo "Report for File: '+file+'"\n'
640     txt += 'echo "LFN: '+lfn+'"\n'
641     txt += 'echo "StorageElement: '+se+'"\n'
642 spiga 1.49 txt += 'echo "StageOutExitStatusReason = %s" | tee -a $RUNTIME_AREA/$repo\n'%reason
643 spiga 1.11 txt += 'echo "StageOutSE = '+se+'" >> $RUNTIME_AREA/$repo\n'
644 fanzago 1.42 #txt += 'export LFNBaseName='+lfn+'\n'
645 fanzago 1.39 txt += 'export SE='+se+'\n'
646 fanzago 1.41
647 spiga 1.11 if dict['erCode'] != '0':
648     cmscp_exit_status = dict['erCode']
649 spiga 1.12 else:
650 spiga 1.49 txt += 'echo "StageOutExitStatusReason = %s" | tee -a $RUNTIME_AREA/$repo\n'%reason
651 spiga 1.12 cmscp_exit_status = dict['erCode']
652     cmscp_exit_status = dict['erCode']
653 spiga 1.8 txt += '\n'
654     txt += 'export StageOutExitStatus='+str(cmscp_exit_status)+'\n'
655     txt += 'echo "StageOutExitStatus = '+str(cmscp_exit_status)+'" | tee -a $RUNTIME_AREA/$repo\n'
656     outFile.write(str(txt))
657     outFile.close()
658     return
659    
660    
661     def usage():
662    
663     msg="""
664 spiga 1.46 cmscp:
665     safe copy of local file to/from remote SE via lcg_cp/srmcp,
666     including success checking version also for CAF using rfcp command to copy the output to SE
667 spiga 1.8
668 spiga 1.46 accepted parameters:
669     source =
670     destination =
671     inputFileList =
672     outputFileList =
673     protocol =
674     option =
675     middleware =
676     srm_version =
677     destinationDir =
678     lfn= =
679     local_stage = activate stage fall back
680     debug = activate verbose print out
681     help = print on line man and exit
682    
683     mandatory:
684     * "source" and/or "destination" must always be defined
685     * either "middleware" or "protocol" must always be defined
686     * "inputFileList" must always be defined
687     * if "local_stage" = 1 also "lfn" must be defined
688 spiga 1.8 """
689 ewv 1.14 print msg
690 spiga 1.8
691 ewv 1.14 return
692 spiga 1.8
693     def HelpOptions(opts=[]):
694     """
695     Check otps, print help if needed
696 ewv 1.14 prepare dict = { opt : value }
697 spiga 1.8 """
698     dict_args = {}
699     if len(opts):
700     for opt, arg in opts:
701 ewv 1.14 dict_args[opt.split('--')[1]] = arg
702 spiga 1.8 if opt in ('-h','-help','--help') :
703     usage()
704     sys.exit(0)
705     return dict_args
706     else:
707     usage()
708     sys.exit(0)
709 spiga 1.1
710     if __name__ == '__main__' :
711 spiga 1.8
712 ewv 1.14 import getopt
713 spiga 1.8
714     allowedOpt = ["source=", "destination=", "inputFileList=", "outputFileList=", \
715 spiga 1.25 "protocol=","option=", "middleware=", "srm_version=", \
716 spiga 1.46 "destinationDir=", "lfn=", "local_stage", "debug", "help"]
717 ewv 1.14 try:
718     opts, args = getopt.getopt( sys.argv[1:], "", allowedOpt )
719 spiga 1.8 except getopt.GetoptError, err:
720     print err
721     HelpOptions()
722     sys.exit(2)
723 ewv 1.14
724 spiga 1.8 dictArgs = HelpOptions(opts)
725 spiga 1.1 try:
726 spiga 1.8 cmscp_ = cmscp(dictArgs)
727 spiga 1.1 cmscp_.run()
728 spiga 1.11 except Exception, ex :
729     print str(ex)
730 spiga 1.1