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.29 by spiga, Sun Nov 23 16:12:20 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":'','destinationDir':'', "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['inputFileList'], 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 ):              
131 <        """
132 <        Implement the logic for remote stage out
109 > #   def checkCopy(self, copy_results, list_files):
110          """
111 <        protocols = self.setProtocol()  
112 <        count=0
113 <        list_files = self.file_to_copy
114 <        results={}  
115 <        for prot in protocols:
116 <            if self.debug: print 'Trying stage out with %s utils \n'%prot
117 <            copy_results = self.copy( list_files, prot )
141 <            list_retry = []
142 <            list_existing = []
143 <            list_ok = []
111 >        #results={}
112 >        list_retry = []
113 >        list_existing = []
114 >        list_ok = []
115 >        if copy_results.keys() == '':
116 >            self.results.update(copy_results)
117 >        else:
118              for file, dict in copy_results.iteritems():
119                  er_code = dict['erCode']
120 <                if er_code == '60307': list_retry.append( file )
147 <                elif er_code == '60303': list_existing.append( file )
148 <                else:
120 >                if er_code == '0':
121                      list_ok.append(file)
122                      reason = 'Copy succedeed with %s utils'%prot
123                      upDict = self.updateReport(file, er_code, reason)
124 <                    copy_results.update(upDict)
124 >                    copy_results.update(upDict)
125 >                elif er_code == '60303': list_existing.append( file )
126 >                else: list_retry.append( file )
127              results.update(copy_results)
128 <            if len(list_ok) != 0:  
128 >            if len(list_ok) != 0:
129                  msg = 'Copy of %s succedeed with %s utils\n'%(str(list_ok),prot)
130 <               # print msg
131 <            if len(list_ok) == len(list_files) :
132 <                break
130 >                if self.debug : print msg
131 >            if len(list_ok) == len(list_files) :
132 >                msg = 'Copy of  all files succedeed\n'
133 >                #break
134              else:
135 <         #       print 'Copy of files %s failed using %s...\n'%(str(list_retry)+str(list_existing),prot)
136 <                if len(list_retry): list_files = list_retry
137 <                else: break
138 <            count =+1  
139 <
140 <        #### TODO Daniele
135 >                if self.debug : print 'Copy of files %s failed using %s...\n'%(str(list_retry)+str(list_existing),prot)
136 >                #if len(list_retry): list_files = list_retry
137 >        return list_retry, results        
138 >        
139 >        """
140 >    def stager( self, middleware, list_files ):
141 >        """
142 >        Implement the logic for remote stage out
143 >        """
144 >        results={}
145 >        for prot, opt in self.setProtocol( middleware ):
146 >            if self.debug: print 'Trying stage out with %s utils \n'%prot
147 >            copy_results = self.copy( list_files, prot, opt )
148 >            ######## to define a new function checkCopy ################
149 >            #list_retry, self.results = self.checkCopy(copy_results, list_files)
150 >            
151 >        #def checkCopy (self, copy_results):
152 >        #    """
153 >        #    """
154 >        #    results={}
155 >            list_retry = []
156 >            list_existing = []
157 >            list_ok = []
158 >            if copy_results.keys() == '':
159 >                results.update(copy_results)
160 >            else:
161 >                for file, dict in copy_results.iteritems():
162 >                    er_code = dict['erCode']
163 >                    if er_code == '0':
164 >                        list_ok.append(file)
165 >                        reason = 'Copy succedeed with %s utils'%prot
166 >                        upDict = self.updateReport(file, er_code, reason)
167 >                        copy_results.update(upDict)
168 >                    elif er_code == '60303': list_existing.append( file )
169 >                    else: list_retry.append( file )
170 >                results.update(copy_results)
171 >                if len(list_ok) != 0:
172 >                    msg = 'Copy of %s succedeed with %s utils\n'%(str(list_ok),prot)
173 >                    if self.debug : print msg
174 >                if len(list_ok) == len(list_files) :
175 >                    break
176 >                else:
177 >                    if self.debug : print 'Copy of files %s failed using %s...\n'%(str(list_retry)+str(list_existing),prot)
178 >                    if len(list_retry): list_files = list_retry
179 >                    else: break
180 >            """
181 >            if len(list_retry):
182 >               list_files = list_retry
183 >            #def backupCopy(list_retry)
184 >               print "in backup"
185 >               self.params['inputFilesList']=list_files
186 >               ### copy backup
187 >               from ProdCommon.FwkJobRep.SiteLocalConfig import loadSiteLocalConfig
188 >               siteCfg = loadSiteLocalConfig()
189 >               #print siteCfg
190 >               seName = siteCfg.localStageOut.get("se-name", None)
191 >               #print  "seName = ", seName
192 >               self.params['destination']=seName
193 >               #catalog = siteCfg.localStageOut.get("catalog", None)
194 >               #print "catalog = ", catalog
195 >               implName = siteCfg.localStageOut.get("command", None)
196 >               print "implName = ", implName
197 >               if (implName == 'srm'):
198 >                  implName='srmv2'
199 >               self.params['protocol']=implName
200 >               tfc = siteCfg.trivialFileCatalog()
201 >               #print "tfc = ", tfc
202 >               print " self.params['inputFilesList'] = ", self.params['inputFilesList']
203 >               file_backup=[]
204 >               for input in self.params['inputFilesList']:
205 >                   ### to add the correct lfn, passed as argument of cmscp function (--lfn xxxx)
206 >                   file = '/store/'+input
207 >                   pfn = tfc.matchLFN(tfc.preferredProtocol, file)
208 >                   print "pfn = ", pfn
209 >                   file_backup.append(pfn)
210 >               self.params['inputFilesList'] = file_backup
211 >               print "#########################################"
212 >               print "self.params['inputFilesList'] = ", self.params['inputFilesList']
213 >               print "self.params['protocol'] = ", self.params['protocol']
214 >               print "self.params['option'] = ", self.params['option']
215 >               self.copy(self.params['inputFilesList'], self.params['protocol'], self.params['option'])
216 >               print "#########################################"
217 >               ###list_retry, self.results = checkCopy(copy_results)
218 >                   #check is something fails and created related dict
219 >                   #        backup = self.analyzeResults(results)
220 >                   #        if backup :
221 >                   #            msg = 'WARNING: backup logic is under implementation\n'
222 >                   #            #backupDict = self.backup()
223 >                   #            ### NOTE: IT MUST RETURN a DICT contains also LFN and SE Name
224 >                   #            results.update(backupDict)
225 >                   #            print msg
226 >            """
227 >        #### TODO Daniele
228          #check is something fails and created related dict
229 <  #      backup = self.analyzeResults(results)
230 <  
231 <  #      if backup :  
229 >  #      backup = self.analyzeResults(results)
230 >
231 >  #      if backup :
232    #          msg = 'WARNING: backup logic is under implementation\n'
233    #          #backupDict = self.backup()
234 <  #          ### NOTE: IT MUST RETURN a DICT contains also LFN and SE Name  
234 >  #          ### NOTE: IT MUST RETURN a DICT contains also LFN and SE Name
235    #          results.update(backupDict)
236    #          print msg
237          return results
238  
239      def initializeApi(self, protocol ):
240          """
241 <        Instantiate storage interface  
241 >        Instantiate storage interface
242          """
243 <        source_prot = protocol
244 <        dest_prot = protocol
245 <        if self.source == '' : source_prot = 'local'
246 <        Source_SE  = self.storageInterface( self.source, source_prot )
247 <        if self.destination == '' : dest_prot = 'local'
248 <        Destination_SE = self.storageInterface( self.destination, dest_prot )
243 >        self.source_prot = protocol
244 >        self.dest_prot = protocol
245 >        if not self.params['source'] : self.source_prot = 'local'
246 >        Source_SE  = self.storageInterface( self.params['source'], self.source_prot )
247 >        if not self.params['destination'] : self.dest_prot = 'local'
248 >        Destination_SE = self.storageInterface( self.params['destination'], self.dest_prot )
249  
250          if self.debug :
251 <            print '(source=%s,  protocol=%s)'%(self.source, source_prot)
252 <            print '(destination=%s,  protocol=%s)'%(self.destination, dest_prot)
251 >            print '(source=%s,  protocol=%s)'%(self.params['source'], self.source_prot)
252 >            print '(destination=%s,  protocol=%s)'%(self.params['destination'], self.dest_prot)
253  
254          return Source_SE, Destination_SE
255  
256 <    def copy( self, list_file, protocol ):
256 >    def copy( self, list_file, protocol, options ):
257          """
258 <        Make the real file copy using SE API
258 >        Make the real file copy using SE API
259          """
260          if self.debug :
261 <            print 'copy(): using %s protocol'%protocol
262 <        Source_SE, Destination_SE = self.initializeApi( protocol )
261 >            print 'copy(): using %s protocol'%protocol
262 >        try:
263 >            Source_SE, Destination_SE = self.initializeApi( protocol )
264 >        except Exception, ex:
265 >            return self.updateReport('', '-1', str(ex))
266  
267 <        # create remote dir
268 <        if protocol in ['gridftp','rfio']:
269 <            self.createDir( Destination_SE, protocol )
267 >        # create remote dir
268 >        if protocol in ['gridftp','rfio','srmv2']:
269 >            try:
270 >                self.createDir( Destination_SE, protocol )
271 >            except Exception, ex:
272 >                return self.updateReport('', '60316', str(ex))
273  
274          ## prepare for real copy  ##
275 <        sbi = SBinterface( Source_SE, Destination_SE )
276 <        sbi_dest = SBinterface(Destination_SE)
275 >        try :
276 >            sbi = SBinterface( Source_SE, Destination_SE )
277 >            sbi_dest = SBinterface(Destination_SE)
278 >            sbi_source = SBinterface(Source_SE)
279 >        except ProtocolMismatch, ex:
280 >            msg = str(ex)+'\n'
281 >            msg += "ERROR : Unable to create SBinterface with %s protocol\n"%protocol
282 >            return self.updateReport('', '-1', str(ex))
283  
284          results = {}
285 <        ## loop over the complete list of files
286 <        for filetocopy in list_file:
285 >        ## loop over the complete list of files
286 >        for filetocopy in list_file:
287              if self.debug : print 'start real copy for %s'%filetocopy
288 <            ErCode, msg = self.checkFileExist( sbi_dest, os.path.basename(filetocopy) )
289 <            if ErCode == '0':
290 <                ErCode, msg = self.makeCopy( sbi, filetocopy )
291 <            if self.debug : print 'Copy results for %s is %s'%( os.path.basename(filetocopy) ,ErCode)
288 >            try :
289 >                ErCode, msg = self.checkFileExist( sbi_source, sbi_dest, filetocopy )
290 >            except Exception, ex:
291 >                ErCode = -1
292 >                msg = str(ex)  
293 >            if ErCode == '0':
294 >                ErCode, msg = self.makeCopy( sbi, filetocopy , options, protocol,sbi_dest )
295 >            if self.debug : print 'Copy results for %s is %s'%( os.path.basename(filetocopy), ErCode)
296              results.update( self.updateReport(filetocopy, ErCode, msg))
297          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
230
231        report = { file : jobStageInfo}
232        return report
298  
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
299  
300      def storageInterface( self, endpoint, protocol ):
301          """
302 <        Create the storage interface.
302 >        Create the storage interface.
303          """
304          try:
305              interface = SElement( FullPath(endpoint), protocol )
306 <        except Exception, ex:
307 <            msg = ''
306 >        except ProtocolUnknown, ex:
307 >            msg = ''
308              if self.debug : msg = str(ex)+'\n'
309 <            msg += "ERROR : Unable to create interface with %s protocol\n"%protocol  
310 <            print msg
309 >            msg += "ERROR : Unable to create interface with %s protocol\n"%protocol
310 >            raise Exception(msg)
311  
312          return interface
313  
282    def checkDir(self, Destination_SE, protocol):
283        '''
284        ToBeImplemented NEEDED for castor
285        '''
286        return
287
314      def createDir(self, Destination_SE, protocol):
315          """
316 <        Create remote dir for gsiftp/rfio REALLY TEMPORARY
317 <        this should be transparent at SE API level.
316 >        Create remote dir for gsiftp REALLY TEMPORARY
317 >        this should be transparent at SE API level.
318          """
319 <        ErCode = '0'
294 <        msg_1 = ''
319 >        msg = ''
320          try:
321              action = SBinterface( Destination_SE )
322              action.createDir()
323 <            if self.debug: print "The directory has been created using protocol %s\n"%protocol
324 <        except Exception, ex:
325 <            msg = ''
326 <            if self.debug : msg = str(ex)+'\n'
327 <            msg_1 = "ERROR: problem with the directory creation using %s protocol \n"%protocol
328 <            msg += msg_1
329 <            ErCode = '60316'  
330 <            #print msg
331 <
332 <        return ErCode, msg_1
323 >            if self.debug: msg+= "The directory has been created using protocol %s\n"%protocol
324 >        except TransferException, ex:
325 >            msg = str(ex)
326 >            if self.debug :
327 >                msg += str(ex.detail)+'\n'
328 >                msg += str(ex.output)+'\n'
329 >            msg += "ERROR: problem with the directory creation using %s protocol \n"%protocol
330 >            raise Exception(msg)
331 >        except OperationException, ex:
332 >            msg = str(ex)
333 >            if self.debug : msg += str(ex.detail)+'\n'
334 >            msg += "ERROR: problem with the directory creation using %s protocol \n"%protocol
335 >            raise Exception(msg)
336 >        return msg
337  
338 <    def checkFileExist(self, sbi, filetocopy):
338 >    def checkFileExist( self, sbi_source, sbi_dest, filetocopy ):
339 >        """
340 >        Check both if source file exist AND
341 >        if destination file ALREADY exist.
342          """
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
343          ErCode = '0'
344          msg = ''
345 <        if check :
346 <            ErCode = '60303'
347 <            msg = "file %s already exist"%filetocopy
348 <            print msg
345 >        f_tocopy=filetocopy
346 >        if self.source_prot != 'local':f_tocopy = os.path.basename(filetocopy)
347 >        try:
348 >            checkSource = sbi_source.checkExists( f_tocopy )
349 >        except OperationException, ex:
350 >            msg = str(ex)
351 >            if self.debug :
352 >                msg += str(ex.detail)+'\n'
353 >                msg += str(ex.output)+'\n'
354 >            msg +='ERROR: problems checkig if source file %s exist'%filetocopy
355 >            raise Exception(msg)
356 >        except WrongOption, ex:
357 >            msg = str(ex)
358 >            if self.debug :
359 >                msg += str(ex.detail)+'\n'
360 >                msg += str(ex.output)+'\n'
361 >            msg +='ERROR problems checkig if source file % exist'%filetocopy
362 >            raise Exception(msg)
363 >        if not checkSource :
364 >            ErCode = '60302'
365 >            msg = "ERROR file %s do not exist"%os.path.basename(filetocopy)
366 >            return ErCode, msg
367 >        f_tocopy=filetocopy
368 >        if self.dest_prot != 'local':f_tocopy = os.path.basename(filetocopy)
369 >        try:
370 >            check = sbi_dest.checkExists( f_tocopy )
371 >        except OperationException, ex:
372 >            msg = str(ex)
373 >            if self.debug :
374 >                msg += str(ex.detail)+'\n'
375 >                msg += str(ex.output)+'\n'
376 >            msg +='ERROR: problems checkig if file %s already exist'%filetocopy
377 >            raise Exception(msg)
378 >        except WrongOption, ex:
379 >            msg = str(ex)
380 >            if self.debug :
381 >                msg += str(ex.detail)+'\n'
382 >                msg += str(ex.output)+'\n'
383 >            msg +='ERROR problems checkig if file % already exist'%filetocopy
384 >            raise Exception(msg)
385 >        if check :
386 >            ErCode = '60303'
387 >            msg = "file %s already exist"%os.path.basename(filetocopy)
388  
389 <        return ErCode,msg  
389 >        return ErCode, msg
390  
391 <    def makeCopy(self, sbi, filetocopy ):  
391 >    def makeCopy(self, sbi, filetocopy, option, protocol, sbi_dest ):
392          """
393 <        call the copy API.  
393 >        call the copy API.
394          """
395 <        path = os.path.dirname(filetocopy)  
395 >        path = os.path.dirname(filetocopy)
396          file_name =  os.path.basename(filetocopy)
397          source_file = filetocopy
398          dest_file = file_name ## to be improved supporting changing file name  TODO
399 <        if self.source == '' and path == '':
399 >        if self.params['source'] == '' and path == '':
400              source_file = os.path.abspath(filetocopy)
401 <        elif self.destination =='':
402 <            dest_file = os.path.join(os.getcwd(),file_name)
403 <        elif self.source != '' and self.destination != '' :
404 <            source_file = file_name  
401 >        elif self.params['destination'] =='':
402 >            destDir = self.params.get('destinationDir',os.getcwd())
403 >            dest_file = os.path.join(destDir,file_name)
404 >        elif self.params['source'] != '' and self.params['destination'] != '' :
405 >            source_file = file_name
406 >
407          ErCode = '0'
408          msg = ''
409 +
410          try:
411 <            pippo = sbi.copy( source_file , dest_file )
412 <            if self.protocol == 'srm' : self.checkSize( sbi, filetocopy )
413 <        except Exception, ex:
414 <            msg = ''
415 <            if self.debug : msg = str(ex)+'\n'
416 <            msg = "Problem copying %s file with %s command"%( filetocopy, protocol )
411 >            sbi.copy( source_file , dest_file , opt = option)
412 >        except TransferException, ex:
413 >            msg = str(ex)
414 >            if self.debug :
415 >                msg += str(ex.detail)+'\n'
416 >                msg += str(ex.output)+'\n'
417 >            msg += "Problem copying %s file" % filetocopy
418              ErCode = '60307'
419 <            #print msg
420 <
419 >        except WrongOption, ex:
420 >            msg = str(ex)
421 >            if self.debug :
422 >                msg += str(ex.detail)+'\n'
423 >                msg += str(ex.output)+'\n'
424 >            msg += "Problem copying %s file" % filetocopy
425 >            ErCode = '60307'
426 >        if ErCode == '0' and protocol.find('srmv') == 0:
427 >            remote_file_size = -1
428 >            local_file_size = os.path.getsize( source_file )
429 >            try:
430 >                remote_file_size = sbi_dest.getSize( dest_file )
431 >            except TransferException, ex:
432 >                msg = str(ex)
433 >                if self.debug :
434 >                    msg += str(ex.detail)+'\n'
435 >                    msg += str(ex.output)+'\n'
436 >                msg += "Problem checking the size of %s file" % filetocopy
437 >                ErCode = '60307'
438 >            except WrongOption, ex:
439 >                msg = str(ex)
440 >                if self.debug :
441 >                    msg += str(ex.detail)+'\n'
442 >                    msg += str(ex.output)+'\n'
443 >                msg += "Problem checking the size of %s file" % filetocopy
444 >                ErCode = '60307'
445 >            if local_file_size != remote_file_size:
446 >                msg = "File size dosn't match: local size = %s ; remote size = %s " % (local_file_size, remote_file_size)
447 >                ErCode = '60307'
448 >
449 >        if ErCode != '0':
450 >            try :
451 >                self.removeFile( sbi_dest, dest_file )
452 >            except Exception, ex:
453 >                msg += '\n'+str(ex)  
454          return ErCode, msg
455 <  
456 <    '''
457 <    def checkSize()
458 <        """
459 <        Using srm needed a check of the ouptut file size.  
460 <        """
461 <    
462 <        echo "--> remoteSize = $remoteSize"
463 <        ## for local file
464 <        localSize=$(stat -c%s "$path_out_file")
465 <        echo "-->  localSize = $localSize"
466 <        if [ $localSize != $remoteSize ]; then
467 <            echo "Local fileSize $localSize does not match remote fileSize $remoteSize"
468 <            echo "Copy failed: removing remote file $destination"
469 <                srmrm $destination
470 <                cmscp_exit_status=60307
471 <      
472 <      
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):
455 >
456 >    def removeFile( self, sbi_dest, filetocopy ):
457 >
458 >        f_tocopy=filetocopy
459 >        if self.dest_prot != 'local':f_tocopy = os.path.basename(filetocopy)
460 >        try:
461 >            sbi_dest.delete( f_tocopy )
462 >        except OperationException, ex:
463 >            msg = str(ex)
464 >            if self.debug :
465 >                msg += str(ex.detail)+'\n'
466 >                msg += str(ex.output)+'\n'
467 >            msg +='ERROR: problems removing partially staged file %s'%filetocopy
468 >            raise Exception(msg)
469 >
470 >        return
471 >
472 >    def backup(self):
473          """
474          Check infos from TFC using existing api obtaining:
475          1)destination
# Line 383 | Line 477 | class cmscp:
477          """
478          return
479  
480 <    def usage(self):
480 >    def updateReport(self, file, erCode, reason, lfn='', se='' ):
481 >        """
482 >        Update the final stage out infos
483 >        """
484 >        jobStageInfo={}
485 >        jobStageInfo['erCode']=erCode
486 >        jobStageInfo['reason']=reason
487 >        jobStageInfo['lfn']=lfn
488 >        jobStageInfo['se']=se
489 >
490 >        report = { file : jobStageInfo}
491 >        return report
492  
493 <        msg="""
494 <        required parameters:
495 <        --source        :: REMOTE           :      
496 <        --destination   :: REMOTE           :  
392 <        --debug             :
393 <        --inFile :: absPath : or name NOT RELATIVE PATH
394 <        --outFIle :: onlyNAME : NOT YET SUPPORTED
395 <
396 <        optional parameters      
493 >    def finalReport( self , results ):
494 >        """
495 >        It a list of LFNs for each SE where data are stored.
496 >        allow "crab -copyLocal" or better "crab -copyOutput". TO_DO.
497          """
498 <        return msg
498 >        outFile = open('cmscpReport.sh',"a")
499 >        cmscp_exit_status = 0
500 >        txt = ''
501 >        for file, dict in results.iteritems():
502 >            if file:
503 >                if dict['lfn']=='':
504 >                    lfn = '$LFNBaseName/'+os.path.basename(file)
505 >                    se  = '$SE'
506 >                else:
507 >                    lfn = dict['lfn']+os.path.basename(file)
508 >                    se = dict['se']
509 >                #dict['lfn'] # to be implemented
510 >                txt +=  'echo "Report for File: '+file+'"\n'
511 >                txt +=  'echo "LFN: '+lfn+'"\n'
512 >                txt +=  'echo "StorageElement: '+se+'"\n'
513 >                txt += 'echo "StageOutExitStatusReason ='+dict['reason']+'" | tee -a $RUNTIME_AREA/$repo\n'
514 >                txt += 'echo "StageOutSE = '+se+'" >> $RUNTIME_AREA/$repo\n'
515 >                if dict['erCode'] != '0':
516 >                    cmscp_exit_status = dict['erCode']
517 >                    cmscp_exit_status = dict['erCode']
518 >            else:
519 >                cmscp_exit_status = dict['erCode']
520 >                cmscp_exit_status = dict['erCode']
521 >        txt += '\n'
522 >        txt += 'export StageOutExitStatus='+str(cmscp_exit_status)+'\n'
523 >        txt +=  'echo "StageOutExitStatus = '+str(cmscp_exit_status)+'" | tee -a $RUNTIME_AREA/$repo\n'
524 >        outFile.write(str(txt))
525 >        outFile.close()
526 >        return
527 >
528 >
529 > def usage():
530 >
531 >    msg="""
532 >    required parameters:
533 >    --source        :: REMOTE           :
534 >    --destination   :: REMOTE           :
535 >    --debug             :
536 >    --inFile :: absPath : or name NOT RELATIVE PATH
537 >    --outFIle :: onlyNAME : NOT YET SUPPORTED
538 >
539 >    optional parameters
540 >    """
541 >    print msg
542 >
543 >    return
544 >
545 > def HelpOptions(opts=[]):
546 >    """
547 >    Check otps, print help if needed
548 >    prepare dict = { opt : value }
549 >    """
550 >    dict_args = {}
551 >    if len(opts):
552 >        for opt, arg in opts:
553 >            dict_args[opt.split('--')[1]] = arg
554 >            if opt in ('-h','-help','--help') :
555 >                usage()
556 >                sys.exit(0)
557 >        return dict_args
558 >    else:
559 >        usage()
560 >        sys.exit(0)
561  
562   if __name__ == '__main__' :
563 +
564 +    import getopt
565 +
566 +    allowedOpt = ["source=", "destination=", "inputFileList=", "outputFileList=", \
567 +                  "protocol=","option=", "middleware=", "srm_version=", \
568 +                  "destinationDir=","debug", "help"]
569 +    try:
570 +        opts, args = getopt.getopt( sys.argv[1:], "", allowedOpt )
571 +    except getopt.GetoptError, err:
572 +        print err
573 +        HelpOptions()
574 +        sys.exit(2)
575 +
576 +    dictArgs = HelpOptions(opts)
577      try:
578 <        cmscp_ = cmscp(sys.argv[1:])
578 >        cmscp_ = cmscp(dictArgs)
579          cmscp_.run()
580 <    except:
581 <        pass
580 >    except Exception, ex :
581 >        print str(ex)
582  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines