ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/cmscp.py
Revision: 1.68
Committed: Thu Jan 28 13:02:03 2010 UTC (15 years, 3 months ago) by fanzago
Content type: text/x-python
Branch: MAIN
CVS Tags: fede_170310, CRAB_2_7_1_pre9, CRAB_LumiMask, CRAB_2_7_lumi, from_LimiMask, CRAB_2_7_1_pre8, CRAB_2_7_1_pre6, CRAB_2_7_1_pre5, CRAB_2_7_1_wmbs_pre4
Branch point for: CRAB_multiout, CRAB_2_7_1_branch
Changes since 1.67: +2 -2 lines
Log Message:
the cmscp_exit_code check outside if, for savannah bug 61870

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