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.5 by afanfani, Thu May 18 18:46:22 2006 UTC vs.
Revision 1.21 by spiga, Thu Jun 5 07:13:31 2008 UTC

# Line 1 | Line 1
1 < #!/usr/bin/env python2
2 < import sys, os, string, re
3 < from DBSInfo import *
4 <
1 > #!/usr/bin/env python
2 > import exceptions
3 > import DBSAPI.dbsApi
4 > from DBSAPI.dbsApiException import *
5 > import common
6 > from crab_util import *
7 >
8 >
9 > # #######################################
10 > class DBSError(exceptions.Exception):
11 >    def __init__(self, errorName, errorMessage):
12 >        args='\nERROR DBS %s : %s \n'%(errorName,errorMessage)
13 >        exceptions.Exception.__init__(self, args)
14 >        pass
15 >    
16 >    def getErrorMessage(self):
17 >        """ Return error message """
18 >        return "%s" % (self.args)
19 >
20 > # #######################################
21 > class DBSInvalidDataTierError(exceptions.Exception):
22 >    def __init__(self, errorName, errorMessage):
23 >        args='\nERROR DBS %s : %s \n'%(errorName,errorMessage)
24 >        exceptions.Exception.__init__(self, args)
25 >        pass
26 >    
27 >    def getErrorMessage(self):
28 >        """ Return error message """
29 >        return "%s" % (self.args)
30 >
31 > # #######################################
32 > class DBSInfoError:
33 >    def __init__(self, url):
34 >        print '\nERROR accessing DBS url : '+url+'\n'
35 >        pass
36  
37   # ####################################
38   class DataDiscoveryError(exceptions.Exception):
39 <  def __init__(self, errorMessage):
40 <   args=errorMessage
41 <   exceptions.Exception.__init__(self, args)
42 <   pass
43 <
44 <  def getErrorMessage(self):
45 <   """ Return exception error """
46 <   return "%s" % (self.args)
39 >    def __init__(self, errorMessage):
40 >        self.args=errorMessage
41 >        exceptions.Exception.__init__(self, self.args)
42 >        pass
43 >
44 >    def getErrorMessage(self):
45 >        """ Return exception error """
46 >        return "%s" % (self.args)
47  
48   # ####################################
49   class NotExistingDatasetError(exceptions.Exception):
50 <  def __init__(self, errorMessage):
51 <   args=errorMessage
52 <   exceptions.Exception.__init__(self, args)
53 <   pass
54 <
55 <  def getErrorMessage(self):
56 <   """ Return exception error """
57 <   return "%s" % (self.args)
50 >    def __init__(self, errorMessage):
51 >        self.args=errorMessage
52 >        exceptions.Exception.__init__(self, self.args)
53 >        pass
54 >
55 >    def getErrorMessage(self):
56 >        """ Return exception error """
57 >        return "%s" % (self.args)
58  
59   # ####################################
60   class NoDataTierinProvenanceError(exceptions.Exception):
61 <  def __init__(self, errorMessage):
62 <   args=errorMessage
63 <   exceptions.Exception.__init__(self, args)
64 <   pass
65 <
66 <  def getErrorMessage(self):
67 <   """ Return exception error """
68 <   return "%s" % (self.args)
61 >    def __init__(self, errorMessage):
62 >        self.args=errorMessage
63 >        exceptions.Exception.__init__(self, self.args)
64 >        pass
65 >
66 >    def getErrorMessage(self):
67 >        """ Return exception error """
68 >        return "%s" % (self.args)
69  
70   # ####################################
71   # class to find and extact info from published data
72   class DataDiscovery:
73 <    def __init__(self, owner, dataset, dataTiers, cfg_params):
73 >    def __init__(self, datasetPath, cfg_params):
74  
75 < #       Attributes
76 <        self.owner = owner
46 <        self.dataset = dataset
47 <        self.dataTiers = dataTiers
75 >        #       Attributes
76 >        self.datasetPath = datasetPath
77          self.cfg_params = cfg_params
78  
79 <        self.dbspaths= []     # DBS output: list of dbspaths for all data
80 <        self.allblocks = []   # DBS output: list of map fileblocks-totevts for all dataset-owners
81 <        self.blocksinfo = {}  # DBS output: map fileblocks-totevts for the primary block, used internally to this class
82 < #DBS output: max events computed by method getMaxEvents
79 >        self.eventsPerBlock = {}  # DBS output: map fileblocks-events for collection
80 >        self.eventsPerFile = {}   # DBS output: map files-events
81 >        self.blocksinfo = {}      # DBS output: map fileblocks-files
82 >        self.maxEvents = 0        # DBS output: max events
83 >        self.parent = {}       # DBS output: max events
84  
85   # ####################################
86      def fetchDBSInfo(self):
# Line 58 | Line 88 | class DataDiscovery:
88          Contact DBS
89          """
90  
91 <        ## add the PU among the required data tiers if the Digi are requested
92 <        if (self.dataTiers.count('Digi')>0) & (self.dataTiers.count('PU')<=0) :
93 <          self.dataTiers.append('PU')
94 <
95 <        ## get info about the requested dataset
96 <        dbs=DBSInfo()
91 >        ## get DBS URL
92 >        dbs_url="http://cmsdbsprod.cern.ch/cms_dbs_prod_global/servlet/DBSServlet"
93 >        if (self.cfg_params.has_key('CMSSW.dbs_url')):
94 >            dbs_url=self.cfg_params['CMSSW.dbs_url']
95 >
96 >        common.logger.debug(3,"Accessing DBS at: "+dbs_url)
97 >
98 >        ## check if runs are selected
99 >        runselection = []
100 >        if (self.cfg_params.has_key('CMSSW.runselection')):
101 >            runselection = parseRange2(self.cfg_params['CMSSW.runselection'])
102 >
103 >        common.logger.debug(6,"runselection is: %s"%runselection)
104 >        ## service API
105 >        args = {}
106 >        args['url']     = dbs_url
107 >        args['level']   = 'CRITICAL'
108 >
109 >        ## check if has been requested to use the parent info
110 >        if (self.cfg_params.has_key('CMSSW.runselection')):
111 >            runselection = parseRange2(self.cfg_params['CMSSW.runselection'])
112 >
113 >        useParent = self.cfg_params.get('CMSSW.use_parent',False)
114 >    
115 >        allowedRetriveValue = [
116 >                        'retrive_child',
117 >                        'retrive_block',
118 >                        'retrive_lumi',
119 >                        'retrive_run'
120 >                        ]
121 >        if useParent:  allowedRetriveValue.append('retrive_parent')
122 >        common.logger.debug(5,"Set of input parameters used for DBS query : \n"+str(allowedRetriveValue))
123 >        common.logger.write("Set of input parameters used for DBS query : \n"+str(allowedRetriveValue))
124 >        api = DBSAPI.dbsApi.DbsApi(args)
125          try:
126 <         self.datasets = dbs.getMatchingDatasets(self.owner, self.dataset)
127 <        except DBSError, ex:
128 <          raise DataDiscoveryError(ex.getErrorMessage())
129 <        if len(self.datasets) == 0:
130 <          raise DataDiscoveryError("Owner=%s, Dataset=%s unknown to DBS" % (self.owner, self.dataset))
131 <        if len(self.datasets) > 1:
132 <          raise DataDiscoveryError("Owner=%s, Dataset=%s is ambiguous" % (self.owner, self.dataset))
133 <        try:
134 <          self.dbsdataset = self.datasets[0].get('datasetPathName')
135 <          self.blocksinfo = dbs.getDatasetContents(self.dbsdataset)
136 <          self.allblocks.append (self.blocksinfo.keys ()) # add also the current fileblocksinfo
137 <          self.dbspaths.append(self.dbsdataset)
138 <        except DBSError, ex:
139 <          raise DataDiscoveryError(ex.getErrorMessage())
140 <        
141 <        if len(self.blocksinfo)<=0:
142 <         msg="\nERROR Data for %s do not exist in DBS! \n Check the dataset/owner variables in crab.cfg !"%self.dbsdataset
143 <         raise NotExistingDatasetError(msg)
144 <
145 <
146 <        ## get info about the parents
147 <        try:
148 <          parents=dbs.getDatasetProvenance(self.dbsdataset, self.dataTiers)
149 <        except DBSInvalidDataTierError, ex:
150 <          msg=ex.getErrorMessage()+' \n Check the data_tier variable in crab.cfg !\n'
151 <          raise DataDiscoveryError(msg)
152 <        except DBSError, ex:
153 <          raise DataDiscoveryError(ex.getErrorMessage())
154 <
155 <        ## check that the user asks for parent Data Tier really existing in the DBS provenance
156 <        self.checkParentDataTier(parents, self.dataTiers)
126 >            if len(runselection) <= 0 :
127 >                files = api.listFiles(path=self.datasetPath,retriveList=allowedRetriveValue)
128 >            else :
129 >                files=[]
130 >                for arun in runselection:
131 >                    try:
132 >                        filesinrun = api.listFiles(path=self.datasetPath,retriveList=allowedRetriveValue,runNumber=arun)
133 >                        files.extend(filesinrun)
134 >                    except:
135 >                        msg="WARNING: problem extracting info from DBS for run %s "%arun
136 >                        common.logger.message(msg)
137 >                        pass
138 >
139 >        except DbsBadRequest, msg:
140 >            raise DataDiscoveryError(msg)
141 >        except DBSError, msg:
142 >            raise DataDiscoveryError(msg)
143 >
144 >        # parse files and fill arrays
145 >        for file in files :
146 >            parList = []
147 >            filename = file['LogicalFileName']
148 >            # asked retry the list of parent for the given child
149 >            if useParent: parList = [x['LogicalFileName'] for x in file['ParentList']]
150 >            self.parent[filename] = parList
151 >            if filename.find('.dat') < 0 :
152 >                fileblock = file['Block']['Name']
153 >                events    = file['NumberOfEvents']
154 >                # number of events per block
155 >                if fileblock in self.eventsPerBlock.keys() :
156 >                    self.eventsPerBlock[fileblock] += events
157 >                else :
158 >                    self.eventsPerBlock[fileblock] = events
159 >                # number of events per file
160 >                self.eventsPerFile[filename] = events
161 >
162 >                # number of events per block
163 >                if fileblock in self.blocksinfo.keys() :
164 >                    self.blocksinfo[fileblock].append(filename)
165 >                else :
166 >                    self.blocksinfo[fileblock] = [filename]
167 >
168 >                # total number of events
169 >                self.maxEvents += events
170 >
171 >        for block in self.eventsPerBlock.keys() :
172 >            common.logger.debug(6,"DBSInfo: total nevts %i in block %s "%(self.eventsPerBlock[block],block))
173 >
174 >        if len(self.eventsPerBlock) <= 0:
175 >            raise NotExistingDatasetError(("\nNo data for %s in DBS\nPlease check"
176 >                                            + " dataset path variables in crab.cfg")
177 >                                            % self.datasetPath)
178  
100        ## for each parent get the corresponding fileblocks
101        try:
102          for p in parents:
103            ## fill a list of dbspaths
104            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())
179  
180   # #################################################
181 <    def checkParentDataTier(self, parents, dataTiers):
181 >    def getMaxEvents(self):
182          """
183 <         check that the data tiers requested by the user really exists in the provenance of the given dataset
183 >        max events
184          """
185 <        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)
123 <
185 >        return self.maxEvents
186  
187   # #################################################
188 <    def getMaxEvents(self):
188 >    def getEventsPerBlock(self):
189          """
190 <         max events of the primary dataset-owner
190 >        list the event collections structure by fileblock
191          """
192 <        ## loop over the fileblocks of the primary dataset-owner
131 <        nevts=0      
132 <        for blockevts in self.blocksinfo.values():
133 <          nevts=nevts+blockevts
134 <
135 <        return nevts
192 >        return self.eventsPerBlock
193  
194   # #################################################
195 <    def getDBSPaths(self):
195 >    def getEventsPerFile(self):
196          """
197 <         list the DBSpaths for all required data
197 >        list the event collections structure by file
198          """
199 <        return self.dbspaths
199 >        return self.eventsPerFile
200  
201   # #################################################
202 <    def getEVC(self):
202 >    def getFiles(self):
203          """
204 <         list the event collections structure by fileblock
204 >        return files grouped by fileblock
205          """
206 <        print "To be used by a more complex job splitting... TODO later... "
150 <        print "it requires changes in what's returned by DBSInfo.getDatasetContents and then fetchDBSInfo"
206 >        return self.blocksinfo        
207  
208   # #################################################
209 <    def getFileBlocks(self):
209 >    def getParent(self):
210          """
211 <         fileblocks for all required dataset-owners
211 >        return parent grouped by file
212          """
213 <        return self.allblocks        
213 >        return self.parent        
214  
215   ########################################################################
160
161

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines