ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/PhEDExDatasvcInfo.py
(Generate patch)

Comparing COMP/CRAB/python/PhEDExDatasvcInfo.py (file contents):
Revision 1.1 by afanfani, Wed Jun 25 12:03:43 2008 UTC vs.
Revision 1.44 by fanzago, Wed Sep 7 00:25:26 2011 UTC

# Line 1 | Line 1
1 < #!/usr/bin/env python
2 <
1 > from Actor import *
2   import urllib
3   from xml.dom.minidom import parse
4   from crab_exceptions import *
5 + from WorkSpace import *
6 + from urlparse import urlparse
7 + from LFNBaseName import *
8 + from crab_util import getUserName
9  
10   class PhEDExDatasvcInfo:
11 <  """
12 <  provides information from PhEDEx Data Service
13 <  """
14 <  # PhEDEx Data Service URL
15 <  datasvc_url="https://cmsweb.cern.ch/phedex/test/datasvc/xml/prod"
11 >    def __init__( self , cfg_params=None, config=None ):
12 >
13 >        ## PhEDEx Data Service URL
14 >        self.datasvc_url="https://cmsweb.cern.ch/phedex/datasvc/xml/prod"
15 >
16 >        self.FacOps_savannah = 'https://savannah.cern.ch/support/?func=additem&group=cmscompinfrasup'
17 >        self.stage_out_faq='https://twiki.cern.ch/twiki/bin/view/CMS/SWGuideCrabHowTo#Stageout_and_publication'
18 >        self.dataPub_faq = 'https://twiki.cern.ch/twiki/bin/view/CMS/SWGuideCrabForPublication'
19 >
20 >        self.usePhedex = True
21 >        self.sched = common.scheduler.name().upper()
22 >
23 >        if config!=None:
24 >            self.checkConfig(config)  
25 >        else:
26 >            self.checkCfgConfig(cfg_params)  
27 >
28 >        self.protocol = self.srm_version
29 >
30 >
31 >    def checkConfig(self,config):
32 >        """
33 >        """
34 >        self.srm_version = config.get("srm_version",'srmv2')
35 >        self.node = config.get('storage_element',None)
36 >        self.lfn='/store/'
37 >
38 >    def checkCfgConfig(self,cfg_params):
39 >        """
40 >        """
41 >        self.datasvc_url = cfg_params.get("USER.datasvc_url",self.datasvc_url)
42 >        self.srm_version = cfg_params.get("USER.srm_version",'srmv2')
43 >        self.node = cfg_params.get('USER.storage_element',None)
44 >
45 >        self.publish_data = cfg_params.get("USER.publish_data",0)
46 >        self.usenamespace = cfg_params.get("USER.usenamespace",0)
47 >        self.user_remote_dir = cfg_params.get("USER.user_remote_dir",'')
48 >        if self.user_remote_dir:
49 >            if ( self.user_remote_dir[-1] != '/' ) : self.user_remote_dir = self.user_remote_dir + '/'
50 >          
51 >        self.datasetpath = cfg_params.get("CMSSW.datasetpath")
52 >        self.publish_data_name = cfg_params.get('USER.publish_data_name','')
53 >
54 >        self.user_port = cfg_params.get("USER.storage_port",'8443')
55 >        self.user_se_path = cfg_params.get("USER.storage_path",'')
56 >        if self.user_se_path:
57 >            if ( self.user_se_path[-1] != '/' ) : self.user_se_path = self.user_se_path + '/'
58 >                                                    
59 >        #check if using "private" Storage
60 >        if not self.node :
61 >            msg = 'Please specify the storage_element name in your crab.cfg section [USER].\n'
62 >            msg +='\tFor further information please visit : %s'%self.stage_out_faq
63 >            raise CrabException(msg)
64 >        if (self.node.find('T1_') + self.node.find('T2_')+self.node.find('T3_')) == -3: self.usePhedex = False
65 >
66 >        if not self.usePhedex and ( self.user_remote_dir == '' or self.user_se_path == '' ):
67 >            ####### FEDE FOR BUG 73010 ############
68 >            msg =  'Error: task ' + common.work_space._top_dir + ' not correctly created. Please remove it. \n'
69 >            msg += '      You are asking to stage out without using CMS Storage Name convention. In this case you \n'
70 >            msg += '      must specify both user_remote_dir and storage_path in the crab.cfg section [USER].\n'
71 >            msg += '      For further information please visit : \n\t%s'%self.stage_out_faq
72 >            task = common._db.getTask()
73 >            #add = '\n\n'
74 >            #import shutil
75 >            #try:
76 >            #    add += '      Task not correctly created: removing the working_dir ' +  common.work_space._top_dir + ' \n'
77 >            #    shutil.rmtree(common.work_space._top_dir)
78 >            #except OSError:
79 >            #    add += '      Warning: problems removing the working_dir ' + common.work_space._top_dir + ' \n'
80 >            #    add += '      Please remove it by hand'
81 >            #msg += add
82 >            raise CrabException(msg)
83 >
84 >        self.forced_path = '/store/user/'
85 >        if self.sched in ['LSF','PBS']:
86 >            self.srm_version = 'direct'
87 >            self.SE = {'LSF':'', 'PBS':''}
88 >            
89 >        if self.sched == 'CAF':
90 >            #### FEDE TEST FOR XROOTD
91 >            ######### first solution ################
92 >            #eos = cfg_params.get("USER.caf_eos_area", 0)
93 >            #if eos == 0:
94 >            #    self.forced_path = '/store/caf/user/'
95 >            #else:    
96 >            #    self.forced_path = '/store/eos/user'
97 >            #########################################
98 >            ######### second solution ###############
99 >            self.forced_path = cfg_params.get("USER.caf_lfn", '/store/caf/user')
100 >            #########################################
101 >            #print "--->>> FORCING THE FIRST PART OF LFN WITH ", self.forced_path
102 >            self.SE = {'CAF':'caf.cern.ch'}
103 >            self.srm_version = 'stageout'
104 >            #print "--->>> query with 'stageout' "
105 >            #########################################
106 >
107 >        if not self.usePhedex:
108 >            self.forced_path = self.user_remote_dir
109 >        return
110 >
111 >    def getEndpoint(self):  
112 >        '''
113 >        Return full SE endpoint and related infos
114 >        '''
115 >        self.lfn = self.getLFN()
116 >
117 >        #extract the PFN for the given node,LFN,protocol
118 >        endpoint = self.getStageoutPFN()
119 >        if ( endpoint[-1] != '/' ) : endpoint = endpoint + '/'
120 >  
121 >        #extract SE name an SE_PATH (needed for publication)
122 >        SE, SE_PATH, User = self.splitEndpoint(endpoint)
123 >
124 >        #### FEDE FOR XROOTD #####
125 >        #print "in getEndpoint di PhEDExDatasvcInfo.py: "
126 >        #print "    SE = ", SE
127 >        #print "    SE_PATH = ", SE_PATH
128 >        #print "    User = ", User
129 >        #print "    endpoint = ", endpoint
130 >        ##############################
131 >
132 >        return endpoint, self.lfn , SE, SE_PATH, User        
133 >      
134 >    def splitEndpoint(self, endpoint):
135 >        '''
136 >        Return relevant infos from endpoint  
137 >        '''
138 >        SE = ''
139 >        SE_PATH = ''
140 >        USER = getUserName()
141 >        if self.usePhedex:
142 >            ### FEDE PER TEST WITH XROOTD
143 >            if (self.protocol == 'direct' or self.protocol == 'stageout'):
144 >                SE = self.SE[self.sched]
145 >                SE_PATH = endpoint
146 >                #############################  
147 >                #print "    SE_PATH = ", SE_PATH
148 >            else:
149 >                url = 'http://'+endpoint.split('://')[1]
150 >                scheme, host, path, params, query, fragment = urlparse(url)
151 >                SE = self.getAuthoritativeSE()
152 >                SE_PATH = endpoint.split(host)[1]
153 >        else:
154 >            SE = self.node
155 >            SE_PATH = self.user_se_path + self.user_remote_dir
156 >            if self.lfn.find('group') != -1:
157 >                try:
158 >                    USER = (self.lfn.split('group')[1]).split('/')[1]
159 >                except:
160 >                    pass
161 >        return SE, SE_PATH, USER
162 >
163 >    def getLFN(self):
164 >        """
165 >        define the LFN composing the needed pieces
166 >        """
167 >        lfn = ''
168 >        l_User = False
169 >        if not self.usePhedex and (int(self.publish_data) == 0 and int(self.usenamespace) == 0) :
170 >            ### add here check if user is trying to force a wrong LFN using a T2  TODO
171 >            ## check if storage_name is a T2 (siteDB query)
172 >            ## if yes :match self.user_lfn with LFNBaseName...
173 >            ##     if NOT : raise (you are using a T2. It's not allowed stage out into self.user_path+self.user_lfn)  
174 >            lfn = self.user_remote_dir
175 >            return lfn
176 >        if self.publish_data_name == '' and int(self.publish_data) == 1:
177 >            msg = "Error. The [USER] section does not have 'publish_data_name'\n"
178 >            msg += '\tFor further information please visit : \n\t%s'%self.dataPub_faq
179 >            raise CrabException(msg)
180 >        if self.publish_data_name == '' and int(self.usenamespace) == 1:
181 >           self.publish_data_name = "DefaultDataset"
182 >        if int(self.publish_data) == 1:
183 >            if self.sched in ['CAF']: l_User=True
184 >            primaryDataset = self.computePrimaryDataset()
185 >            ### added the case lfn = LFNBase(self.forced_path, primaryDataset, self.publish_data_name, publish=True)
186 >            ### for the publication in order to be able to check the lfn length  
187 >            lfn = LFNBase(self.forced_path, primaryDataset, self.publish_data_name, publish=True)  + '/${PSETHASH}/'    
188 >        elif int(self.usenamespace) == 1:
189 >            if self.sched in ['CAF']: l_User=True
190 >            primaryDataset = self.computePrimaryDataset()
191 >            lfn = LFNBase(self.forced_path, primaryDataset, self.publish_data_name)  + '/${PSETHASH}/'    
192 >        else:
193 >            if self.sched in ['CAF','LSF']: l_User=True
194 >            lfn = LFNBase(self.forced_path,self.user_remote_dir)
195 >        if ( lfn[-1] != '/' ) : lfn = lfn + '/'
196 >        return lfn
197 >
198 >    def computePrimaryDataset(self):
199 >        """
200 >        compute the last part for the LFN in case of publication    
201 >        """
202 >        if (self.datasetpath.upper() != 'NONE'):
203 >            primarydataset = self.datasetpath.split("/")[1]
204 >        else:
205 >            primarydataset = self.publish_data_name
206 >        return primarydataset
207      
208 <  def lfn2pfn(self,node,lfn,protocol):
209 <      """
210 <      PhEDEx Data Service lfn2pfn call
17 <
18 <      input:   LFN,node name,protocol
19 <      returns: DOM object with the content of the PhEDEx Data Service call
20 <      """  
21 <      params = {'node' : node , 'lfn': lfn , 'protocol': protocol}
22 <      params = urllib.urlencode(params)
23 <      #print params
24 <      datasvc_lfn2pfn="%s/lfn2pfn"%self.datasvc_url
25 <      urlresults = urllib.urlopen(datasvc_lfn2pfn, params)
26 <      try:
27 <          urlresults = parse(urlresults)
28 <      except:
29 <          urlresults = None
30 <      return urlresults
31 <
32 <  def parse_error(self,urlresults):
33 <      """
34 <      look for errors in the DOM object returned by PhEDEx Data Service call
35 <      """
36 <      errormsg = None
37 <      errors=urlresults.getElementsByTagName('error')
38 <      for error in errors:
39 <          errormsg=error.childNodes[0].data
40 <          if len(error.childNodes)>1:
41 <             errormsg+=error.childNodes[1].data
42 <      return errormsg
43 <
44 <  def parse_lfn2pfn(self,urlresults):
45 <      """
46 <      Parse the content of the result of lfn2pfn PhEDEx Data Service  call
47 <
48 <      input:    DOM object with the content of the lfn2pfn call
49 <      returns:  PFN  
50 <      """
51 <      result = urlresults.getElementsByTagName('phedex')
52 <      if not result:
53 <            return []
54 <      result = result[0]
55 <      pfn = None
56 <      mapping = result.getElementsByTagName('mapping')
57 <      for m in mapping:
58 <          pfn=m.getAttribute("pfn")
59 <          if pfn:
60 <            return pfn
61 <
62 <  def getStageoutPFN(self,node,lfn,protocol):
63 <      """
64 <      input:   LFN,node name,protocol
65 <      returns: PFN
66 <      """
67 <      fullurl="%s/lfn2pfn?node=%s&lfn=%s&protocol=%s"%(self.datasvc_url,node,lfn,protocol)
68 <      domlfn2pfn = self.lfn2pfn(node,lfn,protocol)
69 <      if not domlfn2pfn :
70 <          msg="Unable to get info from %s"%fullurl
71 <          raise CrabException(msg)
72 <
73 <      errormsg = self.parse_error(domlfn2pfn)
74 <      if errormsg:
75 <          msg="Error extracting info from %s due to: %s"%(fullurl,errormsg)
76 <          raise CrabException(msg)
77 <
78 <      stageoutpfn = self.parse_lfn2pfn(domlfn2pfn)
79 <      if not stageoutpfn:
80 <          msg="Unable to get stageout path (PFN) from %s"%fullurl
81 <          raise CrabException(msg)
82 <      return stageoutpfn
83 <
84 <
85 < if __name__ == '__main__' :
86 <    """
87 <    """
88 <    from crab_logger import Logger
89 <    from WorkSpace import *
90 <    continue_dir="/home/fanfani/CRAB"
91 <    cfg_params={'USER.logdir' : continue_dir }
92 <    common.work_space = WorkSpace(continue_dir, cfg_params)
93 <    log = Logger()
94 <    common.logger = log
95 <
96 <    from LFNBaseName import *
97 <    # test values
98 <    lfn = LFNBase("datasetstring")
99 <    node='T2_IT_Bari'
100 <    protocol="srmv2"
101 <
102 <    #create an instance of the PhEDExDatasvcInfo object
103 <    dsvc = PhEDExDatasvcInfo()
104 <    #extract the PFN for the given node,LFN,protocol
105 <    print "Stageout to %s"%dsvc.getStageoutPFN(node,lfn,protocol)
208 >    def domPhedex(self,params,datasvc_baseUrl):
209 >        """
210 >        PhEDEx Data Service lfn2pfn call
211  
212 +        input:   params,datasvc_baseUrl
213 +        returns: DOM object with the content of the PhEDEx Data Service call
214 +        """  
215 +        params = urllib.urlencode(params)
216 +        try:
217 +            urlresults = urllib.urlopen(datasvc_baseUrl, params)
218 +            urlresults = parse(urlresults)
219 +        except IOError:
220 +            msg="Unable to access PhEDEx Data Service at %s"%datasvc_baseUrl
221 +            raise CrabException(msg)
222 +        except:
223 +            urlresults = None
224 +
225 +        return urlresults
226 +
227 +    def parse_error(self,urlresults):
228 +        """
229 +        look for errors in the DOM object returned by PhEDEx Data Service call
230 +        """
231 +        errormsg = None
232 +        errors=urlresults.getElementsByTagName('error')
233 +        for error in errors:
234 +            errormsg=error.childNodes[0].data
235 +            if len(error.childNodes)>1:
236 +               errormsg+=error.childNodes[1].data
237 +        return errormsg
238 +
239 +    def parse_lfn2pfn(self,urlresults):
240 +        """
241 +        Parse the content of the result of lfn2pfn PhEDEx Data Service  call
242 +
243 +        input:    DOM object with the content of the lfn2pfn call
244 +        returns:  PFN  
245 +        """
246 +        result = urlresults.getElementsByTagName('phedex')
247 +              
248 +        if not result:
249 +              return []
250 +        result = result[0]
251 +        pfn = None
252 +        mapping = result.getElementsByTagName('mapping')
253 +        for m in mapping:
254 +            pfn=m.getAttribute("pfn")
255 +            if pfn:
256 +              return pfn
257 +
258 +    def getStageoutPFN( self ):
259 +        """
260 +        input:   LFN,node name,protocol
261 +        returns: PFN
262 +        """
263 +        if self.usePhedex:
264 +            params = {'node' : self.node , 'lfn': self.lfn , 'protocol': self.protocol}
265 +            datasvc_lfn2pfn="%s/lfn2pfn"%self.datasvc_url
266 +            fullurl="%s/lfn2pfn?node=%s&lfn=%s&protocol=%s"%(self.datasvc_url,self.node,self.lfn,self.protocol)
267 +            #print "--->>> fullurl = ", fullurl
268 +            domlfn2pfn = self.domPhedex(params,datasvc_lfn2pfn)
269 +            if not domlfn2pfn :
270 +                msg="Unable to get info from %s"%fullurl
271 +                raise CrabException(msg)
272 +  
273 +            errormsg = self.parse_error(domlfn2pfn)
274 +            if errormsg:
275 +                msg="Error extracting info from %s due to: %s"%(fullurl,errormsg)
276 +                raise CrabException(msg)
277 +  
278 +            stageoutpfn = self.parse_lfn2pfn(domlfn2pfn)
279 +            if not stageoutpfn:
280 +                msg ='Unable to get stageout path from TFC at Site %s \n'%self.node
281 +                msg+='      Please alert the CompInfraSup group through their savannah %s \n'%self.FacOps_savannah
282 +                msg+='      reporting: \n'
283 +                msg+='       Summary: Unable to get user stageout from TFC at Site %s \n'%self.node
284 +                msg+='       OriginalSubmission: stageout path is not retrieved from %s \n'%fullurl
285 +                raise CrabException(msg)
286 +        else:
287 +            if self.sched in ['CAF','LSF','PBS'] :
288 +                stageoutpfn = self.user_se_path+self.lfn
289 +            else:
290 +                stageoutpfn = 'srm://'+self.node+':'+self.user_port+self.user_se_path+self.lfn
291 +
292 +        if ( stageoutpfn[-1] != '/' ) : stageoutpfn = stageoutpfn + '/'
293 +        return stageoutpfn
294 +
295 +    def getAuthoritativeSE(self):
296 +        """
297 +        input:   node name
298 +        returns: AuthoritativeSE
299 +        """
300 +        params = {'node' : self.node }
301 +        datasvc_nodes="%s/nodes"%self.datasvc_url
302 +        fullurl="%s/nodes/?node=%s"%(self.datasvc_url,self.node)
303 +        domnodes = self.domPhedex(params,datasvc_nodes)
304 +
305 +        if not domnodes :
306 +            msg="Unable to get info from %s"%fullurl
307 +            raise CrabException(msg)
308 +
309 +        errormsg = self.parse_error(domnodes)
310 +        if errormsg:
311 +            msg="Error extracting info from %s due to: %s"%(fullurl,errormsg)
312 +            raise CrabException(msg)
313 +        result = domnodes.getElementsByTagName('phedex')
314 +        if not result:
315 +              return []
316 +        result = result[0]
317 +        se = None
318 +        node = result.getElementsByTagName('node')
319 +        for m in node:
320 +            se=m.getAttribute("se")
321 +            if se:
322 +                return se
323 +
324 +
325 + if __name__ == '__main__':
326 +  """
327 +  Sort of unit testing to check Phedex API for whatever site and/or lfn.
328 +  Usage:
329 +     python PhEDExDatasvcInfo.py --node T2_IT_Bari --lfn /store/maremma
330 +
331 +  """
332 +  import getopt,sys
333 +  from crab_util import *
334 +  import common
335 +  klass_name = 'SchedulerGlite'
336 +  klass = importName(klass_name, klass_name)
337 +  common.scheduler = klass()
338 +
339 +  lfn="/store/user/"
340 +  node='T2_IT_Bari'
341 +  valid = ['node=','lfn=']
342 +  try:
343 +       opts, args = getopt.getopt(sys.argv[1:], "", valid)
344 +  except getopt.GetoptError, ex:
345 +       print str(ex)
346 +       sys.exit(1)
347 +  for o, a in opts:
348 +        if o == "--node":
349 +            node = a
350 +        if o == "--lfn":
351 +            lfn = a
352 +  
353 +  mycfg_params = { 'USER.storage_element': node }
354 +  dsvc = PhEDExDatasvcInfo(mycfg_params)
355 +  dsvc.lfn = lfn
356 +  print dsvc.getStageoutPFN()
357 +

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines