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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines