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.14 by slacapra, Wed Jan 17 18:17:58 2007 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 < from DBSInfo import *
2 >
3 > __revision__ = "$Id$"
4 > __version__ = "$Revision$"
5 >
6 > import exceptions
7 > import DBSAPI.dbsApi
8 > from DBSAPI.dbsApiException import *
9 > import common
10 > from crab_util import *
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 >
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 >
26 >    def getErrorMessage(self):
27 >        """ Return error message """
28 >        return "%s" % (self.args)
29 >
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 >
38 >    def getErrorMessage(self):
39 >        """ Return error message """
40 >        return "%s" % (self.args)
41 >
42 >
43 >
44 > class DBSInfoError:
45 >    def __init__(self, url):
46 >        print '\nERROR accessing DBS url : '+url+'\n'
47 >        pass
48 >
49  
50  
5 # ####################################
51   class DataDiscoveryError(exceptions.Exception):
52      def __init__(self, errorMessage):
8        exceptions.Exception.__init__(self, self.args)
53          self.args=errorMessage
54 +        exceptions.Exception.__init__(self, self.args)
55          pass
56  
57      def getErrorMessage(self):
58          """ Return exception error """
59          return "%s" % (self.args)
60  
61 < # ####################################
61 >
62 >
63   class NotExistingDatasetError(exceptions.Exception):
64      def __init__(self, errorMessage):
19        exceptions.Exception.__init__(self, self.args)
65          self.args=errorMessage
66 +        exceptions.Exception.__init__(self, self.args)
67          pass
68  
69      def getErrorMessage(self):
70          """ Return exception error """
71          return "%s" % (self.args)
72  
73 < # ####################################
73 >
74 >
75   class NoDataTierinProvenanceError(exceptions.Exception):
76      def __init__(self, errorMessage):
30        exceptions.Exception.__init__(self, self.args)
77          self.args=errorMessage
78 +        exceptions.Exception.__init__(self, self.args)
79          pass
80  
81      def getErrorMessage(self):
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 <    def __init__(self, datasetPath, dataTiers, cfg_params):
88 >    """
89 >    Class to find and extact info from published data
90 >    """
91 >    def __init__(self, datasetPath, cfg_params, skipAnBlocks):
92  
93 < #       Attributes
93 >        #       Attributes
94          self.datasetPath = datasetPath
95 <        self.dataTiers = dataTiers
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
103 < #DBS output: max events computed by method getMaxEvents
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.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  
53 # ####################################
113      def fetchDBSInfo(self):
114          """
115          Contact DBS
116          """
58
117          ## get DBS URL
118 <        try:
119 <            dbs_url=self.cfg_params['CMSSW.dbs_url']
120 <        except KeyError:
121 <            dbs_url="http://cmsdoc.cern.ch/cms/test/aprom/DBS/CGIServer/prodquery"
118 >        global_url="http://cmsdbsprod.cern.ch/cms_dbs_prod_global/servlet/DBSServlet"
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 >        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 >
149 >        ## service API
150 >        args = {}
151 >        args['url']     = dbs_url
152 >        args['level']   = 'CRITICAL'
153 >
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'
159 >        fileBlocks_FileName = os.path.abspath(self.cfg_params.get('CMSSW.fileblocks_file',defaultName))
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)
179 >
180 >        # parse files and fill arrays
181 >        for file in self.files :
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:
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 >                    # 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
212 >                    self.eventsPerFile[filename] = events
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 >
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)
227  
228 <        ## get info about the requested dataset
229 <        try:
230 <            dbs_instance=self.cfg_params['CMSSW.dbs_instance']
231 <        except KeyError:
232 <            dbs_instance="MCGlobal/Writer"
233 <
234 <        dbs = DBSInfo(dbs_url, dbs_instance)
228 >
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 >
235 >    def queryDbs(self,api,path=None,runselection=None,useParent=None):
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 <            self.datasets = dbs.getMatchingDatasets(self.datasetPath)
248 <        except dbsCgiApi.DbsCgiExecutionError, msg:
247 >            if self.splitByRun:
248 >                files = []
249 >                for arun in runselection:
250 >                    try:
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.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:
273              raise DataDiscoveryError(msg)
274  
275 <        if len(self.datasets) == 0:
80 <            raise DataDiscoveryError("DatasetPath=%s unknown to DBS" %self.datasetPath)
81 <        if len(self.datasets) > 1:
82 <            raise DataDiscoveryError("DatasetPath=%s is ambiguous" %self.datasetPath)
275 >        return files
276  
84        try:
85            self.dbsdataset = self.datasets[0].get('datasetPathName')
277  
278 <            self.eventsPerBlock = dbs.getEventsPerBlock(self.dbsdataset)
279 <            self.blocksinfo = dbs.getDatasetFileBlocks(self.dbsdataset)
280 <            self.eventsPerFile = dbs.getEventsPerFile(self.dbsdataset)
281 <        except DBSError, ex:
282 <            raise DataDiscoveryError(ex.getErrorMessage())
92 <        
93 <        if len(self.eventsPerBlock) <= 0:
94 <            raise NotExistingDatasetError (("\nNo data for %s in DBS\nPlease check"
95 <                                            + " dataset path variables in crab.cfg")
96 <                                            % self.dbsdataset)
278 >    def getMaxEvents(self):
279 >        """
280 >        max events
281 >        """
282 >        return self.maxEvents
283  
284  
285 < # #################################################
100 <    def getMaxEvents(self):
285 >    def getMaxLumis(self):
286          """
287 <        max events
287 >        Return the number of lumis in the dataset
288          """
289 <        ## loop over the event collections
105 <        nevts=0      
106 <        for evc_evts in self.eventsPerBlock.values():
107 <            nevts=nevts+evc_evts
289 >        return self.maxLumis
290  
109        return nevts
291  
111 # #################################################
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
311 >
312 >
313 >    def getParent(self):
314 >        """
315 >        return parent grouped by file
316 >        """
317 >        return self.parent
318 >
319 >
320 >    def getLumis(self):
321 >        """
322 >        return lumi sections grouped by file
323          """
324 <        return self.blocksinfo        
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