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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines