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.27 by fanzago, Wed Sep 16 15:49:01 2009 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  
9   class PhEDExDatasvcInfo:
10 <  """
11 <  provides information from PhEDEx Data Service
12 <  """
13 <  # PhEDEx Data Service URL
14 <  datasvc_url="https://cmsweb.cern.ch/phedex/test/datasvc/xml/prod"
10 >    def __init__( self , cfg_params ):
11 >
12 >        ## PhEDEx Data Service URL
13 >        url="https://cmsweb.cern.ch/phedex/datasvc/xml/prod"
14 >        self.datasvc_url = cfg_params.get("USER.datasvc_url",url)
15 >
16 >        self.FacOps_savannah = 'https://savannah.cern.ch/support/?func=additem&group=cmscompinfrasup'
17 >        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.srm_version = cfg_params.get("USER.srm_version",'srmv2')
21 >        self.node = cfg_params.get('USER.storage_element',None)
22 >        
23 >
24 >
25 >        self.user_lfn = cfg_params.get("USER.lfn",'')
26 >        self.publish_data = cfg_params.get("USER.publish_data",0)
27 >        self.usenamespace = cfg_params.get("USER.usenamespace",0)
28 >        self.user_remote_dir = cfg_params.get("USER.user_remote_dir",'')
29 >        if self.user_remote_dir:
30 >            if ( self.user_remote_dir[-1] != '/' ) : self.user_remote_dir = self.user_remote_dir + '/'
31 >        if self.user_lfn:    
32 >            msg  = 'Warning: lfn has been deprecated, CRAB will ignore it.\n'
33 >            msg += '\t Please use only user_remote_dir removing lfn from your crab.cfg\n'
34 >            msg += '\t For further information please visit : \n\t%s'%stage_out_faq
35 >            common.logger.info(msg)
36 >          
37 >        self.datasetpath = cfg_params.get("CMSSW.datasetpath")
38 >        self.publish_data_name = cfg_params.get('USER.publish_data_name','')
39 >
40 >        self.user_port = cfg_params.get("USER.storage_port",'8443')
41 >        self.user_se_path = cfg_params.get("USER.storage_path",'')
42 >        if self.user_se_path:
43 >            if ( self.user_se_path[-1] != '/' ) : self.user_se_path = self.user_se_path + '/'
44 >                                                    
45 >        #check if using "private" Storage
46 >        self.usePhedex = True
47 >        if not self.node :
48 >            msg = 'Please specify the storage_element name in your crab.cfg section [USER].\n'
49 >            msg +='\tFor further information please visit : %s'%stage_out_faq
50 >            raise CrabException(msg)
51 >        if (self.node.find('T1_') + self.node.find('T2_')+self.node.find('T3_')) == -3: self.usePhedex = False
52 >
53 >        if not self.usePhedex and ( self.user_remote_dir == '' or self.user_se_path == '' ):
54 >            msg = 'You are asking to stage out without using CMS Storage Name convention. In this case you \n'
55 >            msg += '\t must specify both user_remote_dir and storage_path in the crab.cfg section [USER].\n '
56 >            msg += '\t For further information please visit : \n\t%s'%stage_out_faq
57 >            raise CrabException(msg)
58 >        self.sched = common.scheduler.name().upper()
59 >        self.protocol = self.srm_version
60 >
61 >        self.forced_path = '/store/user/'
62 >        if self.sched in ['CAF','LSF']:
63 >            self.protocol = 'direct'
64 >            self.SE = {'CAF':'caf.cern.ch', 'LSF':''}
65 >            if self.sched == 'CAF': self.forced_path = '/store/caf/user/'
66 >            
67 >        if not self.usePhedex:
68 >            self.forced_path = self.user_remote_dir
69 >        return
70 >
71 >    def getEndpoint(self):  
72 >        '''
73 >        Return full SE endpoint and related infos
74 >        '''
75 >        self.lfn = self.getLFN()
76 >
77 >        #extract the PFN for the given node,LFN,protocol
78 >        endpoint = self.getStageoutPFN()
79 >        ### FEDE added a check for the final /
80 >        if ( endpoint[-1] != '/' ) : endpoint = endpoint + '/'
81 >        ######################################
82 >  
83 >        #extract SE name an SE_PATH (needed for publication)
84 >        SE, SE_PATH, User = self.splitEndpoint(endpoint)
85 >
86 >        return endpoint, self.lfn , SE, SE_PATH, User        
87 >      
88 >    def splitEndpoint(self, endpoint):
89 >        '''
90 >        Return relevant infos from endpoint  
91 >        '''
92 >        SE = ''
93 >        SE_PATH = ''
94 >        USER = ''
95 >        if self.usePhedex:
96 >            if self.protocol == 'direct':
97 >                query=endpoint
98 >                SE_PATH = endpoint
99 >                SE = self.SE[self.sched]
100 >            else:
101 >                url = 'http://'+endpoint.split('://')[1]
102 >                # python > 2.4
103 >                # SE = urlparse(url).hostname
104 >                scheme, host, path, params, query, fragment = urlparse(url)
105 >                SE = host.split(':')[0]
106 >                SE_PATH = endpoint.split(host)[1]
107 >            USER = (query.split('user')[1]).split('/')[1]
108 >        else:
109 >            #### to test #####
110 >           # url = 'http://'+endpoint.split('://')[1]
111 >           # scheme, host, path, params, query, fragment = urlparse(url)
112 >           # SE = host.split(':')[0]
113 >           # SE_PATH = endpoint.split(host)[1]
114 >            SE = self.node
115 >            SE_PATH = self.user_se_path + self.user_remote_dir
116 >            try:
117 >                USER = (self.lfn.split('user')[1]).split('/')[1]
118 >            except:
119 >                pass
120 >
121 >        return SE, SE_PATH, USER
122 >  
123 >
124 >    def getLFN(self):
125 >        """
126 >        define the LFN composing the needed pieces
127 >        """
128 >        lfn = ''
129 >        l_User = False
130 >        if not self.usePhedex and (int(self.publish_data) == 0 and int(self.usenamespace) == 0) :
131 >            ### add here check if user is trying to force a wrong LFN using a T2  TODO
132 >            ## check if storage_name is a T2 (siteDB query)
133 >            ## if yes :match self.user_lfn with LFNBaseName...
134 >            ##     if NOT : raise (you are using a T2. It's not allowed stage out into self.user_path+self.user_lfn)  
135 >            lfn = self.user_remote_dir
136 >            return lfn
137 >        if self.publish_data_name == '' and int(self.publish_data) == 1:
138 >            msg = "Error. The [USER] section does not have 'publish_data_name'\n"
139 >            msg += '\tFor further information please visit : \n\t%s'%self.dataPub_faq
140 >            raise CrabException(msg)
141 >        if self.publish_data_name == '' and int(self.usenamespace) == 1:
142 >           self.publish_data_name = "DefaultDataset"
143 >        if int(self.publish_data) == 1:
144 >            if self.sched in ['CAF']: l_User=True
145 >            primaryDataset = self.computePrimaryDataset()
146 >            ### added the case lfn = LFNBase(self.forced_path, primaryDataset, self.publish_data_name, publish=True)
147 >            ### for the publication in order to be able to check the lfn length  
148 >            lfn = LFNBase(self.forced_path, primaryDataset, self.publish_data_name, publish=True)  + '/${PSETHASH}/'    
149 >        elif int(self.usenamespace) == 1:
150 >            if self.sched in ['CAF']: l_User=True
151 >            primaryDataset = self.computePrimaryDataset()
152 >            lfn = LFNBase(self.forced_path, primaryDataset, self.publish_data_name)  + '/${PSETHASH}/'    
153 >        else:
154 >            if self.sched in ['CAF','LSF']: l_User=True
155 >            lfn = LFNBase(self.forced_path,self.user_remote_dir)
156 >        return lfn
157 >
158 >    def computePrimaryDataset(self):
159 >        """
160 >        compute the last part for the LFN in case of publication    
161 >        """
162 >        if (self.datasetpath.upper() != 'NONE'):
163 >            primarydataset = self.datasetpath.split("/")[1]
164 >        else:
165 >            primarydataset = self.publish_data_name
166 >        return primarydataset
167      
168 <  def lfn2pfn(self,node,lfn,protocol):
169 <      """
170 <      PhEDEx Data Service lfn2pfn call
171 <
172 <      input:   LFN,node name,protocol
173 <      returns: DOM object with the content of the PhEDEx Data Service call
174 <      """  
175 <      params = {'node' : node , 'lfn': lfn , 'protocol': protocol}
176 <      params = urllib.urlencode(params)
177 <      #print params
178 <      datasvc_lfn2pfn="%s/lfn2pfn"%self.datasvc_url
179 <      urlresults = urllib.urlopen(datasvc_lfn2pfn, params)
180 <      try:
181 <          urlresults = parse(urlresults)
182 <      except:
183 <          urlresults = None
184 <      return urlresults
185 <
186 <  def parse_error(self,urlresults):
187 <      """
188 <      look for errors in the DOM object returned by PhEDEx Data Service call
189 <      """
190 <      errormsg = None
191 <      errors=urlresults.getElementsByTagName('error')
192 <      for error in errors:
193 <          errormsg=error.childNodes[0].data
194 <          if len(error.childNodes)>1:
195 <             errormsg+=error.childNodes[1].data
196 <      return errormsg
197 <
198 <  def parse_lfn2pfn(self,urlresults):
199 <      """
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)
168 >    def lfn2pfn(self):
169 >        """
170 >        PhEDEx Data Service lfn2pfn call
171 >
172 >        input:   LFN,node name,protocol
173 >        returns: DOM object with the content of the PhEDEx Data Service call
174 >        """  
175 >        params = {'node' : self.node , 'lfn': self.lfn , 'protocol': self.protocol}
176 >        params = urllib.urlencode(params)
177 >        datasvc_lfn2pfn="%s/lfn2pfn"%self.datasvc_url
178 >        try:
179 >            urlresults = urllib.urlopen(datasvc_lfn2pfn, params)
180 >            urlresults = parse(urlresults)
181 >        except IOError:
182 >            msg="Unable to access PhEDEx Data Service at %s"%datasvc_lfn2pfn
183 >            raise CrabException(msg)
184 >        except:
185 >            urlresults = None
186 >
187 >        return urlresults
188 >
189 >    def parse_error(self,urlresults):
190 >        """
191 >        look for errors in the DOM object returned by PhEDEx Data Service call
192 >        """
193 >        errormsg = None
194 >        errors=urlresults.getElementsByTagName('error')
195 >        for error in errors:
196 >            errormsg=error.childNodes[0].data
197 >            if len(error.childNodes)>1:
198 >               errormsg+=error.childNodes[1].data
199 >        return errormsg
200  
201 +    def parse_lfn2pfn(self,urlresults):
202 +        """
203 +        Parse the content of the result of lfn2pfn PhEDEx Data Service  call
204 +
205 +        input:    DOM object with the content of the lfn2pfn call
206 +        returns:  PFN  
207 +        """
208 +        result = urlresults.getElementsByTagName('phedex')
209 +              
210 +        if not result:
211 +              return []
212 +        result = result[0]
213 +        pfn = None
214 +        mapping = result.getElementsByTagName('mapping')
215 +        for m in mapping:
216 +            pfn=m.getAttribute("pfn")
217 +            if pfn:
218 +              return pfn
219 +
220 +    def getStageoutPFN( self ):
221 +        """
222 +        input:   LFN,node name,protocol
223 +        returns: PFN
224 +        """
225 +        if self.usePhedex:
226 +            fullurl="%s/lfn2pfn?node=%s&lfn=%s&protocol=%s"%(self.datasvc_url,self.node,self.lfn,self.protocol)
227 +            domlfn2pfn = self.lfn2pfn()
228 +            if not domlfn2pfn :
229 +                msg="Unable to get info from %s"%fullurl
230 +                raise CrabException(msg)
231 +  
232 +            errormsg = self.parse_error(domlfn2pfn)
233 +            if errormsg:
234 +                msg="Error extracting info from %s due to: %s"%(fullurl,errormsg)
235 +                raise CrabException(msg)
236 +  
237 +            stageoutpfn = self.parse_lfn2pfn(domlfn2pfn)
238 +            if not stageoutpfn:
239 +                msg ='Unable to get stageout path from TFC at Site %s \n'%self.node
240 +                msg+='      Please alert the CompInfraSup group through their savannah %s \n'%self.FacOps_savannah
241 +                msg+='      reporting: \n'
242 +                msg+='       Summary: Unable to get user stageout from TFC at Site %s \n'%self.node
243 +                msg+='       OriginalSubmission: stageout path is not retrieved from %s \n'%fullurl
244 +                raise CrabException(msg)
245 +        else:
246 +            if self.sched in ['CAF','LSF'] :
247 +                stageoutpfn = self.user_se_path+self.lfn
248 +            else:
249 +                stageoutpfn = 'srm://'+self.node+':'+self.user_port+self.user_se_path+self.lfn
250 +
251 +        return stageoutpfn
252 +
253 +
254 +
255 + if __name__ == '__main__':
256 +  """
257 +  Sort of unit testing to check Phedex API for whatever site and/or lfn.
258 +  Usage:
259 +     python PhEDExDatasvcInfo.py --node T2_IT_Bari --lfn /store/maremma
260 +
261 +  """
262 +  import getopt,sys
263 +  from crab_util import *
264 +  import common
265 +  klass_name = 'SchedulerGlite'
266 +  klass = importName(klass_name, klass_name)
267 +  common.scheduler = klass()
268 +
269 +  lfn="/store/user/"
270 +  node='T2_IT_Bari'
271 +  valid = ['node=','lfn=']
272 +  try:
273 +       opts, args = getopt.getopt(sys.argv[1:], "", valid)
274 +  except getopt.GetoptError, ex:
275 +       print str(ex)
276 +       sys.exit(1)
277 +  for o, a in opts:
278 +        if o == "--node":
279 +            node = a
280 +        if o == "--lfn":
281 +            lfn = a
282 +  
283 +  mycfg_params = { 'USER.storage_element': node }
284 +  dsvc = PhEDExDatasvcInfo(mycfg_params)
285 +  dsvc.lfn = lfn
286 +  print dsvc.getStageoutPFN()
287 +

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines