ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/cmscp.py
Revision: 1.68.2.4
Committed: Mon Apr 26 07:35:36 2010 UTC (15 years ago) by spiga
Content type: text/x-python
Branch: CRAB_2_7_1_branch
CVS Tags: CRAB_2_7_2_p1, CRAB_2_7_1_branch_firstMERGE, CRAB_2_7_2
Changes since 1.68.2.3: +1 -1 lines
Log Message:
fix for space_token

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