ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/cmscp.py
(Generate patch)

Comparing COMP/CRAB/python/cmscp.py (file contents):
Revision 1.4 by spiga, Fri Sep 26 11:15:35 2008 UTC vs.
Revision 1.86 by spiga, Mon Mar 28 09:56:28 2011 UTC

# Line 1 | Line 1
1   #!/usr/bin/env python
2 <
3 < import sys, getopt, string
4 < import os, popen2
5 < from ProdCommon.Storage.SEAPI.SElement import SElement, FullPath
2 > import sys, os
3 > import time, random
4 > try:
5 >    import json
6 > except:    
7 >    import simplejson as json
8 > from ProdCommon.Storage.SEAPI.SElement import SElement, FullPath
9   from ProdCommon.Storage.SEAPI.SBinterface import *
10 <
10 > from ProdCommon.Storage.SEAPI.Exceptions import *
11  
12  
13   class cmscp:
14 <    def __init__(self, argv):
14 >    def __init__(self, args):
15          """
16          cmscp
17 <
15 <        safe copy of local file in current directory to remote SE via lcg_cp/srmcp,
17 >        safe copy of local file  to/from remote SE via lcg_cp/srmcp,
18          including success checking  version also for CAF using rfcp command to copy the output to SE
19          input:
20             $1 middleware (CAF, LSF, LCG, OSG)
21             $2 local file (the absolute path of output file or just the name if it's in top dir)
22             $3 if needed: file name (the output file name)
23             $5 remote SE (complete endpoint)
24 <           $6 srm version
24 >           $6 srm version
25 >           --for_lfn $LFNBaseName
26          output:
27               return 0 if all ok
28               return 60307 if srmcp failed
29               return 60303 if file already exists in the SE
30          """
31 <        #set default
31 >        self.params = {"source":'', "destination":'','destinationDir':'', "inputFileList":'', "outputFileList":'', \
32 >                           "protocol":'', "option":'', "middleware":'', "srm_version":'srmv2', "for_lfn":'', "se_name":'', "surl_for_grid":''}
33          self.debug = 0
34 <        self.source = ''
35 <        self.destination = ''
36 <        self.file_to_copy = []
37 <        self.remote_file_name = []
38 <        self.protocol = ''
39 <        self.middleware = ''
40 <        self.srmv = ''
41 <        self.lcgOpt='-b -D srmv2 --vo cms -t 2400 --verbose'  
42 <        self.opt=''
43 <        try:
44 <            opts, args = getopt.getopt(argv, "", ["source=", "destination=", "inputFileList=", "outputFileList=", \
45 <                                                  "protocol=", "middleware=", "srm_version=", "debug", "help"])
46 <        except getopt.GetoptError:
43 <            print self.usage()
44 <            sys.exit(2)
45 <
46 <        self.setAndCheck(opts)  
47 <        
34 >        #### for fallback copy
35 >        self.local_stage = 0
36 >        self.params.update( args )
37 >        ## timeout needed for subprocess command of SEAPI
38 >        ## they should be a bit higher then the corresponding passed by command line  
39 >        ## default values
40 >        self.subprocesstimeout = { \
41 >                                   'copy':   3600, \
42 >                                   'exists': 1200, \
43 >                                   'delete': 1200, \
44 >                                   'size':   1200 \
45 >                                 }
46 >
47          return
48  
49 <    def setAndCheck( self, opts ):
49 >    def processOptions( self ):
50          """
51 <        Set and check command line parameter
51 >        check command line parameter
52          """
53 <        if not opts :
54 <            print self.usage()
55 <            sys.exit()
56 <        for opt, arg in opts :
57 <            if opt  == "--help" :
58 <                print self.usage()
59 <                sys.exit()
60 <            elif opt == "--debug" :
61 <                self.debug = 1
62 <            elif opt == "--source" :
63 <                self.source = arg
64 <            elif opt == "--destination":
65 <                self.destination = arg
66 <            elif opt == "--inputFileList":
68 <                infile = arg
69 <            elif opt == "--outputFileList":
70 <                out_file
71 <            elif opt == "--protocol":
72 <                self.protocol = arg
73 <            elif opt == "--middleware":
74 <                self.middleware = arg
75 <            elif opt == "--srm_version":
76 <                self.srmv = arg
77 <
78 <        # source and dest cannot be undefined at same time
79 <        if self.source == '' and self.destination == '':
80 <            print self.usage()
81 <            sys.exit()
82 <        # if middleware is not defined --> protocol cannot be empty  
83 <        if self.middleware == '' and self.protocol == '':
84 <            print self.usage()
85 <            sys.exit()
86 <        # input file must be defined  
87 <        if infile == '':
88 <            print self.usage()
89 <            sys.exit()
53 >        if 'help' in self.params.keys(): HelpOptions()
54 >        if 'debug' in self.params.keys(): self.debug = 1
55 >        if 'local_stage' in self.params.keys(): self.local_stage = 1
56 >
57 >        # source and dest cannot be undefined at same time
58 >        if not self.params['source']  and not self.params['destination'] :
59 >            HelpOptions()
60 >        # if middleware is not defined --> protocol cannot be empty
61 >        if not self.params['middleware'] and not self.params['protocol'] :
62 >            HelpOptions()
63 >
64 >        # input file must be defined
65 >        if not self.params['inputFileList'] :
66 >            HelpOptions()
67          else:
68 <            if infile.find(','):
69 <                [self.file_to_copy.append(x.strip()) for x in infile.split(',')]
70 <            else:
71 <                self.file_to_copy.append(infile)
72 <        
73 <        ## TO DO:
97 <        #### add check for outFiles
98 <        #### add map {'inFileNAME':'outFileNAME'} to change out name
68 >            file_to_copy=[]
69 >            if self.params['inputFileList'].find(','):
70 >                [file_to_copy.append(x.strip()) for x in self.params['inputFileList'].split(',')]
71 >            else:
72 >                file_to_copy.append(self.params['inputFileList'])
73 >            self.params['inputFileList'] = file_to_copy
74  
75 <        return
75 >        if not self.params['for_lfn'] and self.local_stage == 1 : HelpOptions()
76 >        
77  
78 <    def run( self ):  
103 <        """
104 <        Check if running on UI (no $middleware) or
105 <        on WN (on the Grid), and take different action  
78 >    def run( self ):
79          """
80 <        if self.middleware :  
81 <           results = self.stager()
80 >        Check if running on UI (no $middleware) or
81 >        on WN (on the Grid), and take different action
82 >        """
83 >        self.processOptions()
84 >        if self.debug: print 'calling run() : \n'
85 >        # stage out from WN
86 >        if self.params['middleware'] :
87 >            results = self.stager(self.params['middleware'],self.params['inputFileList'])
88 >            self.writeJsonFile(results)
89 >            self.finalReport(results)
90 >        # Local interaction with SE
91          else:
92 <           results = self.copy( self.file_to_copy, self.protocol , self.opt)
92 >            results = self.copy(self.params['inputFileList'], self.params['protocol'], self.params['option'] )
93 >            self.writeJsonFile(results)
94 >            return results
95 >            
96 >    def writeJsonFile( self, results ):
97 >        """
98 >        write a json file containing copy results for each file
99 >        """
100 >        if self.debug:
101 >            print 'in writeJsonFile() : \n'
102 >            print "---->>>> in writeJsonFile results =  ", results
103 >        jsonOut = "resultCopyFile"
104 >        if os.getenv("RUNTIME_AREA")
105 >            jsonOut = "%s/resultCopyFile"%os.getenv("RUNTIME_AREA")
106 >        fp = open(jsonOut, 'w')
107 >        json.dump(results, fp)
108 >        fp.close()
109 >        if self.debug:
110 >            print '    reading resultCopyFile : \n'
111 >            lp = open(jsonOut, "r")
112 >            inputDict = json.load(lp)
113 >            lp.close()
114 >            print "    inputDict = ", inputDict
115 >        return
116  
117 <        self.finalReport(results,self.middleware)
117 >    def checkLcgUtils( self ):
118 >        """
119 >        _checkLcgUtils_
120 >        check the lcg-utils version and report
121 >        """
122 >        import commands
123 >        cmd = "lcg-cp --version | grep lcg_util"
124 >        status, output = commands.getstatusoutput( cmd )
125 >        num_ver = -1
126 >        if output.find("not found") == -1 or status == 0:
127 >            temp = output.split("-")
128 >            version = ""
129 >            if len(temp) >= 2:
130 >                version = output.split("-")[1]
131 >                temp = version.split(".")
132 >                if len(temp) >= 1:
133 >                    num_ver = int(temp[0])*10
134 >                    num_ver += int(temp[1])
135 >        return num_ver
136  
137 <        return
115 <    
116 <    def setProtocol( self ):    
137 >    def setProtocol( self, middleware ):
138          """
139          define the allowed potocols based on $middlware
140 <        which depend on scheduler
140 >        which depend on scheduler
141          """
142 <        if self.middleware.lower() in ['osg','lcg']:
143 <            supported_protocol = {'srm-lcg': self.lcgOpt }#,
144 <                               #   'srmv2' : '' }
145 <        elif self.middleware.lower() in ['lsf','caf']:
146 <            supported_protocol = {'rfio': '' }
142 >        # default To be used with "middleware"
143 >        if self.debug:
144 >            print 'setProtocol() :\n'
145 >            print '\tmiddleware =  %s utils \n'%middleware
146 >
147 >        lcgOpt={'srmv1':'-b -D srmv1  -t 2400 --verbose',
148 >                'srmv2':'-b -D srmv2  -t 2400 --verbose'}
149 >        if self.checkLcgUtils() >= 17:
150 >            lcgOpt={'srmv1':'-b -D srmv1 --srm-timeout 2400 --sendreceive-timeout 2400 --connect-timeout 300 --verbose',
151 >                    'srmv2':'-b -D srmv2 --srm-timeout 2400 --sendreceive-timeout 2400 --connect-timeout 300 --verbose'}
152 >
153 >        srmOpt={'srmv1':' -report ./srmcp.report -retry_timeout 480000 -retry_num 3 -streams_num=1 ',
154 >                'srmv2':' -report=./srmcp.report -retry_timeout=480000 -retry_num=3 -storagetype=permanent '}
155 >        rfioOpt=''
156 >
157 >        supported_protocol = None
158 >        if middleware.lower() in ['osg','lcg','condor','sge']:
159 >            supported_protocol = [('srm-lcg',lcgOpt[self.params['srm_version']]),\
160 >                                 (self.params['srm_version'],srmOpt[self.params['srm_version']])]
161 >        elif middleware.lower() in ['lsf','caf']:
162 >            supported_protocol = [('rfio',rfioOpt)]
163 >        elif middleware.lower() in ['pbs']:
164 >            supported_protocol = [('rfio',rfioOpt),('local','')]
165 >        elif middleware.lower() in ['arc']:
166 >            supported_protocol = [('srmv2','-debug'),('srmv1','-debug')]
167          else:
168 <            ## here we can add support for any kind of protocol,
168 >            ## here we can add support for any kind of protocol,
169              ## maybe some local schedulers need something dedicated
170              pass
171          return supported_protocol
172  
173 <    def stager( self ):              
173 >
174 >    def checkCopy (self, copy_results, len_list_files, prot):
175 >        """
176 >        Checks the status of copy and update result dictionary
177 >        """
178 >        
179 >        list_retry = []
180 >        list_not_existing = []
181 >        list_already_existing = []
182 >        list_fallback = []
183 >        list_ok = []
184 >        
185 >        if self.debug:
186 >            print 'in checkCopy() :\n'
187 >        
188 >        for file, dict in copy_results.iteritems():
189 >            er_code = dict['erCode']
190 >            if er_code == '0':
191 >                list_ok.append(file)
192 >                reason = 'Copy succedeed with %s utils'%prot
193 >                dict['reason'] = reason
194 >            elif er_code == '60308':
195 >                list_fallback.append( file )
196 >                reason = 'Copy succedeed with %s utils'%prot
197 >                dict['reason'] = reason
198 >            elif er_code == '60302':
199 >                list_not_existing.append( file )
200 >            elif er_code == '60303':
201 >                list_already_existing.append( file )
202 >            else :    
203 >                list_retry.append( file )
204 >          
205 >            if self.debug:
206 >                print "\t file %s \n"%file
207 >                print "\t dict['erCode'] %s \n"%dict['erCode']
208 >                print "\t dict['reason'] %s \n"%dict['reason']
209 >                
210 >            upDict = self.updateReport(file, er_code, dict['reason'])
211 >
212 >            copy_results.update(upDict)
213 >        
214 >        msg = ''
215 >        if len(list_ok) != 0:
216 >            msg += '\tCopy of %s succedeed with %s utils\n'%(str(list_ok),prot)
217 >        if len(list_ok) != len_list_files :
218 >            if len(list_fallback)!=0:
219 >                msg += '\tCopy of %s succedeed with %s utils in the fallback SE\n'%(str(list_fallback),prot)
220 >            if len(list_retry)!=0:
221 >                msg += '\tCopy of %s failed using %s for files \n'%(str(list_retry),prot)
222 >            if len(list_not_existing)!=0:
223 >                msg += '\tCopy of %s failed using %s : files not found \n'%(str(list_not_existing),prot)
224 >            if len(list_already_existing)!=0:
225 >                msg += '\tCopy of %s failed using %s : files already existing\n'%(str(list_already_existing),prot)
226 >        if self.debug : print msg
227 >        return copy_results, list_ok, list_retry, list_fallback
228 >        
229 >    def check_for_retry_localSE (self, copy_results):
230 >        """
231 >        Checks the status of copy and create the list of file to copy to CloseSE
232 >        """
233 >        list_retry_localSE = []
234 >
235 >        if self.debug:
236 >            print 'in check_for_retry_localSE() :\n'
237 >            print "\t results in check local = ", copy_results
238 >        for file, dict in copy_results.iteritems():
239 >            er_code = dict['erCode']
240 >            if er_code != '0' and  er_code != '60302' and er_code != '60308':
241 >                list_retry_localSE.append( file )
242 >                
243 >            if self.debug:
244 >                print "\t file %s \n"%file
245 >                print "\t dict['erCode'] %s \n"%dict['erCode']
246 >                print "\t dict['reason'] %s \n"%dict['reason']
247 >                
248 >        return list_retry_localSE
249 >
250 >        
251 >    def LocalCopy(self, list_retry, results):
252 >        """
253 >        Tries the stage out to the CloseSE
254 >        """
255 >        if self.debug:
256 >            print 'in LocalCopy() :\n'
257 >            print '\t list_retry %s utils \n'%list_retry
258 >            print '\t len(list_retry) %s \n'%len(list_retry)
259 >                
260 >        list_files = list_retry  
261 >        self.params['inputFileList']=list_files
262 >
263 >        ### copy backup
264 >        from ProdCommon.FwkJobRep.SiteLocalConfig import loadSiteLocalConfig
265 >        siteCfg = loadSiteLocalConfig()
266 >        catalog = siteCfg.localStageOut.get("catalog", None)
267 >        tfc = siteCfg.trivialFileCatalog()
268 >        seName = siteCfg.localStageOutSEName()
269 >        if seName is None:
270 >            seName = ""
271 >        option = siteCfg.localStageOutOption()
272 >        if option is None:
273 >            option = ""
274 >        implName = siteCfg.localStageOutCommand()
275 >        if implName is None:
276 >            implName = ""
277 >
278 >        if (implName == 'srm'):
279 >           protocol = 'srmv2'
280 >        elif (implName == 'srmv2-lcg'):
281 >           protocol = 'srm-lcg'
282 >           option = option + ' -b -D srmv2 '
283 >        elif (implName == 'rfcp-CERN'):
284 >           protocol = 'rfio'
285 >        elif (implName == 'rfcp'):
286 >           protocol = 'rfio'
287 >        elif (implName == 'cp'):
288 >           protocol = 'local'
289 >        else: protocol = implName
290 >        
291 >        self.params['protocol']=protocol
292 >        self.params['option']=option
293 >
294 >        if self.debug:
295 >            print '\t siteCFG %s \n'%siteCfg
296 >            print '\t catalog %s \n'%catalog
297 >            print '\t tfc %s '%tfc
298 >            print '\t fallback seName %s \n'%seName
299 >            print "\t fallback protocol %s \n"%protocol            
300 >            print "\t fallback option %s \n"%option
301 >            print "\t self.params['inputFileList'] %s \n"%self.params['inputFileList']
302 >                
303 >        if (str(self.params['for_lfn']).find("/store/") == 0):
304 >            temp = str(self.params['for_lfn']).replace("/store/","/store/temp/",1)
305 >            self.params['for_lfn']= temp
306 >        
307 >        if ( self.params['for_lfn'][-1] != '/' ) : self.params['for_lfn'] = self.params['for_lfn'] + '/'
308 >            
309 >        file_backup=[]
310 >        file_backup_surlgrid=[]
311 >        for input in self.params['inputFileList']:
312 >            file = self.params['for_lfn'] + os.path.basename(input)
313 >            surl = tfc.matchLFN(tfc.preferredProtocol, file)
314 >            
315 >            ###### FEDE TEST_FOR_SURL_GRID
316 >            surl_for_grid = tfc.matchLFN('srmv2', file)
317 >            if (surl_for_grid == None):
318 >                surl_for_grid = tfc.matchLFN('srmv2-lcg', file)
319 >                if (surl_for_grid == None):
320 >                    surl_for_grid = tfc.matchLFN('srm', file)
321 >            if surl_for_grid:
322 >                file_backup_surlgrid.append(surl_for_grid)
323 >            ######
324 >
325 >            file_backup.append(surl)
326 >            if self.debug:
327 >                print '\t for_lfn %s \n'%self.params['for_lfn']
328 >                print '\t file %s \n'%file
329 >                print '\t surl %s \n'%surl
330 >                    
331 >        destination=os.path.dirname(file_backup[0])
332 >        if ( destination[-1] != '/' ) : destination = destination + '/'
333 >        self.params['destination']=destination
334 >
335 >        self.params['se_name']=seName
336 >
337 >        ######
338 >        if (len(file_backup_surlgrid)>0) :
339 >            surl_for_grid=os.path.dirname(file_backup_surlgrid[0])
340 >            if ( surl_for_grid[-1] != '/' ) : surl_for_grid = surl_for_grid + '/'
341 >        else:
342 >            surl_for_grid=''
343 >
344 >        print "surl_for_grid = ", surl_for_grid    
345 >        self.params['surl_for_grid']=surl_for_grid
346 >        #####
347 >
348 >        if self.debug:
349 >            print '\tIn LocalCopy trying the stage out with: \n'
350 >            print "\tself.params['destination'] %s \n"%self.params['destination']
351 >            print "\tself.params['protocol'] %s \n"%self.params['protocol']
352 >            print "\tself.params['option'] %s \n"%self.params['option']
353 >
354 >        localCopy_results = self.copy( self.params['inputFileList'], self.params['protocol'], self.params['option'], backup='yes' )
355 >          
356 >        if localCopy_results.keys() == [''] or localCopy_results.keys() == '' :
357 >            results.update(localCopy_results)
358 >        else:
359 >            localCopy_results, list_ok, list_retry, list_fallback = self.checkCopy(localCopy_results, len(list_files), self.params['protocol'])
360 >                
361 >            results.update(localCopy_results)
362 >        if self.debug:
363 >            print "\t localCopy_results = %s \n"%localCopy_results
364 >        return results        
365 >
366 >    def stager( self, middleware, list_files ):
367          """
368          Implement the logic for remote stage out
369          """
136        protocols = self.setProtocol()  
137        count=0
138        list_files = self.file_to_copy
139        results={}  
140        for prot in protocols.keys():
141            if self.debug: print 'Trying stage out with %s utils \n'%prot
142            copy_results = self.copy( list_files, prot, protocols[prot] )
143            list_retry = []
144            list_existing = []
145            list_ok = []
146            for file, dict in copy_results.iteritems():
147                er_code = dict['erCode']
148                if er_code == '60307': list_retry.append( file )
149                elif er_code == '60303': list_existing.append( file )
150                else:
151                    list_ok.append(file)
152                    reason = 'Copy succedeed with %s utils'%prot
153                    upDict = self.updateReport(file, er_code, reason)
154                    copy_results.update(upDict)
155            results.update(copy_results)
156            if len(list_ok) != 0:  
157                msg = 'Copy of %s succedeed with %s utils\n'%(str(list_ok),prot)
158               # print msg
159            if len(list_ok) == len(list_files) :
160                break
161            else:
162         #       print 'Copy of files %s failed using %s...\n'%(str(list_retry)+str(list_existing),prot)
163                if len(list_retry): list_files = list_retry
164                else: break
165            count =+1  
370  
371 <        #### TODO Daniele
372 <        #check is something fails and created related dict
373 <  #      backup = self.analyzeResults(results)
374 <  
375 <  #      if backup :  
376 <  #          msg = 'WARNING: backup logic is under implementation\n'
377 <  #          #backupDict = self.backup()
378 <  #          ### NOTE: IT MUST RETURN a DICT contains also LFN and SE Name  
379 <  #          results.update(backupDict)
380 <  #          print msg
371 >        if self.debug:
372 >            print 'stager() :\n'
373 >            print '\tmiddleware %s\n'%middleware
374 >            print '\tlist_files %s\n'%list_files
375 >        
376 >        results={}
377 >        for prot, opt in self.setProtocol( middleware ):
378 >            if self.debug:
379 >                print '\tTrying the stage out with %s utils \n'%prot
380 >                print '\tand options %s\n'%opt
381 >                
382 >            copy_results = self.copy( list_files, prot, opt )
383 >            if copy_results.keys() == [''] or copy_results.keys() == '' :
384 >                results.update(copy_results)
385 >            else:
386 >                copy_results, list_ok, list_retry, list_fallback = self.checkCopy(copy_results, len(list_files), prot)
387 >                results.update(copy_results)
388 >                if len(list_ok) == len(list_files) :
389 >                    break
390 >                if len(list_retry):
391 >                    list_files = list_retry
392 >                    #### FEDE added ramdom time before the retry copy with other protocol
393 >                    sec = 120 * random.random()
394 >                    print "seconds to sleep = " , sec
395 >                    time.sleep(sec)
396 >                else: break
397 >
398 >        if self.local_stage:
399 >            list_retry_localSE = self.check_for_retry_localSE(results)
400 >            if len(list_retry_localSE):
401 >                if self.debug:
402 >                    print "\t list_retry_localSE %s \n"%list_retry_localSE
403 >                results = self.LocalCopy(list_retry_localSE, results)
404 >
405 >        if self.debug:
406 >            print "\t results %s \n"%results
407          return results
408  
409      def initializeApi(self, protocol ):
410          """
411 <        Instantiate storage interface  
411 >        Instantiate storage interface
412          """
413 <        source_prot = protocol
414 <        dest_prot = protocol
415 <        if self.source == '' : source_prot = 'local'
416 <        Source_SE  = self.storageInterface( self.source, source_prot )
417 <        if self.destination == '' : dest_prot = 'local'
418 <        Destination_SE = self.storageInterface( self.destination, dest_prot )
413 >        if self.debug : print 'initializeApi() :\n'  
414 >        self.source_prot = protocol
415 >        self.dest_prot = protocol
416 >        if not self.params['source'] : self.source_prot = 'local'
417 >        Source_SE  = self.storageInterface( self.params['source'], self.source_prot )
418 >        if not self.params['destination'] :
419 >            self.dest_prot = 'local'
420 >            Destination_SE = self.storageInterface( self.params['destinationDir'], self.dest_prot )
421 >        else:    
422 >            Destination_SE = self.storageInterface( self.params['destination'], self.dest_prot )
423  
424          if self.debug :
425 <            print '(source=%s,  protocol=%s)'%(self.source, source_prot)
426 <            print '(destination=%s,  protocol=%s)'%(self.destination, dest_prot)
425 >            msg  = '\t(source=%s,  protocol=%s)'%(self.params['source'], self.source_prot)
426 >            msg += '\t(destination=%s,  protocol=%s)'%(self.params['destination'], self.dest_prot)
427 >            msg += '\t(destinationDir=%s,  protocol=%s)'%(self.params['destinationDir'], self.dest_prot)
428 >            print msg
429  
430          return Source_SE, Destination_SE
431  
432 <    def copy( self, list_file, protocol, opt):
432 >    def copy( self, list_file, protocol, options, backup='no' ):
433          """
434 <        Make the real file copy using SE API
434 >        Make the real file copy using SE API
435          """
436 +        msg = ""
437 +        results = {}
438          if self.debug :
439 <            print 'copy(): using %s protocol'%protocol
440 <        Source_SE, Destination_SE = self.initializeApi( protocol )
441 <
442 <        # create remote dir
443 <        if protocol in ['gridftp','rfio']:
444 <            self.createDir( Destination_SE, protocol )
445 <
439 >            msg  = 'copy() :\n'
440 >            msg += '\tusing %s protocol\n'%protocol
441 >            msg += '\tusing %s options\n'%options
442 >            msg += '\tlist_file %s\n'%list_file
443 >            print msg
444 >        try:
445 >            Source_SE, Destination_SE = self.initializeApi( protocol )
446 >        except Exception, ex:
447 >            for filetocopy in list_file:
448 >                results.update( self.updateReport(filetocopy, '-1', str(ex)))
449 >            return results
450 >
451 >        self.hostname = Destination_SE.hostname
452 >        if Destination_SE.protocol in ['gridftp','rfio','srmv2','hadoop','local']:
453 >            try:
454 >                self.createDir( Destination_SE, Destination_SE.protocol )
455 >            except OperationException, ex:
456 >                for filetocopy in list_file:
457 >                    results.update( self.updateReport(filetocopy, '60316', str(ex)))
458 >                return results
459 >            ## when the client commands are not found (wrong env or really missing)
460 >            except MissingCommand, ex:
461 >                msg = "ERROR %s %s" %(str(ex), str(ex.detail))
462 >                for filetocopy in list_file:
463 >                    results.update( self.updateReport(filetocopy, '10041', msg))
464 >                return results
465 >            except Exception, ex:
466 >                msg = "ERROR %s" %(str(ex))
467 >                for filetocopy in list_file:
468 >                    results.update( self.updateReport(filetocopy, '-1', msg))
469 >                return results
470          ## prepare for real copy  ##
471 <        sbi = SBinterface( Source_SE, Destination_SE )
472 <        sbi_dest = SBinterface(Destination_SE)
473 <
474 <        results = {}
475 <        ## loop over the complete list of files
476 <        for filetocopy in list_file:
477 <            if self.debug : print 'start real copy for %s'%filetocopy
478 <            ErCode, msg = self.checkFileExist( sbi_dest, os.path.basename(filetocopy) )
479 <            if ErCode == '0':
480 <                ErCode, msg = self.makeCopy( sbi, filetocopy , opt)
481 <            if self.debug : print 'Copy results for %s is %s'%( os.path.basename(filetocopy) ,ErCode)
471 >        try :
472 >            sbi = SBinterface( Source_SE, Destination_SE )
473 >            sbi_dest = SBinterface(Destination_SE)
474 >            sbi_source = SBinterface(Source_SE)
475 >        except ProtocolMismatch, ex:
476 >            msg  = "ERROR : Unable to create SBinterface with %s protocol"%protocol
477 >            msg += str(ex)
478 >            for filetocopy in list_file:
479 >                results.update( self.updateReport(filetocopy, '-1', msg))
480 >            return results
481 >
482 >        
483 >        ## loop over the complete list of files
484 >        for filetocopy in list_file:
485 >            if self.debug : print '\tStart real copy for %s'%filetocopy
486 >            try :
487 >                ErCode, msg = self.checkFileExist( sbi_source, sbi_dest, filetocopy, options )
488 >            except Exception, ex:
489 >                ErCode = '60307'
490 >                msg = str(ex)  
491 >            if ErCode == '0':
492 >                ErCode, msg = self.makeCopy( sbi, filetocopy , options, protocol,sbi_dest )
493 >                if (ErCode == '0') and (backup == 'yes'):
494 >                    ErCode = '60308'
495 >            if self.debug : print '\tCopy results for %s is %s'%( os.path.basename(filetocopy), ErCode)
496              results.update( self.updateReport(filetocopy, ErCode, msg))
497          return results
222    
223    def updateReport(self, file, erCode, reason, lfn='', se='' ):
224        """
225        Update the final stage out infos
226        """
227        jobStageInfo={}
228        jobStageInfo['erCode']=erCode
229        jobStageInfo['reason']=reason
230        jobStageInfo['lfn']=lfn
231        jobStageInfo['se']=se
498  
233        report = { file : jobStageInfo}
234        return report
235
236    def finalReport( self , results, middleware ):
237        """
238        It should return a clear list of LFNs for each SE where data are stored.
239        allow "crab -copyLocal" or better "crab -copyOutput". TO_DO.  
240        """
241        if middleware:
242            outFile = open('cmscpReport.sh',"a")
243            cmscp_exit_status = 0
244            txt = ''
245            for file, dict in results.iteritems():
246                if dict['lfn']=='':
247                    lfn = '$LFNBaseName/'+os.path.basename(file)
248                    se  = '$SE'
249                else:
250                    lfn = dict['lfn']+os.pat.basename(file)
251                    se = dict['se']      
252                #dict['lfn'] # to be implemented
253                txt +=  'echo "Report for File: '+file+'"\n'
254                txt +=  'echo "LFN: '+lfn+'"\n'  
255                txt +=  'echo "StorageElement: '+se+'"\n'  
256                txt += 'echo "StageOutExitStatusReason ='+dict['reason']+'" | tee -a $RUNTIME_AREA/$repo\n'
257                txt += 'echo "StageOutSE = '+se+'" >> $RUNTIME_AREA/$repo\n'
258                if dict['erCode'] != '0':
259                    cmscp_exit_status = dict['erCode']
260            txt += '\n'
261            txt += 'export StageOutExitStatus='+str(cmscp_exit_status)+'\n'
262            txt +=  'echo "StageOutExitStatus = '+str(cmscp_exit_status)+'" | tee -a $RUNTIME_AREA/$repo\n'
263            outFile.write(str(txt))
264            outFile.close()
265        else:
266            for file, code in results.iteritems():
267                print 'error code = %s for file %s'%(code,file)
268        return
499  
500      def storageInterface( self, endpoint, protocol ):
501          """
502 <        Create the storage interface.
502 >        Create the storage interface.
503          """
504 +        if self.debug : print 'storageInterface():\n'
505          try:
506              interface = SElement( FullPath(endpoint), protocol )
507 <        except Exception, ex:
508 <            msg = ''
509 <            if self.debug : msg = str(ex)+'\n'
510 <            msg += "ERROR : Unable to create interface with %s protocol\n"%protocol  
280 <            print msg
507 >        except ProtocolUnknown, ex:
508 >            msg  = "ERROR : Unable to create interface with %s protocol"%protocol
509 >            msg += str(ex)
510 >            raise Exception(msg)
511  
512          return interface
513  
284    def checkDir(self, Destination_SE, protocol):
285        '''
286        ToBeImplemented NEEDED for castor
287        '''
288        return
289
514      def createDir(self, Destination_SE, protocol):
515          """
516 <        Create remote dir for gsiftp/rfio REALLY TEMPORARY
517 <        this should be transparent at SE API level.
516 >        Create remote dir for gsiftp REALLY TEMPORARY
517 >        this should be transparent at SE API level.
518          """
519 <        ErCode = '0'
520 <        msg_1 = ''
519 >        if self.debug : print 'createDir():\n'
520 >        msg = ''
521          try:
522              action = SBinterface( Destination_SE )
523              action.createDir()
524 <            if self.debug: print "The directory has been created using protocol %s\n"%protocol
525 <        except Exception, ex:
526 <            msg = ''
527 <            if self.debug : msg = str(ex)+'\n'
528 <            msg_1 = "ERROR: problem with the directory creation using %s protocol \n"%protocol
529 <            msg += msg_1
530 <            ErCode = '60316'  
531 <            #print msg
532 <
533 <        return ErCode, msg_1
524 >            if self.debug: print "\tThe directory has been created using protocol %s"%protocol
525 >        except TransferException, ex:
526 >            msg  = "ERROR: problem with the directory creation using %s protocol "%protocol
527 >            msg += str(ex)
528 >            if self.debug :
529 >                dbgmsg  = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
530 >                dbgmsg += '\t'+str(ex.output)+'\n'
531 >                print dbgmsg
532 >            raise Exception(msg)
533 >        except OperationException, ex:
534 >            msg  = "ERROR: problem with the directory creation using %s protocol "%protocol
535 >            msg += str(ex)
536 >            if self.debug : print '\t'+msg+'\n\t'+str(ex.detail)+'\n'
537 >            raise Exception(msg)
538 >        except MissingDestination, ex:
539 >            msg  = "ERROR: problem with the directory creation using %s protocol "%protocol
540 >            msg += str(ex)
541 >            if self.debug : print '\t'+msg+'\n\t'+str(ex.detail)+'\n'
542 >            raise Exception(msg)
543 >        except AlreadyExistsException, ex:
544 >            if self.debug: print "\tThe directory already exist"
545 >            pass
546 >        except Exception, ex:    
547 >            msg = "ERROR %s %s" %(str(ex), str(ex.detail))
548 >            if self.debug : print '\t'+msg+'\n\t'+str(ex.detail)+'\n'
549 >            raise Exception(msg)
550 >        return msg
551  
552 <    def checkFileExist(self, sbi, filetocopy):
552 >    def checkFileExist( self, sbi_source, sbi_dest, filetocopy, option ):
553          """
554 <        Check if file to copy already exist  
555 <        """
556 <        try:
557 <            check = sbi.checkExists(filetocopy)
317 <        except Exception, ex:
318 <            msg = ''
319 <            if self.debug : msg = str(ex)+'\n'
320 <            msg += "ERROR: problem with check File Exist using %s protocol \n"%protocol
321 <           # print msg
554 >        Check both if source file exist AND
555 >        if destination file ALREADY exist.
556 >        """
557 >        if self.debug : print 'checkFileExist():\n'
558          ErCode = '0'
559          msg = ''
560 <        if check :
561 <            ErCode = '60303'
562 <            msg = "file %s already exist"%filetocopy
563 <            print msg
560 >        f_tocopy=filetocopy
561 >        if self.source_prot != 'local':f_tocopy = os.path.basename(filetocopy)
562 >        try:
563 >            checkSource = sbi_source.checkExists( f_tocopy , opt=option, tout = self.subprocesstimeout['exists'] )
564 >            if self.debug : print '\tCheck for local file %s exist succeded \n'%f_tocopy  
565 >        except OperationException, ex:
566 >            msg  ='ERROR: problems checkig if source file %s exist'%filetocopy
567 >            msg += str(ex)
568 >            if self.debug :
569 >                dbgmsg  = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
570 >                dbgmsg += '\t'+str(ex.output)+'\n'
571 >                print dbgmsg
572 >            raise Exception(msg)
573 >        except WrongOption, ex:
574 >            msg  ='ERROR problems checkig if source file % exist'%filetocopy
575 >            msg += str(ex)
576 >            if self.debug :
577 >                dbgmsg  = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
578 >                dbgmsg += '\t'+str(ex.output)+'\n'
579 >                print dbgmsg
580 >            raise Exception(msg)
581 >        except MissingDestination, ex:
582 >            msg  ='ERROR problems checkig if source file % exist'%filetocopy
583 >            msg += str(ex)
584 >            if self.debug : print '\t'+msg+'\n\t'+str(ex.detail)+'\n'
585 >            raise Exception(msg)
586 >        ## when the client commands are not found (wrong env or really missing)
587 >        except MissingCommand, ex:
588 >            ErCode = '10041'
589 >            msg = "ERROR %s %s" %(str(ex), str(ex.detail))
590 >            return ErCode, msg
591 >        if not checkSource :
592 >            ErCode = '60302'
593 >            msg = "ERROR file %s do not exist"%os.path.basename(filetocopy)
594 >            return ErCode, msg
595 >        f_tocopy=os.path.basename(filetocopy)
596 >        try:
597 >            check = sbi_dest.checkExists( f_tocopy, opt=option, tout = self.subprocesstimeout['exists'] )
598 >            if self.debug : print '\tCheck for remote file %s exist done \n'%f_tocopy  
599 >            if self.debug : print '\twith exit code = %s \n'%check  
600 >        except OperationException, ex:
601 >            msg  = 'ERROR: problems checkig if file %s already exist'%filetocopy
602 >            msg += str(ex)
603 >            if self.debug :
604 >                dbgmsg  = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
605 >                dbgmsg += '\t'+str(ex.output)+'\n'
606 >                print dbgmsg
607 >            raise Exception(msg)
608 >        except WrongOption, ex:
609 >            msg  = 'ERROR problems checkig if file % already exist'%filetocopy
610 >            msg += str(ex)
611 >            if self.debug :
612 >                msg += '\t'+msg+'\n\t'+str(ex.detail)+'\n'
613 >                msg += '\t'+str(ex.output)+'\n'
614 >            raise Exception(msg)
615 >        except MissingDestination, ex:
616 >            msg  ='ERROR problems checkig if source file % exist'%filetocopy
617 >            msg += str(ex)
618 >            if self.debug : print '\t'+msg+'\n\t'+str(ex.detail)+'\n'
619 >            raise Exception(msg)
620 >        ## when the client commands are not found (wrong env or really missing)
621 >        except MissingCommand, ex:
622 >            ErCode = '10041'
623 >            msg = "ERROR %s %s" %(str(ex), str(ex.detail))
624 >            return ErCode, msg
625 >        if check :
626 >            ErCode = '60303'
627 >            msg = "file %s already exist"%os.path.basename(filetocopy)
628  
629 <        return ErCode,msg  
629 >        return ErCode, msg
630  
631 <    def makeCopy(self, sbi, filetocopy, opt ):  
631 >    def makeCopy(self, sbi, filetocopy, option, protocol, sbi_dest ):
632          """
633 <        call the copy API.  
633 >        call the copy API.
634          """
635 <        path = os.path.dirname(filetocopy)  
635 >        if self.debug : print 'makeCopy():\n'
636 >        path = os.path.dirname(filetocopy)
637          file_name =  os.path.basename(filetocopy)
638          source_file = filetocopy
639          dest_file = file_name ## to be improved supporting changing file name  TODO
640 <        if self.source == '' and path == '':
640 >        if self.params['source'] == '' and path == '':
641              source_file = os.path.abspath(filetocopy)
642 <        elif self.destination =='':
643 <            dest_file = os.path.join(os.getcwd(),file_name)
644 <        elif self.source != '' and self.destination != '' :
645 <            source_file = file_name  
642 >        elif self.params['destination'] =='':
643 >            destDir = self.params.get('destinationDir',os.getcwd())
644 >            dest_file = os.path.join(destDir,file_name)
645 >        elif self.params['source'] != '' and self.params['destination'] != '' :
646 >            source_file = file_name
647 >
648          ErCode = '0'
649          msg = ''
650 <
650 >
651 >        copy_option = option
652 >        if  self.params['option'].find('space_token')>=0:
653 >            space_token=self.params['option'].split('=')[1]
654 >            if protocol == 'srmv2': copy_option = '%s -space_token=%s'%(option,space_token)
655 >            if protocol == 'srm-lcg': copy_option = '%s -S %s'%(option,space_token)
656          try:
657 <            pippo = sbi.copy( source_file , dest_file , opt)
658 <            if self.protocol == 'srm' : self.checkSize( sbi, filetocopy )
659 <        except Exception, ex:
660 <            msg = ''
661 <            if self.debug : msg = str(ex)+'\n'
662 <            msg = "Problem copying %s file with %s command"%( filetocopy, protocol )
657 >            sbi.copy( source_file , dest_file , opt = copy_option, tout = self.subprocesstimeout['copy'])
658 >        except TransferException, ex:
659 >            msg  = "Problem copying %s file" % filetocopy
660 >            msg += str(ex)
661 >            if self.debug :
662 >                dbgmsg  = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
663 >                dbgmsg += '\t'+str(ex.output)+'\n'
664 >                print dbgmsg
665              ErCode = '60307'
666 <            #print msg
667 <
666 >        except WrongOption, ex:
667 >            msg  = "Problem copying %s file" % filetocopy
668 >            msg += str(ex)
669 >            if self.debug :
670 >                dbgmsg  = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
671 >                dbgmsg += '\t'+str(ex.output)+'\n'
672 >                print dbgmsg
673 >        except SizeZeroException, ex:
674 >            msg  = "Problem copying %s file" % filetocopy
675 >            msg += str(ex)
676 >            if self.debug :
677 >                dbgmsg  = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
678 >                dbgmsg += '\t'+str(ex.output)+'\n'
679 >                print dbgmsg
680 >            ErCode = '60307'
681 >        ## when the client commands are not found (wrong env or really missing)
682 >        except MissingCommand, ex:
683 >            ErCode = '10041'
684 >            msg  = "Problem copying %s file" % filetocopy
685 >            msg += str(ex)
686 >            if self.debug :
687 >                dbgmsg  = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
688 >                dbgmsg += '\t'+str(ex.output)+'\n'
689 >                print dbgmsg
690 >        except AuthorizationException, ex:
691 >            ErCode = '60307'
692 >            msg  = "Problem copying %s file" % filetocopy
693 >            msg += str(ex)
694 >            if self.debug :
695 >                dbgmsg  = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
696 >                dbgmsg += '\t'+str(ex.output)+'\n'
697 >                print dbgmsg
698 >        except SEAPITimeout, ex:
699 >            ErCode = '60317'
700 >            msg  = "Problem copying %s file" % filetocopy
701 >            msg += str(ex)
702 >            if self.debug :
703 >                dbgmsg  = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
704 >                dbgmsg += '\t'+str(ex.output)+'\n'
705 >                print dbgmsg
706 >
707 >        if ErCode == '0' and protocol.find('srmv') == 0:
708 >            remote_file_size = -1
709 >            local_file_size = os.path.getsize( source_file )
710 >            try:
711 >                remote_file_size = sbi_dest.getSize( dest_file, opt=option, tout = self.subprocesstimeout['size'] )
712 >                if self.debug : print '\t Check of remote size succeded for file %s\n'%dest_file
713 >            except TransferException, ex:
714 >                msg  = "Problem checking the size of %s file" % filetocopy
715 >                msg += str(ex)
716 >                if self.debug :
717 >                    dbgmsg  = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
718 >                    dbgmsg += '\t'+str(ex.output)+'\n'
719 >                    print dbgmsg
720 >                ErCode = '60307'
721 >            except WrongOption, ex:
722 >                msg  = "Problem checking the size of %s file" % filetocopy
723 >                msg += str(ex)
724 >                if self.debug :
725 >                    dbgmsg  = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
726 >                    dbgmsg += '\t'+str(ex.output)+'\n'
727 >                    print dbgmsg
728 >                ErCode = '60307'
729 >            if local_file_size != remote_file_size:
730 >                msg = "File size dosn't match: local size = %s ; remote size = %s " % (local_file_size, remote_file_size)
731 >                ErCode = '60307'
732 >
733 >        if ErCode != '0':
734 >            try :
735 >                self.removeFile( sbi_dest, dest_file, option )
736 >            except Exception, ex:
737 >                msg += '\n'+str(ex)  
738          return ErCode, msg
739 <  
740 <    '''
741 <    def checkSize()
739 >
740 >    def removeFile( self, sbi_dest, filetocopy, option ):
741 >        """  
742 >        """  
743 >        if self.debug : print 'removeFile():\n'
744 >        f_tocopy=filetocopy
745 >        if self.dest_prot != 'local':f_tocopy = os.path.basename(filetocopy)
746 >        try:
747 >            sbi_dest.delete( f_tocopy, opt=option, tout = self.subprocesstimeout['delete'] )
748 >            if self.debug : '\t deletion of file %s succeeded\n'%str(filetocopy)
749 >        except OperationException, ex:
750 >            msg  ='ERROR: problems removing partially staged file %s'%filetocopy
751 >            msg += str(ex)
752 >            if self.debug :
753 >                dbgmsg  = '\t'+msg+'\n\t'+str(ex.detail)+'\n'
754 >                dbgmsg += '\t'+str(ex.output)+'\n'
755 >                print dbgmsg
756 >            raise Exception(msg)
757 >
758 >        return
759 >
760 >    def updateReport(self, file, erCode, reason):
761          """
762 <        Using srm needed a check of the ouptut file size.  
762 >        Update the final stage out infos
763          """
764 <    
765 <        echo "--> remoteSize = $remoteSize"
766 <        ## for local file
767 <        localSize=$(stat -c%s "$path_out_file")
768 <        echo "-->  localSize = $localSize"
769 <        if [ $localSize != $remoteSize ]; then
770 <            echo "Local fileSize $localSize does not match remote fileSize $remoteSize"
771 <            echo "Copy failed: removing remote file $destination"
772 <                srmrm $destination
773 <                cmscp_exit_status=60307
774 <      
775 <      
776 <                echo "Problem copying $path_out_file to $destination with srmcp command"
777 <                StageOutExitStatusReason='remote and local file dimension not match'
778 <                echo "StageOutReport = `cat ./srmcp.report`"
779 <    '''
780 <    def backup(self):
781 <        """
782 <        Check infos from TFC using existing api obtaining:
783 <        1)destination
784 <        2)protocol
764 >        jobStageInfo={}
765 >        jobStageInfo['erCode']=erCode
766 >        jobStageInfo['reason']=reason
767 >        if not self.params['for_lfn']: self.params['for_lfn']=''
768 >        if not self.params['se_name']: self.params['se_name']=''
769 >        if not self.hostname: self.hostname=''
770 >        if (erCode != '0') and (erCode != '60308'):
771 >           jobStageInfo['for_lfn']='/copy_problem/'
772 >        else:  
773 >            jobStageInfo['for_lfn']=self.params['for_lfn']
774 >        jobStageInfo['se_name']=self.params['se_name']
775 >        jobStageInfo['endpoint']=self.hostname
776 >        ### ADDING SURLFORGRID FOR COPYDATA
777 >        if not self.params['surl_for_grid']: self.params['surl_for_grid']=''
778 >        jobStageInfo['surl_for_grid']=self.params['surl_for_grid']
779 >        #####
780 >        report = { file : jobStageInfo}
781 >        return report
782 >
783 >    def finalReport( self , results ):
784 >        """
785 >        It a list of LFNs for each SE where data are stored.
786 >        allow "crab -copyLocal" or better "crab -copyOutput". TO_DO.
787          """
788 +        outFile = open('cmscpReport.sh',"a")
789 +        cmscp_exit_status = 0
790 +        txt = ''
791 +        for file, dict in results.iteritems():
792 +            reason = str(dict['reason'])
793 +            if str(reason).find("'") > -1:
794 +                reason = " ".join(reason.split("'"))
795 +            reason="'%s'"%reason
796 +            if file:
797 +                if dict['for_lfn']=='':
798 +                    lfn = '${LFNBaseName}'+os.path.basename(file)
799 +                    se  = '$SE'
800 +                    LFNBaseName = '$LFNBaseName'
801 +                else:
802 +                    lfn = dict['for_lfn']+os.path.basename(file)
803 +                    se = dict['se_name']
804 +                    LFNBaseName = os.path.dirname(lfn)
805 +                    if (LFNBaseName[-1] != '/'):
806 +                        LFNBaseName = LFNBaseName + '/'
807 +
808 +                
809 +                txt += 'echo "Report for File: '+file+'"\n'
810 +                txt += 'echo "LFN: '+lfn+'"\n'
811 +                txt += 'echo "StorageElement: '+se+'"\n'
812 +                txt += 'echo "StageOutExitStatusReason = %s" | tee -a $RUNTIME_AREA/$repo\n'%reason
813 +                txt += 'echo "StageOutSE = '+se+'" >> $RUNTIME_AREA/$repo\n'
814 +
815 +                
816 +                if dict['erCode'] != '0':
817 +                    cmscp_exit_status = dict['erCode']
818 +            else:
819 +                txt += 'echo "StageOutExitStatusReason = %s" | tee -a $RUNTIME_AREA/$repo\n'%reason
820 +                cmscp_exit_status = dict['erCode']
821 +        txt += '\n'
822 +        txt += 'export StageOutExitStatus='+str(cmscp_exit_status)+'\n'
823 +        txt += 'echo "StageOutExitStatus = '+str(cmscp_exit_status)+'" | tee -a $RUNTIME_AREA/$repo\n'
824 +        outFile.write(str(txt))
825 +        outFile.close()
826          return
827  
389    def usage(self):
828  
829 <        msg="""
830 <        required parameters:
831 <        --source        :: REMOTE           :      
832 <        --destination   :: REMOTE           :  
833 <        --debug             :
834 <        --inFile :: absPath : or name NOT RELATIVE PATH
835 <        --outFIle :: onlyNAME : NOT YET SUPPORTED
836 <
837 <        optional parameters      
838 <        """
839 <        return msg
829 > def usage():
830 >
831 >    msg="""
832 >    cmscp:
833 >        safe copy of local file  to/from remote SE via lcg_cp/srmcp,
834 >        including success checking  version also for CAF using rfcp command to copy the output to SE
835 >
836 >    accepted parameters:
837 >       source           =
838 >       destination      =
839 >       inputFileList    =
840 >       outputFileList   =
841 >       protocol         =
842 >       option           =
843 >       middleware       =  
844 >       srm_version      =
845 >       destinationDir   =
846 >       lfn=             =
847 >       local_stage      =  activate stage fall back  
848 >       debug            =  activate verbose print out
849 >       help             =  print on line man and exit  
850 >    
851 >    mandatory:
852 >       * "source" and/or "destination" must always be defined
853 >       * either "middleware" or "protocol" must always be defined
854 >       * "inputFileList" must always be defined
855 >       * if "local_stage" = 1 also  "lfn" must be defined
856 >    """
857 >    print msg
858 >
859 >    return
860 >
861 > def HelpOptions(opts=[]):
862 >    """
863 >    Check otps, print help if needed
864 >    prepare dict = { opt : value }
865 >    """
866 >    dict_args = {}
867 >    if len(opts):
868 >        for opt, arg in opts:
869 >            dict_args[opt.split('--')[1]] = arg
870 >            if opt in ('-h','-help','--help') :
871 >                usage()
872 >                sys.exit(0)
873 >        return dict_args
874 >    else:
875 >        usage()
876 >        sys.exit(0)
877  
878   if __name__ == '__main__' :
879 +
880 +    import getopt
881 +
882 +    allowedOpt = ["source=", "destination=", "inputFileList=", "outputFileList=", \
883 +                  "protocol=","option=", "middleware=", "srm_version=", \
884 +                  "destinationDir=", "for_lfn=", "local_stage", "debug", "help", "se_name="]
885 +    try:
886 +        opts, args = getopt.getopt( sys.argv[1:], "", allowedOpt )
887 +    except getopt.GetoptError, err:
888 +        print err
889 +        HelpOptions()
890 +        sys.exit(2)
891 +
892 +    dictArgs = HelpOptions(opts)
893      try:
894 <        cmscp_ = cmscp(sys.argv[1:])
894 >        cmscp_ = cmscp(dictArgs)
895          cmscp_.run()
896 <    except:
897 <        pass
896 >    except Exception, ex :
897 >        print str(ex)
898  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines