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.7.2.1 by spiga, Thu Jul 20 12:03:48 2006 UTC vs.
Revision 1.44 by ewv, Wed May 26 19:46:12 2010 UTC

# Line 1 | Line 1
1   #!/usr/bin/env python
2 < import sys, os, string, re
3 < 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 > from LumiList import LumiList
12 > import os
13 >
14 >
15 >
16 > class DBSError(exceptions.Exception):
17 >    def __init__(self, errorName, errorMessage):
18 >        args='\nERROR DBS %s : %s \n'%(errorName,errorMessage)
19 >        exceptions.Exception.__init__(self, args)
20 >        pass
21 >
22 >    def getErrorMessage(self):
23 >        """ Return error message """
24 >        return "%s" % (self.args)
25 >
26 >
27 >
28 > class DBSInvalidDataTierError(exceptions.Exception):
29 >    def __init__(self, errorName, errorMessage):
30 >        args='\nERROR DBS %s : %s \n'%(errorName,errorMessage)
31 >        exceptions.Exception.__init__(self, args)
32 >        pass
33 >
34 >    def getErrorMessage(self):
35 >        """ Return error message """
36 >        return "%s" % (self.args)
37 >
38 >
39 >
40 > class DBSInfoError:
41 >    def __init__(self, url):
42 >        print '\nERROR accessing DBS url : '+url+'\n'
43 >        pass
44 >
45  
46  
6 # ####################################
47   class DataDiscoveryError(exceptions.Exception):
48      def __init__(self, errorMessage):
49 <        args=errorMessage
50 <        exceptions.Exception.__init__(self, args)
49 >        self.args=errorMessage
50 >        exceptions.Exception.__init__(self, self.args)
51          pass
52  
53      def getErrorMessage(self):
54          """ Return exception error """
55          return "%s" % (self.args)
56  
57 < # ####################################
57 >
58 >
59   class NotExistingDatasetError(exceptions.Exception):
60      def __init__(self, errorMessage):
61 <        args=errorMessage
62 <        exceptions.Exception.__init__(self, args)
61 >        self.args=errorMessage
62 >        exceptions.Exception.__init__(self, self.args)
63          pass
64  
65      def getErrorMessage(self):
66          """ Return exception error """
67          return "%s" % (self.args)
68  
69 < # ####################################
69 >
70 >
71   class NoDataTierinProvenanceError(exceptions.Exception):
72      def __init__(self, errorMessage):
73 <        args=errorMessage
74 <        exceptions.Exception.__init__(self, args)
73 >        self.args=errorMessage
74 >        exceptions.Exception.__init__(self, self.args)
75          pass
76  
77      def getErrorMessage(self):
78          """ Return exception error """
79          return "%s" % (self.args)
80  
39 # ####################################
40 # class to find and extact info from published data
41 class DataDiscovery:
42    def __init__(self, owner, dataset, dataTiers, cfg_params):
81  
82 < #       Attributes
83 <        self.owner = owner
84 <        self.dataset = dataset
85 <        self.dataTiers = dataTiers
82 >
83 > class DataDiscovery:
84 >    """
85 >    Class to find and extact info from published data
86 >    """
87 >    def __init__(self, datasetPath, cfg_params, skipAnBlocks):
88 >
89 >        #       Attributes
90 >        self.datasetPath = datasetPath
91 >        # Analysis dataset is primary/processed/tier/definition
92 >        self.ads = len(self.datasetPath.split("/")) > 4
93          self.cfg_params = cfg_params
94 +        self.skipBlocks = skipAnBlocks
95  
96 <        self.dbspaths= []     # DBS output: list of dbspaths for all data
97 <        self.allblocks = []   # DBS output: list of map fileblocks-totevts for all dataset-owners
98 <        self.blocksinfo = {}  # DBS output: map fileblocks-totevts for the primary block, used internally to this class
99 < #DBS output: max events computed by method getMaxEvents
96 >        self.eventsPerBlock = {}  # DBS output: map fileblocks-events for collection
97 >        self.eventsPerFile = {}   # DBS output: map files-events
98 > #         self.lumisPerBlock = {}   # DBS output: number of lumis in each block
99 > #         self.lumisPerFile = {}    # DBS output: number of lumis in each file
100 >        self.blocksinfo = {}      # DBS output: map fileblocks-files
101 >        self.maxEvents = 0        # DBS output: max events
102 >        self.maxLumis = 0         # DBS output: total number of lumis
103 >        self.parent = {}          # DBS output: parents of each file
104 >        self.lumis = {}           # DBS output: lumis in each file
105 >        self.lumiMask = None
106  
55 # ####################################
107      def fetchDBSInfo(self):
108          """
109          Contact DBS
110          """
111 +        ## get DBS URL
112 +        global_url="http://cmsdbsprod.cern.ch/cms_dbs_prod_global/servlet/DBSServlet"
113 +        dbs_url=  self.cfg_params.get('CMSSW.dbs_url', global_url)
114 +        common.logger.info("Accessing DBS at: "+dbs_url)
115 +
116 +        ## check if runs are selected
117 +        runselection = []
118 +        if (self.cfg_params.has_key('CMSSW.runselection')):
119 +            runselection = parseRange2(self.cfg_params['CMSSW.runselection'])
120 +
121 +        ## check if various lumi parameters are set
122 +        self.lumiMask = self.cfg_params.get('CMSSW.lumi_mask',None)
123 +        self.lumiParams = self.cfg_params.get('CMSSW.total_number_of_lumis',None) or \
124 +                          self.cfg_params.get('CMSSW.lumis_per_job',None)
125 +
126 +        lumiList = None
127 +        if self.lumiMask:
128 +            lumiList = LumiList(filename=self.lumiMask)
129 +        if runselection:
130 +            runList = LumiList(runs = runselection)
131 +
132 +        self.splitByRun = int(self.cfg_params.get('CMSSW.split_by_run', 0))
133 +
134 +        common.logger.log(10-1,"runselection is: %s"%runselection)
135 +        ## service API
136 +        args = {}
137 +        args['url']     = dbs_url
138 +        args['level']   = 'CRITICAL'
139 +
140 +        ## check if has been requested to use the parent info
141 +        useparent = int(self.cfg_params.get('CMSSW.use_parent',0))
142 +
143 +        ## check if has been asked for a non default file to store/read analyzed fileBlocks
144 +        defaultName = common.work_space.shareDir()+'AnalyzedBlocks.txt'
145 +        fileBlocks_FileName = os.path.abspath(self.cfg_params.get('CMSSW.fileblocks_file',defaultName))
146 +
147 +        api = DBSAPI.dbsApi.DbsApi(args)
148 +        self.files = self.queryDbs(api,path=self.datasetPath,runselection=runselection,useParent=useparent)
149 +
150 +        anFileBlocks = []
151 +        if self.skipBlocks: anFileBlocks = readTXTfile(self, fileBlocks_FileName)
152 +
153 +        # parse files and fill arrays
154 +        for file in self.files :
155 +            parList  = []
156 +            fileLumis = [] # List of tuples
157 +            # skip already analyzed blocks
158 +            fileblock = file['Block']['Name']
159 +            if fileblock not in anFileBlocks :
160 +                filename = file['LogicalFileName']
161 +                # asked retry the list of parent for the given child
162 +                if useparent==1:
163 +                    parList = [x['LogicalFileName'] for x in file['ParentList']]
164 +                if self.ads or self.lumiMask or self.lumiParams:
165 +                    fileLumis = [ (x['RunNumber'], x['LumiSectionNumber'])
166 +                                 for x in file['LumiList'] ]
167 +                self.parent[filename] = parList
168 +                # For LumiMask, intersection of two lists.
169 +                if self.lumiMask:
170 +                    self.lumis[filename] = lumiList.filterLumis(fileLumis)
171 +                    if runselection:
172 +                        self.lumis[filename] = runList.filterLumis(self.lumis[filename])
173 +                else:
174 +                    self.lumis[filename] = fileLumis
175 +                if filename.find('.dat') < 0 :
176 +                    events    = file['NumberOfEvents']
177 +                    # Count number of events and lumis per block
178 +                    if fileblock in self.eventsPerBlock.keys() :
179 +                        self.eventsPerBlock[fileblock] += events
180 +                    else :
181 +                        self.eventsPerBlock[fileblock] = events
182 +                    # Number of events per file
183 +                    self.eventsPerFile[filename] = events
184 +
185 +                    # List of files per block
186 +                    if fileblock in self.blocksinfo.keys() :
187 +                        self.blocksinfo[fileblock].append(filename)
188 +                    else :
189 +                        self.blocksinfo[fileblock] = [filename]
190 +
191 +                    # total number of events
192 +                    self.maxEvents += events
193 +                    self.maxLumis  += len(self.lumis[filename])
194 +
195 +        if  self.skipBlocks and len(self.eventsPerBlock.keys()) == 0:
196 +            msg = "No new fileblocks available for dataset: "+str(self.datasetPath)
197 +            raise  CrabException(msg)
198 +
199 +        saveFblocks=''
200 +        for block in self.eventsPerBlock.keys() :
201 +            saveFblocks += str(block)+'\n'
202 +            common.logger.log(10-1,"DBSInfo: total nevts %i in block %s "%(self.eventsPerBlock[block],block))
203 +        writeTXTfile(self, fileBlocks_FileName , saveFblocks)
204 +
205 +        if len(self.eventsPerBlock) <= 0:
206 +            raise NotExistingDatasetError(("\nNo data for %s in DBS\nPlease check"
207 +                                            + " dataset path variables in crab.cfg")
208 +                                            % self.datasetPath)
209 +
210 +
211 +    def queryDbs(self,api,path=None,runselection=None,useParent=None):
212 +
213 +        allowedRetriveValue = ['retrive_block', 'retrive_run']
214 +        if self.ads or self.lumiMask or self.lumiParams:
215 +            allowedRetriveValue.append('retrive_lumi')
216 +        if useParent == 1: allowedRetriveValue.append('retrive_parent')
217 +        common.logger.debug("Set of input parameters used for DBS query: %s" % allowedRetriveValue)
218 +        try:
219 +            if len(runselection) <=0 or self.ads or self.lumiMask:
220 +                if useParent==1 or self.splitByRun==1 or self.ads or self.lumiMask or self.lumiParams:
221 +                    if self.ads:
222 +                        files = api.listFiles(analysisDataset=path, retriveList=allowedRetriveValue)
223 +                    else :
224 +                        files = api.listFiles(path=path, retriveList=allowedRetriveValue)
225 +                else:
226 +                    files = api.listDatasetFiles(self.datasetPath)
227 +            else :
228 +                files=[]
229 +                for arun in runselection:
230 +                    try:
231 +                        if self.ads:
232 +                            filesinrun = api.listFiles(analysisDataset=path,retriveList=allowedRetriveValue,runNumber=arun)
233 +                        else:
234 +                            filesinrun = api.listFiles(path=path,retriveList=allowedRetriveValue,runNumber=arun)
235 +                        files.extend(filesinrun)
236 +                    except:
237 +                        msg="WARNING: problem extracting info from DBS for run %s "%arun
238 +                        common.logger.info(msg)
239 +                        pass
240  
241 <        ## add the PU among the required data tiers if the Digi are requested
242 <        if (self.dataTiers.count('Digi')>0) & (self.dataTiers.count('PU')<=0) :
243 <            self.dataTiers.append('PU')
241 >        except DbsBadRequest, msg:
242 >            raise DataDiscoveryError(msg)
243 >        except DBSError, msg:
244 >            raise DataDiscoveryError(msg)
245  
246 <        ## get info about the requested dataset
66 <        dbs=DBSInfo()
67 <        try:
68 <            self.datasets = dbs.getMatchingDatasets(self.owner, self.dataset)
69 <        except DBSError, ex:
70 <            raise DataDiscoveryError(ex.getErrorMessage())
71 <        if len(self.datasets) == 0:
72 <            raise DataDiscoveryError("Owner=%s, Dataset=%s unknown to DBS" % (self.owner, self.dataset))
73 <        if len(self.datasets) > 1:
74 <            raise DataDiscoveryError("Owner=%s, Dataset=%s is ambiguous" % (self.owner, self.dataset))
75 <        try:
76 <            self.dbsdataset = self.datasets[0].get('datasetPathName')
77 <            self.blocksinfo = dbs.getDatasetContents(self.dbsdataset)
78 <            self.allblocks.append (self.blocksinfo.keys ()) # add also the current fileblocksinfo
79 <            self.dbspaths.append(self.dbsdataset)
80 <        except DBSError, ex:
81 <            raise DataDiscoveryError(ex.getErrorMessage())
82 <        
83 <        if len(self.blocksinfo)<=0:
84 <            msg="\nERROR Data for %s do not exist in DBS! \n Check the dataset/owner variables in crab.cfg !"%self.dbsdataset
85 <            raise NotExistingDatasetError(msg)
246 >        return files
247  
248  
249 <        ## get info about the parents
250 <        try:
251 <            parents=dbs.getDatasetProvenance(self.dbsdataset, self.dataTiers)
252 <        except DBSInvalidDataTierError, ex:
253 <            msg=ex.getErrorMessage()+' \n Check the data_tier variable in crab.cfg !\n'
93 <            raise DataDiscoveryError(msg)
94 <        except DBSError, ex:
95 <            raise DataDiscoveryError(ex.getErrorMessage())
249 >    def getMaxEvents(self):
250 >        """
251 >        max events
252 >        """
253 >        return self.maxEvents
254  
97        ## check that the user asks for parent Data Tier really existing in the DBS provenance
98        self.checkParentDataTier(parents, self.dataTiers)
255  
256 <        ## for each parent get the corresponding fileblocks
257 <        try:
258 <            for p in parents:
259 <                ## fill a list of dbspaths
260 <                parentPath = p.get('parent').get('datasetPathName')
105 <                self.dbspaths.append (parentPath)
106 <                parentBlocks = dbs.getDatasetContents (parentPath)
107 <                self.allblocks.append (parentBlocks.keys ())  # add parent fileblocksinfo
108 <        except DBSError, ex:
109 <            raise DataDiscoveryError(ex.getErrorMessage())
110 <
111 < # #################################################
112 <    def checkParentDataTier(self, parents, dataTiers):
113 <        """
114 <        check that the data tiers requested by the user really exists in the provenance of the given dataset
115 <        """
116 <        startType = string.split(self.dbsdataset,'/')[2]
117 <        # for example 'type' is PU and 'dataTier' is Hit
118 <        parentTypes = map(lambda p: p.get('type'), parents)
119 <        for tier in dataTiers:
120 <            if parentTypes.count(tier) <= 0 and tier != startType:
121 <                msg="\nERROR Data %s not published in DBS with asked data tiers : the data tier not found is %s !\n  Check the data_tier variable in crab.cfg !"%(self.dbsdataset,tier)
122 <                raise  NoDataTierinProvenanceError(msg)
256 >    def getMaxLumis(self):
257 >        """
258 >        Return the number of lumis in the dataset
259 >        """
260 >        return self.maxLumis
261  
262  
263 < # #################################################
264 <    def getMaxEvents(self):
263 >    def getEventsPerBlock(self):
264 >        """
265 >        list the event collections structure by fileblock
266 >        """
267 >        return self.eventsPerBlock
268 >
269 >
270 >    def getEventsPerFile(self):
271          """
272 <        max events of the primary dataset-owner
272 >        list the event collections structure by file
273          """
274 <        ## loop over the fileblocks of the primary dataset-owner
131 <        nevts=0      
132 <        for blockevts in self.blocksinfo.values():
133 <            nevts=nevts+blockevts
274 >        return self.eventsPerFile
275  
135        return nevts
276  
277 < # #################################################
138 <    def getDBSPaths(self):
277 >    def getFiles(self):
278          """
279 <        list the DBSpaths for all required data
279 >        return files grouped by fileblock
280          """
281 <        return self.dbspaths
281 >        return self.blocksinfo
282  
283 < # #################################################
284 <    def getEVC(self):
283 >
284 >    def getParent(self):
285          """
286 <        list the event collections structure by fileblock
286 >        return parent grouped by file
287          """
288 <        print "To be used by a more complex job splitting... TODO later... "
289 <        print "it requires changes in what's returned by DBSInfo.getDatasetContents and then fetchDBSInfo"
288 >        return self.parent
289 >
290  
291 < # #################################################
153 <    def getFileBlocks(self):
291 >    def getLumis(self):
292          """
293 <        fileblocks for all required dataset-owners
293 >        return lumi sections grouped by file
294          """
295 <        return self.allblocks        
295 >        return self.lumis
296  
297 < ########################################################################
297 >
298 >    def getListFiles(self):
299 >        """
300 >        return parent grouped by file
301 >        """
302 >        return self.files

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines