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.3 by spiga, Fri Sep 26 07:38:41 2008 UTC vs.
Revision 1.17 by mcinquil, Tue Oct 21 10:21:11 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 <  
38 <        try:
39 <            opts, args = getopt.getopt(argv, "", ["source=", "destination=", "inputFileList=", "outputFileList=", \
40 <                                                  "protocol=", "middleware=", "srm_version=", "debug", "help"])
41 <        except getopt.GetoptError:
42 <            print self.usage()
43 <            sys.exit(2)
44 <
45 <        self.setAndCheck(opts)  
46 <        
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":
67 <                infile = arg
68 <            elif opt == "--outputFileList":
69 <                out_file
70 <            elif opt == "--protocol":
71 <                self.protocol = arg
72 <            elif opt == "--middleware":
73 <                self.middleware = arg
74 <            elif opt == "--srm_version":
75 <                self.srmv = arg
76 <
77 <        # source and dest cannot be undefined at same time
78 <        if self.source == '' and self.destination == '':
79 <            print self.usage()
80 <            sys.exit()
81 <        # if middleware is not defined --> protocol cannot be empty  
82 <        if self.middleware == '' and self.protocol == '':
83 <            print self.usage()
84 <            sys.exit()
85 <        # input file must be defined  
86 <        if infile == '':
87 <            print self.usage()
88 <            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          """
106        if self.middleware :  
107           results = self.stager()
108        else:
109           results = self.copy( self.file_to_copy, self.protocol )
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
114 <    
115 <    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','srmv2']
92 <        elif self.middleware.lower() in ['lsf','caf']:
93 <            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:
118 <            if self.debug: print 'Trying stage out with %s utils \n'%prot
119 <            copy_results = self.copy( list_files, prot )
120 <            list_retry = []
121 <            list_existing = []
143 <            list_ok = []
144 <            for file, dict in copy_results.iteritems():
145 <                er_code = dict['erCode']
146 <                if er_code == '60307': list_retry.append( file )
147 <                elif er_code == '60303': list_existing.append( file )
148 <                else:
149 <                    list_ok.append(file)
150 <                    reason = 'Copy succedeed with %s utils'%prot
151 <                    upDict = self.updateReport(file, er_code, reason)
152 <                    copy_results.update(upDict)
153 <            results.update(copy_results)
154 <            if len(list_ok) != 0:  
155 <                msg = 'Copy of %s succedeed with %s utils\n'%(str(list_ok),prot)
156 <               # print msg
157 <            if len(list_ok) == len(list_files) :
158 <                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 ):
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 )
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
220    
221    def updateReport(self, file, erCode, reason, lfn='', se='' ):
222        """
223        Update the final stage out infos
224        """
225        jobStageInfo={}
226        jobStageInfo['erCode']=erCode
227        jobStageInfo['reason']=reason
228        jobStageInfo['lfn']=lfn
229        jobStageInfo['se']=se
212  
231        report = { file : jobStageInfo}
232        return report
233
234    def finalReport( self , results, middleware ):
235        """
236        It should return a clear list of LFNs for each SE where data are stored.
237        allow "crab -copyLocal" or better "crab -copyOutput". TO_DO.  
238        """
239        if middleware:
240            outFile = open('cmscpReport.sh',"a")
241            cmscp_exit_status = 0
242            txt = ''
243            for file, dict in results.iteritems():
244                if dict['lfn']=='':
245                    lfn = '$LFNBaseName/'+os.path.basename(file)
246                    se  = '$SE'
247                else:
248                    lfn = dict['lfn']+os.pat.basename(file)
249                    se = dict['se']      
250                #dict['lfn'] # to be implemented
251                txt +=  'echo "Report for File: '+file+'"\n'
252                txt +=  'echo "LFN: '+lfn+'"\n'  
253                txt +=  'echo "StorageElement: '+se+'"\n'  
254                txt += 'echo "StageOutExitStatusReason ='+dict['reason']+'" | tee -a $RUNTIME_AREA/$repo\n'
255                txt += 'echo "StageOutSE = '+se+'" >> $RUNTIME_AREA/$repo\n'
256                if dict['erCode'] != '0':
257                    cmscp_exit_status = dict['erCode']
258            txt += '\n'
259            txt += 'export StageOutExitStatus='+str(cmscp_exit_status)+'\n'
260            txt +=  'echo "StageOutExitStatus = '+str(cmscp_exit_status)+'" | tee -a $RUNTIME_AREA/$repo\n'
261            outFile.write(str(txt))
262            outFile.close()
263        else:
264            for file, code in results.iteritems():
265                print 'error code = %s for file %s'%(code,file)
266        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  
282    def checkDir(self, Destination_SE, protocol):
283        '''
284        ToBeImplemented NEEDED for castor
285        '''
286        return
287
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'
294 <        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          """
311        Check if file to copy already exist  
312        """
313        try:
314            check = sbi.checkExists(filetocopy)
315        except Exception, ex:
316            msg = ''
317            if self.debug : msg = str(ex)+'\n'
318            msg += "ERROR: problem with check File Exist using %s protocol \n"%protocol
319           # 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
325            print msg
277  
278 <        return ErCode,msg  
278 >        return ErCode, msg
279  
280 <    def makeCopy(self, sbi, filetocopy ):  
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 +
298          try:
299 <            pippo = sbi.copy( source_file , dest_file )
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 <    '''
358 <    def checkSize()
359 <        """
360 <        Using srm needed a check of the ouptut file size.  
361 <        """
362 <    
363 <        echo "--> remoteSize = $remoteSize"
364 <        ## for local file
365 <        localSize=$(stat -c%s "$path_out_file")
366 <        echo "-->  localSize = $localSize"
367 <        if [ $localSize != $remoteSize ]; then
368 <            echo "Local fileSize $localSize does not match remote fileSize $remoteSize"
369 <            echo "Copy failed: removing remote file $destination"
370 <                srmrm $destination
371 <                cmscp_exit_status=60307
372 <      
373 <      
374 <                echo "Problem copying $path_out_file to $destination with srmcp command"
375 <                StageOutExitStatusReason='remote and local file dimension not match'
376 <                echo "StageOutReport = `cat ./srmcp.report`"
377 <    '''
378 <    def backup(self):
320 >
321 >    def backup(self):
322          """
323          Check infos from TFC using existing api obtaining:
324          1)destination
# Line 383 | 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
395 <
396 <        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 >            if file:
352 >                if dict['lfn']=='':
353 >                    lfn = '$LFNBaseName/'+os.path.basename(file)
354 >                    se  = '$SE'
355 >                else:
356 >                    lfn = dict['lfn']+os.path.basename(file)
357 >                    se = dict['se']
358 >                #dict['lfn'] # to be implemented
359 >                txt +=  'echo "Report for File: '+file+'"\n'
360 >                txt +=  'echo "LFN: '+lfn+'"\n'
361 >                txt +=  'echo "StorageElement: '+se+'"\n'
362 >                txt += 'echo "StageOutExitStatusReason ='+dict['reason']+'" | tee -a $RUNTIME_AREA/$repo\n'
363 >                txt += 'echo "StageOutSE = '+se+'" >> $RUNTIME_AREA/$repo\n'
364 >                if dict['erCode'] != '0':
365 >                    cmscp_exit_status = dict['erCode']
366 >                    cmscp_exit_status = dict['erCode']
367 >            else:
368 >                cmscp_exit_status = dict['erCode']
369 >                cmscp_exit_status = dict['erCode']
370 >        txt += '\n'
371 >        txt += 'export StageOutExitStatus='+str(cmscp_exit_status)+'\n'
372 >        txt +=  'echo "StageOutExitStatus = '+str(cmscp_exit_status)+'" | tee -a $RUNTIME_AREA/$repo\n'
373 >        outFile.write(str(txt))
374 >        outFile.close()
375 >        return
376 >
377 >
378 > def usage():
379 >
380 >    msg="""
381 >    required parameters:
382 >    --source        :: REMOTE           :
383 >    --destination   :: REMOTE           :
384 >    --debug             :
385 >    --inFile :: absPath : or name NOT RELATIVE PATH
386 >    --outFIle :: onlyNAME : NOT YET SUPPORTED
387 >
388 >    optional parameters
389 >    """
390 >    print msg
391 >
392 >    return
393 >
394 > def HelpOptions(opts=[]):
395 >    """
396 >    Check otps, print help if needed
397 >    prepare dict = { opt : value }
398 >    """
399 >    dict_args = {}
400 >    if len(opts):
401 >        for opt, arg in opts:
402 >            dict_args[opt.split('--')[1]] = arg
403 >            if opt in ('-h','-help','--help') :
404 >                usage()
405 >                sys.exit(0)
406 >        return dict_args
407 >    else:
408 >        usage()
409 >        sys.exit(0)
410  
411   if __name__ == '__main__' :
412 +
413 +    import getopt
414 +
415 +    allowedOpt = ["source=", "destination=", "inputFileList=", "outputFileList=", \
416 +                  "protocol=","option=", "middleware=", "srm_version=", "debug", "help"]
417 +    try:
418 +        opts, args = getopt.getopt( sys.argv[1:], "", allowedOpt )
419 +    except getopt.GetoptError, err:
420 +        print err
421 +        HelpOptions()
422 +        sys.exit(2)
423 +
424 +    dictArgs = HelpOptions(opts)
425      try:
426 <        cmscp_ = cmscp(sys.argv[1:])
426 >        cmscp_ = cmscp(dictArgs)
427          cmscp_.run()
428 <    except:
429 <        pass
428 >    except Exception, ex :
429 >        print str(ex)
430  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines