ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/Publisher.py
(Generate patch)

Comparing COMP/CRAB/python/Publisher.py (file contents):
Revision 1.19 by afanfani, Mon Nov 17 13:02:07 2008 UTC vs.
Revision 1.49 by fanzago, Fri May 28 09:46:00 2010 UTC

# Line 3 | Line 3 | import common
3   import time, glob
4   from Actor import *
5   from crab_util import *
6 from crab_logger import Logger
6   from crab_exceptions import *
7   from ProdCommon.FwkJobRep.ReportParser import readJobReport
8   from ProdCommon.FwkJobRep.ReportState import checkSuccess
# Line 13 | Line 12 | from ProdCommon.DataMgmt.DBS.DBSErrors i
12   from ProdCommon.DataMgmt.DBS.DBSReader import DBSReader
13   from ProdCommon.DataMgmt.DBS.DBSWriter import DBSWriter,DBSWriterObjects
14   import sys
15 + from DBSAPI.dbsApi import DbsApi
16 + from DBSAPI.dbsMigrateApi import DbsMigrateApi
17 + from DBSAPI.dbsApiException import *
18  
19   class Publisher(Actor):
20      def __init__(self, cfg_params):
21          """
22 <        Publisher class:
22 >        Publisher class:
23  
24          - parses CRAB FrameworkJobReport on UI
25          - returns <file> section of xml in dictionary format for each xml file in crab_0_xxxx/res directory
26          - publishes output data on DBS and DLS
27          """
28  
29 <        try:
30 <            userprocessedData = cfg_params['USER.publish_data_name']
31 <            self.processedData = None
30 <        except KeyError:
29 >        self.cfg_params=cfg_params
30 >      
31 >        if not cfg_params.has_key('USER.publish_data_name'):
32              raise CrabException('Cannot publish output data, because you did not specify USER.publish_data_name parameter in the crab.cfg file')
33 +        self.userprocessedData = cfg_params['USER.publish_data_name']
34 +        self.processedData = None
35  
36 <        try:
37 <            if (int(cfg_params['USER.copy_data']) != 1): raise KeyError
38 <        except KeyError:
39 <            raise CrabException('You can not publish data because you did not selected *** copy_data = 1  *** in the crab.cfg file')
40 <        try:
41 <            self.pset = cfg_params['CMSSW.pset']
42 <        except KeyError:
36 >        if (not cfg_params.has_key('USER.copy_data') or int(cfg_params['USER.copy_data']) != 1 ) or \
37 >            (not cfg_params.has_key('USER.publish_data') or int(cfg_params['USER.publish_data']) != 1 ):
38 >            msg  = 'You can not publish data because you did not selected \n'
39 >            msg += '\t*** copy_data = 1 and publish_data = 1  *** in the crab.cfg file'
40 >            raise CrabException(msg)
41 >
42 >        if not cfg_params.has_key('CMSSW.pset'):
43              raise CrabException('Cannot publish output data, because you did not specify the psetname in [CMSSW] of your crab.cfg file')
44 <        try:
45 <            self.globalDBS=cfg_params['CMSSW.dbs_url']
46 <        except KeyError:
47 <            self.globalDBS="http://cmsdbsprod.cern.ch/cms_dbs_prod_global/servlet/DBSServlet"
48 <        try:
46 <            self.DBSURL=cfg_params['USER.dbs_url_for_publication']
47 <            common.logger.message('<dbs_url_for_publication> = '+self.DBSURL)
48 <            if (self.DBSURL == "http://cmsdbsprod.cern.ch/cms_dbs_prod_global/servlet/DBSServlet") or (self.DBSURL == "https://cmsdbsprod.cern.ch:8443/cms_dbs_prod_global_writer/servlet/DBSServlet"):
49 <                msg = "You can not publish your data in the globalDBS = " + self.DBSURL + "\n"
50 <                msg = msg + "Please write your local one in the [USER] section 'dbs_url_for_publication'"
51 <                raise CrabException(msg)
52 <        except KeyError:
44 >        self.pset = cfg_params['CMSSW.pset']
45 >
46 >        self.globalDBS=cfg_params.get('CMSSW.dbs_url',"http://cmsdbsprod.cern.ch/cms_dbs_prod_global/servlet/DBSServlet")
47 >
48 >        if not cfg_params.has_key('USER.dbs_url_for_publication'):
49              msg = "Warning. The [USER] section does not have 'dbs_url_for_publication'"
50              msg = msg + " entry, necessary to publish the data.\n"
51              msg = msg + "Use the command **crab -publish -USER.dbs_url_for_publication=dbs_url_for_publication*** \nwhere dbs_url_for_publication is your local dbs instance."
52              raise CrabException(msg)
53 +
54 +        self.DBSURL=cfg_params['USER.dbs_url_for_publication']
55 +        common.logger.info('<dbs_url_for_publication> = '+self.DBSURL)
56 +        if (self.DBSURL == "http://cmsdbsprod.cern.ch/cms_dbs_prod_global/servlet/DBSServlet") or (self.DBSURL == "https://cmsdbsprod.cern.ch:8443/cms_dbs_prod_global_writer/servlet/DBSServlet"):
57 +            msg = "You can not publish your data in the globalDBS = " + self.DBSURL + "\n"
58 +            msg = msg + "Please write your local one in the [USER] section 'dbs_url_for_publication'"
59 +            raise CrabException(msg)
60              
61          self.content=file(self.pset).read()
62          self.resDir = common.work_space.resDir()
# Line 72 | Line 75 | class Publisher(Actor):
75                  dataset=string.strip(dataset)
76                  self.dataset_to_import.append(dataset)
77          ###        
78 <                
78 >            
79 >        self.import_all_parents = cfg_params.get('USER.publish_with_import_all_parents',1)
80 >        
81 >        if ( int(self.import_all_parents) == 0 ):
82 >            common.logger.info("WARNING: The option USER.publish_with_import_all_parents=0 has been deprecated. The import of parents is compulsory and done by default")
83 >        self.skipOcheck=cfg_params.get('CMSSW.publish_zero_event',1)
84 >        if ( int(self.skipOcheck) == 0 ):
85 >            common.logger.info("WARNING: The option CMSSW.publish_zero_event has been deprecated. The publication is done by default also for files with 0 events")
86          self.SEName=''
87          self.CMSSW_VERSION=''
88          self.exit_status=''
89          self.time = time.strftime('%y%m%d_%H%M%S',time.localtime(time.time()))
90 <        self.problemFiles=[]  
90 >        self.problemFiles=[]
91          self.noEventsFiles=[]
92          self.noLFN=[]
93 <        
93 >
94      def importParentDataset(self,globalDBS, datasetpath):
95          """
96 <        """
97 <        dbsWriter = DBSWriter(self.DBSURL,level='ERROR')
98 <        
96 >           WARNING: it works only with DBS_2_0_9_patch_6
97 >        """
98 >
99 >        args={'url':globalDBS}
100          try:
101 <            dbsWriter.importDatasetWithoutParentage(globalDBS, self.datasetpath, self.DBSURL)
102 <        except DBSWriterError, ex:
101 >            api_reader = DbsApi(args)
102 >        except DbsApiException, ex:
103 >            msg = "%s\n" % formatEx(ex)
104 >            raise CrabException(msg)
105 >
106 >        args={'url':self.DBSURL}
107 >        try:
108 >            api_writer = DbsApi(args)
109 >        except DbsApiException, ex:
110 >            msg = "%s\n" % formatEx(ex)
111 >            raise CrabException(msg)
112 >
113 >        try:
114 >            common.logger.info("--->>> Importing all parents level")
115 >            start = time.time()
116 >            common.logger.debug("start import parents time: " + str(start))
117 >            for block in api_reader.listBlocks(datasetpath):
118 >                api_writer.dbsMigrateBlock(globalDBS,self.DBSURL,block['Name'] )
119 >            stop = time.time()
120 >            common.logger.debug("stop import parents time: " + str(stop))
121 >            common.logger.info("--->>> duration of all parents import (sec): "+str(stop - start))
122 >        except DbsApiException, ex:
123              msg = "Error importing dataset to be processed into local DBS\n"
124              msg += "Source Dataset: %s\n" % datasetpath
125              msg += "Source DBS: %s\n" % globalDBS
126              msg += "Destination DBS: %s\n" % self.DBSURL
127 <            common.logger.message(msg)
127 >            common.logger.info(msg)
128 >            common.logger.info(str(ex))
129              return 1
130          return 0
131 <          
131 >
132      def publishDataset(self,file):
133          """
134          """
# Line 105 | Line 137 | class Publisher(Actor):
137              self.exit_status = '0'
138          except IndexError:
139              self.exit_status = '1'
140 <            msg = "Error: Problem with "+file+" file"  
141 <            common.logger.message(msg)
140 >            msg = "Error: Problem with "+file+" file"
141 >            common.logger.info(msg)
142              return self.exit_status
143  
144          if (len(self.dataset_to_import) != 0):
145             for dataset in self.dataset_to_import:
146 <               common.logger.message("--->>> Importing parent dataset in the dbs: " +dataset)
146 >               common.logger.info("--->>> Importing parent dataset in the dbs: " +dataset)
147                 status_import=self.importParentDataset(self.globalDBS, dataset)
148                 if (status_import == 1):
149 <                   common.logger.message('Problem with parent '+ dataset +' import from the global DBS '+self.globalDBS+ 'to the local one '+self.DBSURL)
149 >                   common.logger.info('Problem with parent '+ dataset +' import from the global DBS '+self.globalDBS+ 'to the local one '+self.DBSURL)
150                     self.exit_status='1'
151                     return self.exit_status
152 <               else:    
153 <                   common.logger.message('Import ok of dataset '+dataset)
154 <            
155 <        #// DBS to contact
156 <        dbswriter = DBSWriter(self.DBSURL)                        
125 <        try:  
126 <            fileinfo= jobReport.files[0]
127 <            self.exit_status = '0'
128 <        except IndexError:
152 >               else:
153 >                   common.logger.info('Import ok of dataset '+dataset)
154 >
155 >        
156 >        if (len(jobReport.files) <= 0) :
157              self.exit_status = '1'
158 <            msg = "Error: No file to publish in xml file"+file+" file"  
159 <            common.logger.message(msg)
158 >            msg = "Error: No EDM file to publish in xml file"+file+" file"
159 >            common.logger.info(msg)
160              return self.exit_status
161 +        else:
162 +            msg = "fjr contains some files to publish"
163 +            common.logger.debug(msg)
164  
165 <        datasets=fileinfo.dataset
166 <        common.logger.debug(6,"FileInfo = " + str(fileinfo))
167 <        common.logger.debug(6,"DatasetInfo = " + str(datasets))
168 <        if len(datasets)<=0:
169 <           self.exit_status = '1'
170 <           msg = "Error: No info about dataset in the xml file "+file
171 <           common.logger.message(msg)
172 <           return self.exit_status
173 <        for dataset in datasets:
174 <            #### for production data
175 <            self.processedData = dataset['ProcessedDataset']
176 <            if (dataset['PrimaryDataset'] == 'null'):
177 <                dataset['PrimaryDataset'] = dataset['ProcessedDataset']
178 <            else: # add parentage from input dataset
179 <                dataset['ParentDataset']= self.datasetpath
180 <    
181 <            dataset['PSetContent']=self.content
182 <            cfgMeta = {'name' : self.pset , 'Type' : 'user' , 'annotation': 'user cfg', 'version' : 'private version'} # add real name of user cfg
183 <            common.logger.message("PrimaryDataset = %s"%dataset['PrimaryDataset'])
184 <            common.logger.message("ProcessedDataset = %s"%dataset['ProcessedDataset'])
185 <            common.logger.message("<User Dataset Name> = /"+dataset['PrimaryDataset']+"/"+dataset['ProcessedDataset']+"/USER")
186 <            
187 <            common.logger.debug(6,"--->>> Inserting primary: %s processed : %s"%(dataset['PrimaryDataset'],dataset['ProcessedDataset']))
188 <            
189 <            primary = DBSWriterObjects.createPrimaryDataset( dataset, dbswriter.dbs)
190 <            common.logger.debug(6,"Primary:  %s "%primary)
191 <            
192 <            algo = DBSWriterObjects.createAlgorithm(dataset, cfgMeta, dbswriter.dbs)
193 <            common.logger.debug(6,"Algo:  %s "%algo)
165 >        #### datasets creation in dbs
166 >        #// DBS to contact write and read of the same dbs
167 >        dbsReader = DBSReader(self.DBSURL,level='ERROR')
168 >        dbswriter = DBSWriter(self.DBSURL)
169 >        #####
170 >
171 >        self.published_datasets = []
172 >        for fileinfo in jobReport.files:
173 >            datasets_info=fileinfo.dataset
174 >            if len(datasets_info)<=0:
175 >                self.exit_status = '1'
176 >                msg = "Error: No info about dataset in the xml file "+file
177 >                common.logger.info(msg)
178 >                return self.exit_status
179 >            else:
180 >                for dataset in datasets_info:
181 >                    #### for production data
182 >                    self.processedData = dataset['ProcessedDataset']
183 >                    if (dataset['PrimaryDataset'] == 'null'):
184 >                        dataset['PrimaryDataset'] = self.userprocessedData
185 >                    elif self.datasetpath.upper() != 'NONE':
186 >                        dataset['ParentDataset']= self.datasetpath
187 >
188 >                    dataset['PSetContent']=self.content
189 >                    cfgMeta = {'name' : self.pset , 'Type' : 'user' , 'annotation': 'user cfg', 'version' : 'private version'} # add real name of user cfg
190 >                    common.logger.info("PrimaryDataset = %s"%dataset['PrimaryDataset'])
191 >                    common.logger.info("ProcessedDataset = %s"%dataset['ProcessedDataset'])
192 >                    common.logger.info("<User Dataset Name> = /"+dataset['PrimaryDataset']+"/"+dataset['ProcessedDataset']+"/USER")
193 >                    
194 >                    self.dataset_to_check="/"+dataset['PrimaryDataset']+"/"+dataset['ProcessedDataset']+"/USER"
195  
196 <            processed = DBSWriterObjects.createProcessedDataset(primary, algo, dataset, dbswriter.dbs)
197 <            common.logger.debug(6,"Processed:  %s "%processed)
198 <            
199 <            common.logger.debug(6,"Inserted primary %s processed %s"%(primary,processed))
200 <            
201 <        common.logger.debug(6,"exit_status = %s "%self.exit_status)
202 <        return self.exit_status    
196 >
197 >                    self.published_datasets.append(self.dataset_to_check)
198 >
199 >                    common.logger.log(10-1,"--->>> Inserting primary: %s processed : %s"%(dataset['PrimaryDataset'],dataset['ProcessedDataset']))
200 >                    
201 >                    #### check if dataset already exists in the DBS
202 >                    result = dbsReader.matchProcessedDatasets(dataset['PrimaryDataset'], 'USER', dataset['ProcessedDataset'])
203 >                    if (len(result) != 0):
204 >                       result = dbsReader.listDatasetFiles(self.dataset_to_check)
205 >
206 >                    primary = DBSWriterObjects.createPrimaryDataset( dataset, dbswriter.dbs)
207 >                    common.logger.log(10-1,"Primary:  %s "%primary)
208 >                    print "primary = ", primary
209 >
210 >                    algo = DBSWriterObjects.createAlgorithm(dataset, cfgMeta, dbswriter.dbs)
211 >                    common.logger.log(10-1,"Algo:  %s "%algo)
212 >
213 >                    processed = DBSWriterObjects.createProcessedDataset(primary, algo, dataset, dbswriter.dbs)
214 >                    common.logger.log(10-1,"Processed:  %s "%processed)
215 >                    print "processed = ", processed
216 >
217 >                    common.logger.log(10-1,"Inserted primary %s processed %s"%(primary,processed))
218 >                    #######################################################################################
219 >                
220 >        common.logger.log(10-1,"exit_status = %s "%self.exit_status)
221 >        return self.exit_status
222  
223      def publishAJobReport(self,file,procdataset):
224          """
225             input:  xml file, processedDataset
226          """
227 +        common.logger.debug("FJR = %s"%file)
228          try:
229              jobReport = readJobReport(file)[0]
230              self.exit_status = '0'
# Line 180 | Line 232 | class Publisher(Actor):
232              self.exit_status = '1'
233              msg = "Error: Problem with "+file+" file"
234              raise CrabException(msg)
183        ### overwrite ProcessedDataset with user defined value
184        ### overwrite lumisections with no value
235          ### skip publication for 0 events files
236          filestopublish=[]
237          for file in jobReport.files:
# Line 191 | Line 241 | class Publisher(Actor):
241              elif (file['LFN'] == ''):
242                  self.noLFN.append(file['PFN'])
243              else:
244 <                if int(file['TotalEvents']) != 0 :
195 <                    #file.lumisections = {}
196 <                    # lumi info are now in run hash
197 <                    file.runs = {}
198 <                    for ds in file.dataset:
199 <                        ### FEDE FOR NEW LFN ###
200 <                        #ds['ProcessedDataset']=procdataset
201 <                        ########################
202 <                        ### Fede for production
203 <                        if (ds['PrimaryDataset'] == 'null'):
204 <                            ds['PrimaryDataset']=procdataset
205 <                    filestopublish.append(file)
206 <                else:
244 >                if int(file['TotalEvents']) == 0:
245                      self.noEventsFiles.append(file['LFN'])
246 +                for ds in file.dataset:
247 +                    ### Fede for production
248 +                    if (ds['PrimaryDataset'] == 'null'):
249 +                        ds['PrimaryDataset']=self.userprocessedData
250 +                filestopublish.append(file)
251 +      
252          jobReport.files = filestopublish
253 +        for file in filestopublish:
254 +            common.logger.debug("--->>> LFN of file to publish =  " + str(file['LFN']))
255          ### if all files of FJR have number of events = 0
256          if (len(filestopublish) == 0):
257 <           return None
257 >            return None
258            
259          #// DBS to contact
260          dbswriter = DBSWriter(self.DBSURL)
261          # insert files
262          Blocks=None
263          try:
264 <            Blocks=dbswriter.insertFiles(jobReport)
265 <            common.logger.message("Inserting file in blocks = %s"%Blocks)
264 >            ### FEDE added insertDetectorData = True to propagate in DBS info about run and lumi
265 >            Blocks=dbswriter.insertFiles(jobReport, insertDetectorData = True)
266 >            #Blocks=dbswriter.insertFiles(jobReport)
267 >            common.logger.debug("--->>> Inserting file in blocks = %s"%Blocks)
268          except DBSWriterError, ex:
269 <            common.logger.error("Insert file error: %s"%ex)
269 >            common.logger.debug("--->>> Insert file error: %s"%ex)
270          return Blocks
271  
272      def run(self):
# Line 227 | Line 275 | class Publisher(Actor):
275          """
276          
277          file_list = glob.glob(self.resDir+"crab_fjr*.xml")
278 +        
279          ## Select only those fjr that are succesfull
280 +        if (len(file_list)==0):
281 +            common.logger.info("--->>> "+self.resDir+" empty: no file to publish on DBS")
282 +            self.exit_status = '1'
283 +            return self.exit_status
284 +
285          good_list=[]
286          for fjr in file_list:
287              reports = readJobReport(fjr)
288 <            if reports[0].status == "Success":
289 <               good_list.append(fjr)
288 >            if len(reports)>0:
289 >               if reports[0].status == "Success":
290 >                  good_list.append(fjr)
291          file_list=good_list
292          ##
293 <        common.logger.debug(6, "file_list = "+str(file_list))
294 <        common.logger.debug(6, "len(file_list) = "+str(len(file_list)))
295 <            
293 >        common.logger.log(10-1, "fjr with FrameworkJobReport Status='Success', file_list = "+str(file_list))
294 >        common.logger.log(10-1, "len(file_list) = "+str(len(file_list)))
295 >
296          if (len(file_list)>0):
297              BlocksList=[]
298 <            common.logger.message("--->>> Start dataset publication")
298 >            common.logger.info("--->>> Start dataset publication")
299              self.exit_status=self.publishDataset(file_list[0])
300              if (self.exit_status == '1'):
301 <                return self.exit_status
302 <            common.logger.message("--->>> End dataset publication")
301 >                return self.exit_status
302 >            common.logger.info("--->>> End dataset publication")
303  
304  
305 <            common.logger.message("--->>> Start files publication")
305 >            common.logger.info("--->>> Start files publication")
306              for file in file_list:
252                common.logger.debug(1, "file = "+file)
307                  Blocks=self.publishAJobReport(file,self.processedData)
308                  if Blocks:
309                      for x in Blocks: # do not allow multiple entries of the same block
310                          if x not in BlocksList:
311                             BlocksList.append(x)
312 <                    
312 >
313              # close the blocks
314 <            common.logger.debug(6, "BlocksList = %s"%BlocksList)
261 <            # dbswriter = DBSWriter(self.DBSURL,level='ERROR')
314 >            common.logger.log(10-1, "BlocksList = %s"%BlocksList)
315              dbswriter = DBSWriter(self.DBSURL)
316 <            
316 >
317              for BlockName in BlocksList:
318 <                try:  
318 >                try:
319                      closeBlock=dbswriter.manageFileBlock(BlockName,maxFiles= 1)
320 <                    common.logger.debug(6, "closeBlock %s"%closeBlock)
268 <                    #dbswriter.dbs.closeBlock(BlockName)
320 >                    common.logger.log(10-1, "closeBlock %s"%closeBlock)
321                  except DBSWriterError, ex:
322 <                    common.logger.message("Close block error %s"%ex)
322 >                    common.logger.info("Close block error %s"%ex)
323  
324              if (len(self.noEventsFiles)>0):
325 <                common.logger.message("--->>> WARNING: "+str(len(self.noEventsFiles))+" files not published because they contain 0 events are:")
325 >                common.logger.info("--->>> WARNING: "+str(len(self.noEventsFiles))+" published files contain 0 events are:")
326                  for lfn in self.noEventsFiles:
327 <                    common.logger.message("------ LFN: %s"%lfn)
327 >                    common.logger.info("------ LFN: %s"%lfn)
328              if (len(self.noLFN)>0):
329 <                common.logger.message("--->>> WARNING: there are "+str(len(self.noLFN))+" files not published because they have empty LFN")
329 >                common.logger.info("--->>> WARNING: there are "+str(len(self.noLFN))+" files not published because they have empty LFN")
330                  for pfn in self.noLFN:
331 <                    common.logger.message("------ pfn: %s"%pfn)
331 >                    common.logger.info("------ pfn: %s"%pfn)
332              if (len(self.problemFiles)>0):
333 <                common.logger.message("--->>> WARNING: "+str(len(self.problemFiles))+" files not published because they had problem with copy to SE")
333 >                common.logger.info("--->>> WARNING: "+str(len(self.problemFiles))+" files not published because they had problem with copy to SE")
334                  for lfn in self.problemFiles:
335 <                    common.logger.message("------ LFN: %s"%lfn)
336 <            common.logger.message("--->>> End files publication")
337 <            common.logger.message("--->>> To check data publication please use: InspectDBS2.py --DBSURL=<dbs_url_for_publication> --datasetPath=<User Dataset Name>")
335 >                    common.logger.info("------ LFN: %s"%lfn)
336 >            common.logger.info("--->>> End files publication")
337 >
338 >            #### FEDE for MULTI ####
339 >            for dataset_to_check in self.published_datasets:
340 >                self.cfg_params['USER.dataset_to_check']=dataset_to_check
341 >                from InspectDBS import InspectDBS
342 >                check=InspectDBS(self.cfg_params)
343 >                check.checkPublication()
344 >            #########################
345 >
346              return self.exit_status
347  
348          else:
349 <            common.logger.message("--->>> "+self.resDir+" empty: no file to publish on DBS")
349 >            common.logger.info("--->>> No valid files to publish on DBS. Your jobs do not report exit codes = 0")
350              self.exit_status = '1'
351              return self.exit_status
352      

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines