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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines