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.16 by mcinquil, Tue Oct 21 09:22:15 2008 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
3 > import sys, os
4 > from ProdCommon.Storage.SEAPI.SElement import SElement, FullPath
5   from ProdCommon.Storage.SEAPI.SBinterface import *
6 <
6 > from ProdCommon.Storage.SEAPI.Exceptions import *
7  
8  
9   class cmscp:
10 <    def __init__(self, argv):
10 >    def __init__(self, args):
11          """
12          cmscp
13  
14 <        safe copy of local file in current directory to remote SE via lcg_cp/srmcp,
14 >        safe copy of local file in current directory to remote SE via lcg_cp/srmcp,
15          including success checking  version also for CAF using rfcp command to copy the output to SE
16          input:
17             $1 middleware (CAF, LSF, LCG, OSG)
18             $2 local file (the absolute path of output file or just the name if it's in top dir)
19             $3 if needed: file name (the output file name)
20             $5 remote SE (complete endpoint)
21 <           $6 srm version
21 >           $6 srm version
22          output:
23               return 0 if all ok
24               return 60307 if srmcp failed
25               return 60303 if file already exists in the SE
26          """
27 +
28          #set default
29 +        self.params = {"source":'', "destination":'', "inputFileList":'', "outputFileList":'', \
30 +                           "protocol":'', "option":'', "middleware":'', "srm_version":'srmv2'}
31          self.debug = 0
32 <        self.source = ''
33 <        self.destination = ''
34 <        self.file_to_copy = []
33 <        self.remote_file_name = []
34 <        self.protocol = ''
35 <        self.middleware = ''
36 <        self.srmv = ''
37 <        self.lcgOpt='-b -D srmv2 --vo cms -t 2400 --verbose'  
38 <        self.opt=''
39 <        try:
40 <            opts, args = getopt.getopt(argv, "", ["source=", "destination=", "inputFileList=", "outputFileList=", \
41 <                                                  "protocol=", "middleware=", "srm_version=", "debug", "help"])
42 <        except getopt.GetoptError:
43 <            print self.usage()
44 <            sys.exit(2)
45 <
46 <        self.setAndCheck(opts)  
47 <        
32 >
33 >        self.params.update( args )
34 >
35          return
36  
37 <    def setAndCheck( self, opts ):
37 >    def processOptions( self ):
38          """
39 <        Set and check command line parameter
39 >        check command line parameter
40          """
41 <        if not opts :
42 <            print self.usage()
43 <            sys.exit()
44 <        for opt, arg in opts :
45 <            if opt  == "--help" :
46 <                print self.usage()
47 <                sys.exit()
48 <            elif opt == "--debug" :
49 <                self.debug = 1
50 <            elif opt == "--source" :
51 <                self.source = arg
52 <            elif opt == "--destination":
53 <                self.destination = arg
54 <            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()
41 >
42 >        if 'help' in self.params.keys(): HelpOptions()
43 >        if 'debug' in self.params.keys(): self.debug = 1
44 >
45 >        # source and dest cannot be undefined at same time
46 >        if not self.params['source']  and not self.params['destination'] :
47 >            HelpOptions()
48 >
49 >        # if middleware is not defined --> protocol cannot be empty
50 >        if not self.params['middleware'] and not self.params['protocol'] :
51 >            HelpOptions()
52 >
53 >        # input file must be defined
54 >        if not self.params['inputFileList'] : HelpOptions()
55          else:
56 <            if infile.find(','):
57 <                [self.file_to_copy.append(x.strip()) for x in infile.split(',')]
58 <            else:
59 <                self.file_to_copy.append(infile)
60 <        
56 >            file_to_copy=[]
57 >            if self.params['inputFileList'].find(','):
58 >                [file_to_copy.append(x.strip()) for x in self.params['inputFileList'].split(',')]
59 >            else:
60 >                file_to_copy.append(self.params['inputFileList'])
61 >            self.params['inputFileList'] = file_to_copy
62 >
63          ## TO DO:
64          #### add check for outFiles
65          #### add map {'inFileNAME':'outFileNAME'} to change out name
66  
67          return
68  
69 <    def run( self ):  
69 >    def run( self ):
70          """
71 <        Check if running on UI (no $middleware) or
72 <        on WN (on the Grid), and take different action  
71 >        Check if running on UI (no $middleware) or
72 >        on WN (on the Grid), and take different action
73          """
107        if self.middleware :  
108           results = self.stager()
109        else:
110           results = self.copy( self.file_to_copy, self.protocol , self.opt)
74  
75 <        self.finalReport(results,self.middleware)
75 >        self.processOptions()
76 >        # stage out from WN
77 >        if self.params['middleware'] :
78 >           results = self.stager(self.params['middleware'],self.params['inputFileList'])
79 >           self.finalReport(results)
80 >        # Local interaction with SE
81 >        else:
82 >           results = self.copy(self.params['inputFilesList'], self.params['protocol'], self.params['option'] )
83 >           return results
84  
85 <        return
115 <    
116 <    def setProtocol( self ):    
85 >    def setProtocol( self, middleware ):
86          """
87          define the allowed potocols based on $middlware
88 <        which depend on scheduler
88 >        which depend on scheduler
89          """
90 <        if self.middleware.lower() in ['osg','lcg']:
91 <            supported_protocol = {'srm-lcg': self.lcgOpt }#,
92 <                               #   'srmv2' : '' }
93 <        elif self.middleware.lower() in ['lsf','caf']:
94 <            supported_protocol = {'rfio': '' }
90 >        # default To be used with "middleware"
91 >        lcgOpt={'srmv1':'-b -D srmv1  -t 2400 --verbose',
92 >                'srmv2':'-b -D srmv2  -t 2400 --verbose'}
93 >        srmOpt={'srmv1':' -report ./srmcp.report -retry_timeout 480000 -retry_num 3 -streams_num=1 ',
94 >                'srmv2':' -report ./srmcp.report -retry_timeout 480000 -retry_num 3 '}
95 >        rfioOpt=''
96 >
97 >        supported_protocol = None
98 >        if middleware.lower() in ['osg','lcg','condor']:
99 >            supported_protocol = [('srm-lcg',lcgOpt[self.params['srm_version']]),\
100 >                                  (self.params['srm_version'],srmOpt[self.params['srm_version']])]
101 >        elif middleware.lower() in ['lsf','caf']:
102 >            supported_protocol = [('rfio',rfioOpt)]
103          else:
104 <            ## here we can add support for any kind of protocol,
104 >            ## here we can add support for any kind of protocol,
105              ## maybe some local schedulers need something dedicated
106              pass
107          return supported_protocol
108  
109 <    def stager( self ):              
109 >    def stager( self, middleware, list_files ):
110          """
111          Implement the logic for remote stage out
112          """
113 <        protocols = self.setProtocol()  
114 <        count=0
115 <        list_files = self.file_to_copy
116 <        results={}  
117 <        for prot in protocols.keys():
118 <            if self.debug: print 'Trying stage out with %s utils \n'%prot
119 <            copy_results = self.copy( list_files, prot, protocols[prot] )
120 <            list_retry = []
121 <            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
113 >        results={}
114 >        for prot, opt in self.setProtocol( middleware ):
115 >            if self.debug: print 'Trying stage out with %s utils \n'%prot
116 >            copy_results = self.copy( list_files, prot, opt )
117 >            list_retry = []
118 >            list_existing = []
119 >            list_ok = []
120 >            if copy_results.keys() == '':
121 >                results.update(copy_results)
122              else:
123 <         #       print 'Copy of files %s failed using %s...\n'%(str(list_retry)+str(list_existing),prot)
124 <                if len(list_retry): list_files = list_retry
125 <                else: break
126 <            count =+1  
127 <
128 <        #### TODO Daniele
123 >                for file, dict in copy_results.iteritems():
124 >                    er_code = dict['erCode']
125 >                    if er_code == '0':
126 >                        list_ok.append(file)
127 >                        reason = 'Copy succedeed with %s utils'%prot
128 >                        upDict = self.updateReport(file, er_code, reason)
129 >                        copy_results.update(upDict)
130 >                    elif er_code == '60303': list_existing.append( file )
131 >                    else: list_retry.append( file )
132 >                results.update(copy_results)
133 >                if len(list_ok) != 0:
134 >                    msg = 'Copy of %s succedeed with %s utils\n'%(str(list_ok),prot)
135 >                    if self.debug : print msg
136 >                if len(list_ok) == len(list_files) :
137 >                    break
138 >                else:
139 >                    if self.debug : print 'Copy of files %s failed using %s...\n'%(str(list_retry)+str(list_existing),prot)
140 >                    if len(list_retry): list_files = list_retry
141 >                    else: break
142 >
143 >        #### TODO Daniele
144          #check is something fails and created related dict
145 <  #      backup = self.analyzeResults(results)
146 <  
147 <  #      if backup :  
145 >  #      backup = self.analyzeResults(results)
146 >
147 >  #      if backup :
148    #          msg = 'WARNING: backup logic is under implementation\n'
149    #          #backupDict = self.backup()
150 <  #          ### NOTE: IT MUST RETURN a DICT contains also LFN and SE Name  
150 >  #          ### NOTE: IT MUST RETURN a DICT contains also LFN and SE Name
151    #          results.update(backupDict)
152    #          print msg
153          return results
154  
155      def initializeApi(self, protocol ):
156          """
157 <        Instantiate storage interface  
157 >        Instantiate storage interface
158          """
159 <        source_prot = protocol
160 <        dest_prot = protocol
161 <        if self.source == '' : source_prot = 'local'
162 <        Source_SE  = self.storageInterface( self.source, source_prot )
163 <        if self.destination == '' : dest_prot = 'local'
164 <        Destination_SE = self.storageInterface( self.destination, dest_prot )
159 >        source_prot = protocol
160 >        dest_prot = protocol
161 >        if not self.params['source'] : source_prot = 'local'
162 >        Source_SE  = self.storageInterface( self.params['source'], source_prot )
163 >        if not self.params['destination'] : dest_prot = 'local'
164 >        Destination_SE = self.storageInterface( self.params['destination'], dest_prot )
165  
166          if self.debug :
167 <            print '(source=%s,  protocol=%s)'%(self.source, source_prot)
168 <            print '(destination=%s,  protocol=%s)'%(self.destination, dest_prot)
167 >            print '(source=%s,  protocol=%s)'%(self.params['source'], source_prot)
168 >            print '(destination=%s,  protocol=%s)'%(self.params['destination'], dest_prot)
169  
170          return Source_SE, Destination_SE
171  
172 <    def copy( self, list_file, protocol, opt):
172 >    def copy( self, list_file, protocol, options ):
173          """
174 <        Make the real file copy using SE API
174 >        Make the real file copy using SE API
175          """
176          if self.debug :
177 <            print 'copy(): using %s protocol'%protocol
178 <        Source_SE, Destination_SE = self.initializeApi( protocol )
177 >            print 'copy(): using %s protocol'%protocol
178 >        try:
179 >            Source_SE, Destination_SE = self.initializeApi( protocol )
180 >        except Exception, ex:
181 >            return self.updateReport('', '-1', str(ex))
182  
183 <        # create remote dir
183 >        # create remote dir
184          if protocol in ['gridftp','rfio']:
185 <            self.createDir( Destination_SE, protocol )
185 >            try:
186 >                self.createDir( Destination_SE, protocol )
187 >            except Exception, ex:
188 >                return self.updateReport('', '60316', str(ex))
189  
190          ## prepare for real copy  ##
191 <        sbi = SBinterface( Source_SE, Destination_SE )
192 <        sbi_dest = SBinterface(Destination_SE)
191 >        try :
192 >            sbi = SBinterface( Source_SE, Destination_SE )
193 >            sbi_dest = SBinterface(Destination_SE)
194 >        except ProtocolMismatch, ex:
195 >            msg = str(ex)+'\n'
196 >            msg += "ERROR : Unable to create SBinterface with %s protocol\n"%protocol
197 >            return self.updateReport('', '-1', str(ex))
198  
199          results = {}
200 <        ## loop over the complete list of files
201 <        for filetocopy in list_file:
200 >        ## loop over the complete list of files
201 >        for filetocopy in list_file:
202              if self.debug : print 'start real copy for %s'%filetocopy
203 <            ErCode, msg = self.checkFileExist( sbi_dest, os.path.basename(filetocopy) )
204 <            if ErCode == '0':
205 <                ErCode, msg = self.makeCopy( sbi, filetocopy , opt)
206 <            if self.debug : print 'Copy results for %s is %s'%( os.path.basename(filetocopy) ,ErCode)
203 >            try :
204 >                ErCode, msg = self.checkFileExist( sbi_dest, os.path.basename(filetocopy) )
205 >            except Exception, ex:
206 >                return self.updateReport(filetocopy, '-1', str(ex))
207 >            if ErCode == '0':
208 >                ErCode, msg = self.makeCopy( sbi, filetocopy , options )
209 >            if self.debug : print 'Copy results for %s is %s'%( os.path.basename(filetocopy), ErCode)
210              results.update( self.updateReport(filetocopy, ErCode, msg))
211          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
212  
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
213  
214      def storageInterface( self, endpoint, protocol ):
215          """
216 <        Create the storage interface.
216 >        Create the storage interface.
217          """
218          try:
219              interface = SElement( FullPath(endpoint), protocol )
220 <        except Exception, ex:
221 <            msg = ''
220 >        except ProtocolUnknown, ex:
221 >            msg = ''
222              if self.debug : msg = str(ex)+'\n'
223 <            msg += "ERROR : Unable to create interface with %s protocol\n"%protocol  
224 <            print msg
223 >            msg += "ERROR : Unable to create interface with %s protocol\n"%protocol
224 >            raise Exception(msg)
225  
226          return interface
227  
284    def checkDir(self, Destination_SE, protocol):
285        '''
286        ToBeImplemented NEEDED for castor
287        '''
288        return
289
228      def createDir(self, Destination_SE, protocol):
229          """
230 <        Create remote dir for gsiftp/rfio REALLY TEMPORARY
231 <        this should be transparent at SE API level.
230 >        Create remote dir for gsiftp REALLY TEMPORARY
231 >        this should be transparent at SE API level.
232          """
233 <        ErCode = '0'
296 <        msg_1 = ''
233 >        msg = ''
234          try:
235              action = SBinterface( Destination_SE )
236              action.createDir()
237 <            if self.debug: print "The directory has been created using protocol %s\n"%protocol
238 <        except Exception, ex:
239 <            msg = ''
240 <            if self.debug : msg = str(ex)+'\n'
241 <            msg_1 = "ERROR: problem with the directory creation using %s protocol \n"%protocol
242 <            msg += msg_1
243 <            ErCode = '60316'  
244 <            #print msg
237 >            if self.debug: msg+= "The directory has been created using protocol %s\n"%protocol
238 >        except TransferException, ex:
239 >            msg = str(ex)
240 >            if self.debug :
241 >                msg += str(ex.detail)+'\n'
242 >                msg += str(ex.output)+'\n'
243 >            msg += "ERROR: problem with the directory creation using %s protocol \n"%protocol
244 >            raise Exceptions(msg)
245 >        except OperationException, ex:
246 >            msg = str(ex)
247 >            if self.debug : msg += str(ex.detail)+'\n'
248 >            msg += "ERROR: problem with the directory creation using %s protocol \n"%protocol
249  
250 <        return ErCode, msg_1
250 >        return msg
251  
252 <    def checkFileExist(self, sbi, filetocopy):
252 >    def checkFileExist( self, sbi, filetocopy ):
253 >        """
254 >        Check if file to copy already exist
255          """
313        Check if file to copy already exist  
314        """
315        try:
316            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
256          ErCode = '0'
257          msg = ''
258 <        if check :
259 <            ErCode = '60303'
258 >        try:
259 >            check = sbi.checkExists(filetocopy)
260 >        except OperationException, ex:
261 >            msg = str(ex)
262 >            if self.debug :
263 >                msg += str(ex.detail)+'\n'
264 >                msg += str(ex.output)+'\n'
265 >            msg +='ERROR: problems checkig if file %s already exist'%filetocopy
266 >            raise Exception(msg)
267 >        except WrongOption, ex:
268 >            msg = str(ex)
269 >            if self.debug :
270 >                msg += str(ex.detail)+'\n'
271 >                msg += str(ex.output)+'\n'
272 >            msg +='ERROR problems checkig if file % already exist'%filetocopy
273 >            raise Exception(msg)
274 >        if check :
275 >            ErCode = '60303'
276              msg = "file %s already exist"%filetocopy
327            print msg
277  
278 <        return ErCode,msg  
278 >        return ErCode, msg
279  
280 <    def makeCopy(self, sbi, filetocopy, opt ):  
280 >    def makeCopy(self, sbi, filetocopy, option ):
281          """
282 <        call the copy API.  
282 >        call the copy API.
283          """
284 <        path = os.path.dirname(filetocopy)  
284 >        path = os.path.dirname(filetocopy)
285          file_name =  os.path.basename(filetocopy)
286          source_file = filetocopy
287          dest_file = file_name ## to be improved supporting changing file name  TODO
288 <        if self.source == '' and path == '':
288 >        if self.params['source'] == '' and path == '':
289              source_file = os.path.abspath(filetocopy)
290 <        elif self.destination =='':
290 >        elif self.params['destination'] =='':
291              dest_file = os.path.join(os.getcwd(),file_name)
292 <        elif self.source != '' and self.destination != '' :
293 <            source_file = file_name  
292 >        elif self.params['source'] != '' and self.params['destination'] != '' :
293 >            source_file = file_name
294 >
295          ErCode = '0'
296          msg = ''
297 <
297 >
298          try:
299 <            pippo = sbi.copy( source_file , dest_file , opt)
300 <            if self.protocol == 'srm' : self.checkSize( sbi, filetocopy )
301 <        except Exception, ex:
302 <            msg = ''
303 <            if self.debug : msg = str(ex)+'\n'
304 <            msg = "Problem copying %s file with %s command"%( filetocopy, protocol )
299 >            sbi.copy( source_file , dest_file , opt = option)
300 >        except TransferException, ex:
301 >            msg = str(ex)
302 >            if self.debug :
303 >                msg += str(ex.detail)+'\n'
304 >                msg += str(ex.output)+'\n'
305 >            msg += "Problem copying %s file" % filetocopy
306 >            ErCode = '60307'
307 >        except WrongOption, ex:
308 >            msg = str(ex)
309 >            if self.debug :
310 >                msg += str(ex.detail)+'\n'
311 >                msg += str(ex.output)+'\n'
312 >            msg += "Problem copying %s file" % filetocopy
313              ErCode = '60307'
314 <            #print msg
314 >
315 >         ## TO BE IMPLEMENTED if NEEDED
316 >         ## NOTE: SE API Already available
317 >    #    if self.protocol.find('srm')  : self.checkSize( sbi, filetocopy )
318  
319          return ErCode, msg
320 <  
321 <    '''
361 <    def checkSize()
362 <        """
363 <        Using srm needed a check of the ouptut file size.  
364 <        """
365 <    
366 <        echo "--> remoteSize = $remoteSize"
367 <        ## for local file
368 <        localSize=$(stat -c%s "$path_out_file")
369 <        echo "-->  localSize = $localSize"
370 <        if [ $localSize != $remoteSize ]; then
371 <            echo "Local fileSize $localSize does not match remote fileSize $remoteSize"
372 <            echo "Copy failed: removing remote file $destination"
373 <                srmrm $destination
374 <                cmscp_exit_status=60307
375 <      
376 <      
377 <                echo "Problem copying $path_out_file to $destination with srmcp command"
378 <                StageOutExitStatusReason='remote and local file dimension not match'
379 <                echo "StageOutReport = `cat ./srmcp.report`"
380 <    '''
381 <    def backup(self):
320 >
321 >    def backup(self):
322          """
323          Check infos from TFC using existing api obtaining:
324          1)destination
# Line 386 | Line 326 | class cmscp:
326          """
327          return
328  
329 <    def usage(self):
329 >    def updateReport(self, file, erCode, reason, lfn='', se='' ):
330 >        """
331 >        Update the final stage out infos
332 >        """
333 >        jobStageInfo={}
334 >        jobStageInfo['erCode']=erCode
335 >        jobStageInfo['reason']=reason
336 >        jobStageInfo['lfn']=lfn
337 >        jobStageInfo['se']=se
338  
339 <        msg="""
340 <        required parameters:
341 <        --source        :: REMOTE           :      
342 <        --destination   :: REMOTE           :  
343 <        --debug             :
344 <        --inFile :: absPath : or name NOT RELATIVE PATH
345 <        --outFIle :: onlyNAME : NOT YET SUPPORTED
398 <
399 <        optional parameters      
339 >        report = { file : jobStageInfo}
340 >        return report
341 >
342 >    def finalReport( self , results ):
343 >        """
344 >        It a list of LFNs for each SE where data are stored.
345 >        allow "crab -copyLocal" or better "crab -copyOutput". TO_DO.
346          """
347 <        return msg
347 >        outFile = open('cmscpReport.sh',"a")
348 >        cmscp_exit_status = 0
349 >        txt = ''
350 >        for file, dict in results.iteritems():
351 >            print file
352 >            print dict
353 >            if file:
354 >                if dict['lfn']=='':
355 >                    lfn = '$LFNBaseName/'+os.path.basename(file)
356 >                    se  = '$SE'
357 >                else:
358 >                    lfn = dict['lfn']+os.path.basename(file)
359 >                    se = dict['se']
360 >                #dict['lfn'] # to be implemented
361 >                txt +=  'echo "Report for File: '+file+'"\n'
362 >                txt +=  'echo "LFN: '+lfn+'"\n'
363 >                txt +=  'echo "StorageElement: '+se+'"\n'
364 >                txt += 'echo "StageOutExitStatusReason ='+dict['reason']+'" | tee -a $RUNTIME_AREA/$repo\n'
365 >                txt += 'echo "StageOutSE = '+se+'" >> $RUNTIME_AREA/$repo\n'
366 >                if dict['erCode'] != '0':
367 >                    cmscp_exit_status = dict['erCode']
368 >                    cmscp_exit_status = dict['erCode']
369 >            else:
370 >                cmscp_exit_status = dict['erCode']
371 >                cmscp_exit_status = dict['erCode']
372 >        txt += '\n'
373 >        txt += 'export StageOutExitStatus='+str(cmscp_exit_status)+'\n'
374 >        txt +=  'echo "StageOutExitStatus = '+str(cmscp_exit_status)+'" | tee -a $RUNTIME_AREA/$repo\n'
375 >        outFile.write(str(txt))
376 >        outFile.close()
377 >        return
378 >
379 >
380 > def usage():
381 >
382 >    msg="""
383 >    required parameters:
384 >    --source        :: REMOTE           :
385 >    --destination   :: REMOTE           :
386 >    --debug             :
387 >    --inFile :: absPath : or name NOT RELATIVE PATH
388 >    --outFIle :: onlyNAME : NOT YET SUPPORTED
389 >
390 >    optional parameters
391 >    """
392 >    print msg
393 >
394 >    return
395 >
396 > def HelpOptions(opts=[]):
397 >    """
398 >    Check otps, print help if needed
399 >    prepare dict = { opt : value }
400 >    """
401 >    dict_args = {}
402 >    if len(opts):
403 >        for opt, arg in opts:
404 >            dict_args[opt.split('--')[1]] = arg
405 >            if opt in ('-h','-help','--help') :
406 >                usage()
407 >                sys.exit(0)
408 >        return dict_args
409 >    else:
410 >        usage()
411 >        sys.exit(0)
412  
413   if __name__ == '__main__' :
414 +
415 +    import getopt
416 +
417 +    allowedOpt = ["source=", "destination=", "inputFileList=", "outputFileList=", \
418 +                  "protocol=","option=", "middleware=", "srm_version=", "debug", "help"]
419 +    try:
420 +        opts, args = getopt.getopt( sys.argv[1:], "", allowedOpt )
421 +    except getopt.GetoptError, err:
422 +        print err
423 +        HelpOptions()
424 +        sys.exit(2)
425 +
426 +    dictArgs = HelpOptions(opts)
427      try:
428 <        cmscp_ = cmscp(sys.argv[1:])
428 >        cmscp_ = cmscp(dictArgs)
429          cmscp_.run()
430 <    except:
431 <        pass
430 >    except Exception, ex :
431 >        print str(ex)
432  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines