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

Comparing COMP/CRAB/python/DataDiscovery.py (file contents):
Revision 1.30 by spiga, Tue Mar 31 22:36:42 2009 UTC vs.
Revision 1.49 by ewv, Mon Aug 30 10:36:33 2010 UTC

# Line 1 | Line 1
1   #!/usr/bin/env python
2 +
3 + __revision__ = "$Id$"
4 + __version__ = "$Revision$"
5 +
6   import exceptions
7   import DBSAPI.dbsApi
8 < from DBSAPI.dbsApiException import *
8 > from DBSAPI.dbsApiException import *
9   import common
10   from crab_util import *
11 < import os
11 > try: # Can remove when CMSSW 3.7 and earlier are dropped
12 >    from FWCore.PythonUtilities.LumiList import LumiList
13 > except ImportError:
14 >    from LumiList import LumiList
15 >
16 > import os
17 >
18  
19  
10 # #######################################
20   class DBSError(exceptions.Exception):
21      def __init__(self, errorName, errorMessage):
22          args='\nERROR DBS %s : %s \n'%(errorName,errorMessage)
23          exceptions.Exception.__init__(self, args)
24          pass
25 <    
25 >
26      def getErrorMessage(self):
27          """ Return error message """
28          return "%s" % (self.args)
29  
30 < # #######################################
30 >
31 >
32   class DBSInvalidDataTierError(exceptions.Exception):
33      def __init__(self, errorName, errorMessage):
34          args='\nERROR DBS %s : %s \n'%(errorName,errorMessage)
35          exceptions.Exception.__init__(self, args)
36          pass
37 <    
37 >
38      def getErrorMessage(self):
39          """ Return error message """
40          return "%s" % (self.args)
41  
42 < # #######################################
42 >
43 >
44   class DBSInfoError:
45      def __init__(self, url):
46          print '\nERROR accessing DBS url : '+url+'\n'
47          pass
48  
49 < # ####################################
49 >
50 >
51   class DataDiscoveryError(exceptions.Exception):
52      def __init__(self, errorMessage):
53          self.args=errorMessage
# Line 46 | Line 58 | class DataDiscoveryError(exceptions.Exce
58          """ Return exception error """
59          return "%s" % (self.args)
60  
61 < # ####################################
61 >
62 >
63   class NotExistingDatasetError(exceptions.Exception):
64      def __init__(self, errorMessage):
65          self.args=errorMessage
# Line 57 | Line 70 | class NotExistingDatasetError(exceptions
70          """ Return exception error """
71          return "%s" % (self.args)
72  
73 < # ####################################
73 >
74 >
75   class NoDataTierinProvenanceError(exceptions.Exception):
76      def __init__(self, errorMessage):
77          self.args=errorMessage
# Line 68 | Line 82 | class NoDataTierinProvenanceError(except
82          """ Return exception error """
83          return "%s" % (self.args)
84  
85 < # ####################################
86 < # class to find and extact info from published data
85 >
86 >
87   class DataDiscovery:
88 +    """
89 +    Class to find and extact info from published data
90 +    """
91      def __init__(self, datasetPath, cfg_params, skipAnBlocks):
92  
93          #       Attributes
94          self.datasetPath = datasetPath
95 +        # Analysis dataset is primary/processed/tier/definition
96 +        self.ads = len(self.datasetPath.split("/")) > 4
97          self.cfg_params = cfg_params
98          self.skipBlocks = skipAnBlocks
99  
100          self.eventsPerBlock = {}  # DBS output: map fileblocks-events for collection
101          self.eventsPerFile = {}   # DBS output: map files-events
102 <        self.blocksinfo = {}      # DBS output: map fileblocks-files
102 > #         self.lumisPerBlock = {}   # DBS output: number of lumis in each block
103 > #         self.lumisPerFile = {}    # DBS output: number of lumis in each file
104 >        self.blocksinfo = {}      # DBS output: map fileblocks-files
105          self.maxEvents = 0        # DBS output: max events
106 <        self.parent = {}       # DBS output: max events
106 >        self.maxLumis = 0         # DBS output: total number of lumis
107 >        self.parent = {}          # DBS output: parents of each file
108 >        self.lumis = {}           # DBS output: lumis in each file
109 >        self.lumiMask = None
110 >        self.splitByLumi = False
111 >        self.splitDataByEvent = 0
112  
87 # ####################################
113      def fetchDBSInfo(self):
114          """
115          Contact DBS
116          """
117          ## get DBS URL
118          global_url="http://cmsdbsprod.cern.ch/cms_dbs_prod_global/servlet/DBSServlet"
119 <        caf_url = "http://cmsdbsprod.cern.ch/cms_dbs_caf_analysis_01/servlet/DBSServlet"
120 <        dbs_url_map  =   {'glite':    global_url,
96 <                          'glitecoll':global_url,\
97 <                          'condor':   global_url,\
98 <                          'condor_g': global_url,\
99 <                          'glidein':  global_url,\
100 <                          'lsf':      global_url,\
101 <                          'caf':      caf_url,\
102 <                          'sge':      global_url,
103 <                          'arc':      global_url
104 <                          }
105 <
106 <        dbs_url_default = dbs_url_map[(common.scheduler.name()).lower()]
107 <        dbs_url=  self.cfg_params.get('CMSSW.dbs_url', dbs_url_default)
108 <        common.logger.debug(3,"Accessing DBS at: "+dbs_url)
119 >        dbs_url=  self.cfg_params.get('CMSSW.dbs_url', global_url)
120 >        common.logger.info("Accessing DBS at: "+dbs_url)
121  
122          ## check if runs are selected
123          runselection = []
124          if (self.cfg_params.has_key('CMSSW.runselection')):
125              runselection = parseRange2(self.cfg_params['CMSSW.runselection'])
126  
127 +        ## check if various lumi parameters are set
128 +        self.lumiMask = self.cfg_params.get('CMSSW.lumi_mask',None)
129 +        self.lumiParams = self.cfg_params.get('CMSSW.total_number_of_lumis',None) or \
130 +                          self.cfg_params.get('CMSSW.lumis_per_job',None)
131 +
132 +        lumiList = None
133 +        if self.lumiMask:
134 +            lumiList = LumiList(filename=self.lumiMask)
135 +        if runselection:
136 +            runList = LumiList(runs = runselection)
137  
138          self.splitByRun = int(self.cfg_params.get('CMSSW.split_by_run', 0))
139 <          
140 <        self.ads = int(self.cfg_params.get('CMSSW.ads', 0))
139 >        self.splitDataByEvent = int(self.cfg_params.get('CMSSW.split_by_event', 0))
140 >        common.logger.log(10-1,"runselection is: %s"%runselection)
141 >
142 >        if not self.splitByRun:
143 >            self.splitByLumi = self.lumiMask or self.lumiParams or self.ads
144 >
145 >        if self.splitByRun and not runselection:
146 >            msg = "Error: split_by_run must be combined with a runselection"
147 >            raise CrabException(msg)
148  
120        common.logger.debug(6,"runselection is: %s"%runselection)
149          ## service API
150          args = {}
151          args['url']     = dbs_url
# Line 126 | Line 154 | class DataDiscovery:
154          ## check if has been requested to use the parent info
155          useparent = int(self.cfg_params.get('CMSSW.use_parent',0))
156  
157 <        ## check if has been asked for a non default file to store/read analyzed fileBlocks  
158 <        defaultName = common.work_space.shareDir()+'AnalyzedBlocks.txt'  
157 >        ## check if has been asked for a non default file to store/read analyzed fileBlocks
158 >        defaultName = common.work_space.shareDir()+'AnalyzedBlocks.txt'
159          fileBlocks_FileName = os.path.abspath(self.cfg_params.get('CMSSW.fileblocks_file',defaultName))
132
133        api = DBSAPI.dbsApi.DbsApi(args)
160  
161 +        api = DBSAPI.dbsApi.DbsApi(args)
162          self.files = self.queryDbs(api,path=self.datasetPath,runselection=runselection,useParent=useparent)
163  
164 +        # Check to see what the dataset is
165 +        pdsName = self.datasetPath.split("/")[1]
166 +        primDSs = api.listPrimaryDatasets(pdsName)
167 +        dataType = primDSs[0]['Type']
168 +        common.logger.debug("Datatype is %s" % dataType)
169 +        if dataType == 'data' and not \
170 +            (self.splitByRun or self.splitByLumi or self.splitDataByEvent):
171 +            msg = 'Data must be split by lumi or by run. ' \
172 +                  'Please see crab -help for the correct settings'
173 +            raise  CrabException(msg)
174 +
175 +
176 +
177          anFileBlocks = []
178 <        if self.skipBlocks: anFileBlocks = readTXTfile(self, fileBlocks_FileName)
178 >        if self.skipBlocks: anFileBlocks = readTXTfile(self, fileBlocks_FileName)
179  
180          # parse files and fill arrays
181          for file in self.files :
182 <            parList = []
182 >            parList  = []
183 >            fileLumis = [] # List of tuples
184              # skip already analyzed blocks
185              fileblock = file['Block']['Name']
186              if fileblock not in anFileBlocks :
187                  filename = file['LogicalFileName']
188 <                # asked retry the list of parent for the given child
189 <                if useparent==1: parList = [x['LogicalFileName'] for x in file['ParentList']]
190 <                self.parent[filename] = parList
188 >                # asked retry the list of parent for the given child
189 >                if useparent==1:
190 >                    parList = [x['LogicalFileName'] for x in file['ParentList']]
191 >                if self.splitByLumi:
192 >                    fileLumis = [ (x['RunNumber'], x['LumiSectionNumber'])
193 >                                 for x in file['LumiList'] ]
194 >                self.parent[filename] = parList
195 >                # For LumiMask, intersection of two lists.
196 >                if self.lumiMask and runselection:
197 >                    self.lumis[filename] = runList.filterLumis(lumiList.filterLumis(fileLumis))
198 >                elif runselection:
199 >                    self.lumis[filename] = runList.filterLumis(fileLumis)
200 >                elif self.lumiMask:
201 >                    self.lumis[filename] = lumiList.filterLumis(fileLumis)
202 >                else:
203 >                    self.lumis[filename] = fileLumis
204                  if filename.find('.dat') < 0 :
205                      events    = file['NumberOfEvents']
206 <                    # number of events per block
206 >                    # Count number of events and lumis per block
207                      if fileblock in self.eventsPerBlock.keys() :
208                          self.eventsPerBlock[fileblock] += events
209                      else :
210                          self.eventsPerBlock[fileblock] = events
211 <                    # number of events per file
211 >                    # Number of events per file
212                      self.eventsPerFile[filename] = events
213 <            
214 <                    # number of events per block
213 >
214 >                    # List of files per block
215                      if fileblock in self.blocksinfo.keys() :
216                          self.blocksinfo[fileblock].append(filename)
217                      else :
218                          self.blocksinfo[fileblock] = [filename]
219 <            
219 >
220                      # total number of events
221                      self.maxEvents += events
222 +                    self.maxLumis  += len(self.lumis[filename])
223 +
224          if  self.skipBlocks and len(self.eventsPerBlock.keys()) == 0:
225              msg = "No new fileblocks available for dataset: "+str(self.datasetPath)
226 <            raise  CrabException(msg)    
226 >            raise  CrabException(msg)
227 >
228  
172        saveFblocks=''
173        for block in self.eventsPerBlock.keys() :
174            saveFblocks += str(block)+'\n'
175            common.logger.debug(6,"DBSInfo: total nevts %i in block %s "%(self.eventsPerBlock[block],block))
176        writeTXTfile(self, fileBlocks_FileName , saveFblocks)
177                      
229          if len(self.eventsPerBlock) <= 0:
230              raise NotExistingDatasetError(("\nNo data for %s in DBS\nPlease check"
231                                              + " dataset path variables in crab.cfg")
232                                              % self.datasetPath)
233  
234  
184 ###########################
185
235      def queryDbs(self,api,path=None,runselection=None,useParent=None):
236 <
237 <        allowedRetriveValue = ['retrive_block', 'retrive_run']
238 <        if useParent==1 : allowedRetriveValue = allowedRetriveValue + ['retrive_parent']
236 >
237 >
238 >        allowedRetriveValue = []
239 >        if self.splitByLumi or self.splitByRun or useParent == 1:
240 >            allowedRetriveValue.extend(['retrive_block', 'retrive_run'])
241 >        if self.splitByLumi:
242 >            allowedRetriveValue.append('retrive_lumi')
243 >        if useParent == 1:
244 >            allowedRetriveValue.append('retrive_parent')
245 >        common.logger.debug("Set of input parameters used for DBS query: %s" % allowedRetriveValue)
246          try:
247 <            if len(runselection) <=0 :
248 <                if useParent==1 or self.splitByRun==1 :
193 <                    if self.ads==1 :          
194 <                        files = api.listFiles(analysisDataset=path, retriveList=allowedRetriveValue)
195 <                    else :
196 <                        files = api.listFiles(path=path, retriveList=allowedRetriveValue)
197 <                    common.logger.debug(5,"Set of input parameters used for DBS query : \n"+str(allowedRetriveValue))
198 <                    common.logger.write("Set of input parameters used for DBS query : \n"+str(allowedRetriveValue))
199 <                else:
200 <                    files = api.listDatasetFiles(self.datasetPath)
201 <            else :
202 <                files=[]
247 >            if self.splitByRun:
248 >                files = []
249                  for arun in runselection:
250                      try:
251 <                        if self.ads==1 : filesinrun = api.listFiles(analysisDataset=path,retriveList=allowedRetriveValue,runNumber=arun)
252 <                        else: filesinrun = api.listFiles(path=path,retriveList=allowedRetriveValue,runNumber=arun)
251 >                        if self.ads:
252 >                            filesinrun = api.listFiles(analysisDataset=path,retriveList=allowedRetriveValue,runNumber=arun)
253 >                        else:
254 >                            filesinrun = api.listFiles(path=path,retriveList=allowedRetriveValue,runNumber=arun)
255                          files.extend(filesinrun)
256                      except:
257                          msg="WARNING: problem extracting info from DBS for run %s "%arun
258 <                        common.logger.message(msg)
258 >                        common.logger.info(msg)
259                          pass
260  
261 +            else:
262 +                if allowedRetriveValue:
263 +                    if self.ads:
264 +                        files = api.listFiles(analysisDataset=path, retriveList=allowedRetriveValue)
265 +                    else :
266 +                        files = api.listFiles(path=path, retriveList=allowedRetriveValue)
267 +                else:
268 +                    files = api.listDatasetFiles(self.datasetPath)
269 +
270          except DbsBadRequest, msg:
271              raise DataDiscoveryError(msg)
272          except DBSError, msg:
# Line 217 | Line 274 | class DataDiscovery:
274  
275          return files
276  
277 < # #################################################
277 >
278      def getMaxEvents(self):
279          """
280 <        max events
280 >        max events
281          """
282          return self.maxEvents
283  
284 < # #################################################
284 >
285 >    def getMaxLumis(self):
286 >        """
287 >        Return the number of lumis in the dataset
288 >        """
289 >        return self.maxLumis
290 >
291 >
292      def getEventsPerBlock(self):
293          """
294 <        list the event collections structure by fileblock
294 >        list the event collections structure by fileblock
295          """
296          return self.eventsPerBlock
297  
298 < # #################################################
298 >
299      def getEventsPerFile(self):
300          """
301 <        list the event collections structure by file
301 >        list the event collections structure by file
302          """
303          return self.eventsPerFile
304  
305 < # #################################################
305 >
306      def getFiles(self):
307          """
308 <        return files grouped by fileblock
308 >        return files grouped by fileblock
309          """
310 <        return self.blocksinfo        
310 >        return self.blocksinfo
311 >
312  
248 # #################################################
313      def getParent(self):
314          """
315 <        return parent grouped by file
315 >        return parent grouped by file
316          """
317 <        return self.parent        
317 >        return self.parent
318  
319 < # #################################################
320 <    def getListFiles(self):
319 >
320 >    def getLumis(self):
321          """
322 <        return parent grouped by file
322 >        return lumi sections grouped by file
323          """
324 <        return self.files        
324 >        return self.lumis
325 >
326  
327 < ########################################################################
327 >    def getListFiles(self):
328 >        """
329 >        return parent grouped by file
330 >        """
331 >        return self.files

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines