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.61 by spiga, Wed Sep 30 10:32:28 2009 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines