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.33 by ewv, Thu Jul 30 18:45:44 2009 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 > 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  
5 # ####################################
46   class DataDiscoveryError(exceptions.Exception):
47      def __init__(self, errorMessage):
8        exceptions.Exception.__init__(self, 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):
19        exceptions.Exception.__init__(self, 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):
30        exceptions.Exception.__init__(self, 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  
80 < # ####################################
81 < # class to find and extact info from published data
80 >
81 >
82   class DataDiscovery:
83 <    def __init__(self, datasetPath, dataTiers, cfg_params):
83 >    """
84 >    Class to find and extact info from published data
85 >    """
86 >    def __init__(self, datasetPath, cfg_params, skipAnBlocks):
87  
88 < #       Attributes
88 >        #       Attributes
89          self.datasetPath = datasetPath
90 <        self.dataTiers = dataTiers
90 >        # Analysis dataset is primary/processed/tier/definition
91 >        self.ads = len(self.datasetPath.split("/")) > 3
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.blocksinfo = {}  # DBS output: map fileblocks-files
98 < #DBS output: max events computed by method getMaxEvents
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 >
105  
53 # ####################################
106      def fetchDBSInfo(self):
107          """
108          Contact DBS
109          """
58
110          ## get DBS URL
111 <        try:
112 <            dbs_url=self.cfg_params['CMSSW.dbs_url']
113 <        except KeyError:
114 <            dbs_url="http://cmsdoc.cern.ch/cms/test/aprom/DBS/CGIServer/prodquery"
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 >                          'glitecoll':global_url,\
115 >                          'condor':   global_url,\
116 >                          'condor_g': global_url,\
117 >                          'glidein':  global_url,\
118 >                          'lsf':      global_url,\
119 >                          'caf':      caf_url,\
120 >                          'sge':      global_url,
121 >                          'arc':      global_url
122 >                          }
123 >
124 >        dbs_url_default = dbs_url_map[(common.scheduler.name()).lower()]
125 >        dbs_url=  self.cfg_params.get('CMSSW.dbs_url', dbs_url_default)
126 >        common.logger.debug("Accessing DBS at: "+dbs_url)
127 >
128 >        ## check if runs are selected
129 >        runselection = []
130 >        if (self.cfg_params.has_key('CMSSW.runselection')):
131 >            runselection = parseRange2(self.cfg_params['CMSSW.runselection'])
132 >
133 >
134 >        self.splitByRun = int(self.cfg_params.get('CMSSW.split_by_run', 0))
135 >
136 >        common.logger.log(10-1,"runselection is: %s"%runselection)
137 >        ## service API
138 >        args = {}
139 >        args['url']     = dbs_url
140 >        args['level']   = 'CRITICAL'
141 >
142 >        ## check if has been requested to use the parent info
143 >        useparent = int(self.cfg_params.get('CMSSW.use_parent',0))
144 >
145 >        ## check if has been asked for a non default file to store/read analyzed fileBlocks
146 >        defaultName = common.work_space.shareDir()+'AnalyzedBlocks.txt'
147 >        fileBlocks_FileName = os.path.abspath(self.cfg_params.get('CMSSW.fileblocks_file',defaultName))
148 >
149 >        api = DBSAPI.dbsApi.DbsApi(args)
150 >        self.files = self.queryDbs(api,path=self.datasetPath,runselection=runselection,useParent=useparent)
151 >
152 >        anFileBlocks = []
153 >        if self.skipBlocks: anFileBlocks = readTXTfile(self, fileBlocks_FileName)
154 >
155 >        # parse files and fill arrays
156 >        for file in self.files :
157 >            parList  = []
158 >            lumiList = [] # List of tuples
159 >            # skip already analyzed blocks
160 >            fileblock = file['Block']['Name']
161 >            if fileblock not in anFileBlocks :
162 >                filename = file['LogicalFileName']
163 >                # asked retry the list of parent for the given child
164 >                if useparent==1:
165 >                    parList = [x['LogicalFileName'] for x in file['ParentList']]
166 >                if self.ads:
167 >                    lumiList = [ (x['RunNumber'], x['LumiSectionNumber'])
168 >                                 for x in file['LumiList'] ]
169 >                self.parent[filename] = parList
170 >                self.lumis[filename] = lumiList
171 >                if filename.find('.dat') < 0 :
172 >                    events    = file['NumberOfEvents']
173 >                    # Count number of events and lumis per block
174 >                    if fileblock in self.eventsPerBlock.keys() :
175 >                        self.eventsPerBlock[fileblock] += events
176 >                    else :
177 >                        self.eventsPerBlock[fileblock] = events
178 >                    # Number of events per file
179 >                    self.eventsPerFile[filename] = events
180 >
181 >                    # List of files per block
182 >                    if fileblock in self.blocksinfo.keys() :
183 >                        self.blocksinfo[fileblock].append(filename)
184 >                    else :
185 >                        self.blocksinfo[fileblock] = [filename]
186 >
187 >                    # total number of events
188 >                    self.maxEvents += events
189 >                    self.maxLumis  += len(lumiList)
190 >
191 >        if  self.skipBlocks and len(self.eventsPerBlock.keys()) == 0:
192 >            msg = "No new fileblocks available for dataset: "+str(self.datasetPath)
193 >            raise  CrabException(msg)
194 >
195 >        saveFblocks=''
196 >        for block in self.eventsPerBlock.keys() :
197 >            saveFblocks += str(block)+'\n'
198 >            common.logger.log(10-1,"DBSInfo: total nevts %i in block %s "%(self.eventsPerBlock[block],block))
199 >        writeTXTfile(self, fileBlocks_FileName , saveFblocks)
200  
201 <        ## get info about the requested dataset
202 <        try:
203 <            dbs_instance=self.cfg_params['CMSSW.dbs_instance']
204 <        except KeyError:
205 <            dbs_instance="MCGlobal/Writer"
206 <
207 <        dbs = DBSInfo(dbs_url, dbs_instance)
201 >        if len(self.eventsPerBlock) <= 0:
202 >            raise NotExistingDatasetError(("\nNo data for %s in DBS\nPlease check"
203 >                                            + " dataset path variables in crab.cfg")
204 >                                            % self.datasetPath)
205 >
206 >
207 >    def queryDbs(self,api,path=None,runselection=None,useParent=None):
208 >
209 >        allowedRetriveValue = ['retrive_block', 'retrive_run']
210 >        if self.ads: allowedRetriveValue.append('retrive_lumi')
211 >        if useParent == 1: allowedRetriveValue.append('retrive_parent')
212 >        common.logger.debug("Set of input parameters used for DBS query: %s" % allowedRetriveValue)
213          try:
214 <            self.datasets = dbs.getMatchingDatasets(self.datasetPath)
215 <        except dbsCgiApi.DbsCgiExecutionError, msg:
214 >            if len(runselection) <=0 :
215 >                if useParent==1 or self.splitByRun==1 :
216 >                    if self.ads:
217 >                        files = api.listFiles(analysisDataset=path, retriveList=allowedRetriveValue)
218 >                    else :
219 >                        files = api.listFiles(path=path, retriveList=allowedRetriveValue)
220 >                else:
221 >                    files = api.listDatasetFiles(self.datasetPath)
222 >            else :
223 >                files=[]
224 >                for arun in runselection:
225 >                    try:
226 >                        if self.ads:
227 >                            filesinrun = api.listFiles(analysisDataset=path,retriveList=allowedRetriveValue,runNumber=arun)
228 >                        else:
229 >                            filesinrun = api.listFiles(path=path,retriveList=allowedRetriveValue,runNumber=arun)
230 >                        files.extend(filesinrun)
231 >                    except:
232 >                        msg="WARNING: problem extracting info from DBS for run %s "%arun
233 >                        common.logger.info(msg)
234 >                        pass
235 >
236 >        except DbsBadRequest, msg:
237              raise DataDiscoveryError(msg)
238          except DBSError, msg:
239              raise DataDiscoveryError(msg)
240  
241 <        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)
241 >        return files
242  
84        try:
85            self.dbsdataset = self.datasets[0].get('datasetPathName')
243  
244 <            self.eventsPerBlock = dbs.getEventsPerBlock(self.dbsdataset)
245 <            self.blocksinfo = dbs.getDatasetFileBlocks(self.dbsdataset)
246 <            self.eventsPerFile = dbs.getEventsPerFile(self.dbsdataset)
247 <        except DBSError, ex:
248 <            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)
244 >    def getMaxEvents(self):
245 >        """
246 >        max events
247 >        """
248 >        return self.maxEvents
249  
250  
251 < # #################################################
100 <    def getMaxEvents(self):
251 >    def getMaxLumis(self):
252          """
253 <        max events
253 >        Return the number of lumis in the dataset
254          """
255 <        ## loop over the event collections
105 <        nevts=0      
106 <        for evc_evts in self.eventsPerBlock.values():
107 <            nevts=nevts+evc_evts
255 >        return self.maxLumis
256  
109        return nevts
257  
111 # #################################################
258      def getEventsPerBlock(self):
259          """
260 <        list the event collections structure by fileblock
260 >        list the event collections structure by fileblock
261          """
262          return self.eventsPerBlock
263  
264 < # #################################################
264 >
265      def getEventsPerFile(self):
266          """
267 <        list the event collections structure by file
267 >        list the event collections structure by file
268          """
269          return self.eventsPerFile
270  
271 < # #################################################
271 >
272      def getFiles(self):
273          """
274 <        return files grouped by fileblock
274 >        return files grouped by fileblock
275 >        """
276 >        return self.blocksinfo
277 >
278 >
279 >    def getParent(self):
280 >        """
281 >        return parent grouped by file
282          """
283 <        return self.blocksinfo        
283 >        return self.parent
284  
285 < ########################################################################
285 >
286 >    def getLumis(self):
287 >        """
288 >        return lumi sections grouped by file
289 >        """
290 >        return self.lumis
291 >
292 >
293 >    def getListFiles(self):
294 >        """
295 >        return parent grouped by file
296 >        """
297 >        return self.files

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines