CMS 3D CMS Logo

/data/doxygen/doxygen-1.7.3/gen/CMSSW_4_2_8/src/DQMServices/Components/src/DQMFileSaver.cc

Go to the documentation of this file.
00001 #include "DQMServices/Components/src/DQMFileSaver.h"
00002 #include "DQMServices/Core/interface/DQMStore.h"
00003 #include "DQMServices/Core/interface/MonitorElement.h"
00004 #include "FWCore/Framework/interface/Event.h"
00005 #include "FWCore/Framework/interface/Run.h"
00006 #include "FWCore/Framework/interface/LuminosityBlock.h"
00007 #include "FWCore/ParameterSet/interface/ParameterSet.h"
00008 #include "FWCore/Version/interface/GetReleaseVersion.h"
00009 #include "FWCore/ServiceRegistry/interface/Service.h"
00010 #include "FWCore/MessageLogger/interface/MessageLogger.h"
00011 #include "FWCore/MessageLogger/interface/JobReport.h"
00012 #include <sys/stat.h>
00013 #include <unistd.h>
00014 #include <iostream>
00015 #include <vector>
00016 #include <string>
00017 #include <TString.h>
00018 #include <TSystem.h>
00019 
00020 //--------------------------------------------------------
00021 static void
00022 getAnInt(const edm::ParameterSet &ps, int &value, const std::string &name)
00023 {
00024   value = ps.getUntrackedParameter<int>(name, value);
00025   if (value < 1 && value != -1)
00026     throw cms::Exception("DQMFileSaver")
00027       << "Invalid '" << name << "' parameter '" << value
00028       << "'.  Must be -1 or >= 1.";
00029 }
00030 
00031 void
00032 DQMFileSaver::saveForOffline(const std::string &workflow, int run, int lumi)
00033 {
00034 
00035   char suffix[64];
00036   sprintf(suffix, "R%09d", run);
00037 
00038   char rewrite[128];
00039   if (lumi == 0) // save for run
00040     sprintf(rewrite, "\\1Run %d/\\2/Run summary", run);
00041   else
00042     sprintf(rewrite, "\\1Run %d/\\2/By Lumi Section %d-%d", irun_, ilumi_, ilumi_);
00043 
00044   size_t pos = 0;
00045   std::string wflow;
00046   wflow.reserve(workflow.size() + 3);
00047   wflow = workflow;
00048   while ((pos = wflow.find('/', pos)) != std::string::npos)
00049     wflow.replace(pos++, 1, "__");
00050     
00051   std::string filename = fileBaseName_ + suffix + wflow + ".root";
00052 
00053   if (lumi == 0) // save for run
00054   {
00055     // set run end flag
00056     dbe_->cd();
00057     dbe_->setCurrentFolder("Info/ProvInfo");
00058 
00059     // do this, because ProvInfo is not yet run in offline DQM
00060     MonitorElement* me = dbe_->get("Info/ProvInfo/CMSSW"); 
00061     if (!me) me = dbe_->bookString("CMSSW",edm::getReleaseVersion().c_str() );
00062     
00063     me = dbe_->get("Info/ProvInfo/runIsComplete");
00064     if (!me) me = dbe_->bookFloat("runIsComplete");
00065 
00066     if (me)
00067     { 
00068       if (runIsComplete_)
00069         me->Fill(1.);
00070       else
00071         me->Fill(0.);
00072     }
00073 
00074     dbe_->save(filename,
00075              "", 
00076              "^(Reference/)?([^/]+)", 
00077              rewrite,
00078              (DQMStore::SaveReferenceTag) saveReference_,
00079              saveReferenceQMin_,
00080              fileUpdate_);
00081   }
00082   else // save EventInfo folders for luminosity sections
00083   {
00084     std::vector<std::string> systems = (dbe_->cd(), dbe_->getSubdirs());
00085 
00086     std::cout << " DQMFileSaver: storing EventInfo folders for Run: " 
00087               << irun_ << ", Lumi Section: " << ilumi_ << ", Subsystems: " ;
00088               
00089     for (size_t i = 0, e = systems.size(); i != e; ++i) {
00090       if (systems[i] != "Reference") {
00091         dbe_->cd();
00092         std::cout << systems[i] << "  " ;
00093         dbe_->save(filename,
00094            systems[i]+"/EventInfo", "^(Reference/)?([^/]+)", rewrite,
00095            DQMStore::SaveWithoutReference,
00096            dqm::qstatus::STATUS_OK,
00097            fileUpdate_);
00098         // from now on update newly created file
00099         if (fileUpdate_=="RECREATE") fileUpdate_="UPDATE";
00100       }
00101     }
00102     std::cout << "\n";
00103   }
00104 
00105   if (pastSavedFiles_.size() == 0)
00106   {
00107     // save JobReport upon creation of file (once per job)
00108     saveJobReport(filename);
00109     pastSavedFiles_.push_back(filename);
00110   }
00111   
00112 }
00113 
00114 static void
00115 doSaveForOnline(std::list<std::string> &pastSavedFiles,
00116                 size_t numKeepSavedFiles,
00117                 DQMStore *store,
00118                 const std::string &filename,
00119                 const std::string &directory,
00120                 const std::string &rxpat,
00121                 const std::string &rewrite,
00122                 DQMStore::SaveReferenceTag saveref,
00123                 int saveRefQMin)
00124 {
00125   store->save(filename, "" , "^(Reference/)?([^/]+)", 
00126          rewrite, saveref, saveRefQMin);
00127   pastSavedFiles.push_back(filename);
00128   if (pastSavedFiles.size() > numKeepSavedFiles)
00129   {
00130     remove(pastSavedFiles.front().c_str());
00131     pastSavedFiles.pop_front();
00132   }
00133 }
00134 
00135 void
00136 DQMFileSaver::saveForOnline(const std::string &suffix, const std::string &rewrite)
00137 {
00138   std::vector<std::string> systems = (dbe_->cd(), dbe_->getSubdirs());
00139 
00140   for (size_t i = 0, e = systems.size(); i != e; ++i)
00141   {
00142     if (systems[i] != "Reference")
00143     {
00144       dbe_->cd();
00145       if (MonitorElement* me = dbe_->get(systems[i] + "/EventInfo/processName"))
00146       {
00147         doSaveForOnline(pastSavedFiles_, numKeepSavedFiles_, dbe_,
00148                         fileBaseName_ + me->getStringValue() + suffix + ".root",
00149                         "", "^(Reference/)?([^/]+)", rewrite,
00150                         (DQMStore::SaveReferenceTag) saveReference_,
00151                         saveReferenceQMin_);
00152         return;
00153       }
00154     }
00155   }
00156 
00157   // if no EventInfo Folder is found, then store subsystem wise
00158   for (size_t i = 0, e = systems.size(); i != e; ++i)
00159     if (systems[i] != "Reference")
00160       doSaveForOnline(pastSavedFiles_, numKeepSavedFiles_, dbe_,
00161                       fileBaseName_ + systems[i] + suffix + ".root",
00162                       systems[i], "^(Reference/)?([^/]+)", rewrite,
00163                       (DQMStore::SaveReferenceTag) saveReference_,
00164                       saveReferenceQMin_);
00165 }
00166 
00167 void
00168 DQMFileSaver::saveJobReport(const std::string &filename)
00169 {
00170 
00171   // Report the file to job report service.
00172   edm::Service<edm::JobReport> jr;
00173   if (jr.isAvailable())
00174   {
00175     std::map<std::string, std::string> info;
00176     info["Source"] = "DQMStore";
00177     info["FileClass"] = "DQM";
00178     jr->reportAnalysisFile(filename, info);
00179   }
00180 
00181 }
00182 
00183 //--------------------------------------------------------
00184 DQMFileSaver::DQMFileSaver(const edm::ParameterSet &ps)
00185   : convention_ (Offline),
00186     workflow_ (""),
00187     producer_ ("DQM"),
00188     dirName_ ("."),
00189     version_ (1),
00190     runIsComplete_ (false),
00191     saveByLumiSection_ (-1),
00192     saveByEvent_ (-1),
00193     saveByMinute_ (-1),
00194     saveByTime_ (-1),
00195     saveByRun_ (1),
00196     saveAtJobEnd_ (false),
00197     saveReference_ (DQMStore::SaveWithReference),
00198     saveReferenceQMin_ (dqm::qstatus::STATUS_OK),
00199     forceRunNumber_ (-1),
00200     fileBaseName_ (""),
00201     fileUpdate_ ("RECREATE"),
00202     dbe_ (&*edm::Service<DQMStore>()),
00203     irun_ (-1),
00204     ilumi_ (-1),
00205     ilumiprev_ (-1),
00206     ievent_ (-1),
00207     nrun_ (0),
00208     nlumi_ (0),
00209     nevent_ (0),
00210     numKeepSavedFiles_ (5)
00211 {
00212   // Determine the file saving convention, and adjust defaults accordingly.
00213   std::string convention = ps.getUntrackedParameter<std::string>("convention", "Offline");
00214   if (convention == "Offline")
00215     convention_ = Offline;
00216   else if (convention == "Online")
00217     convention_ = Online;
00218   else
00219     throw cms::Exception("DQMFileSaver")
00220       << "Invalid 'convention' parameter '" << convention << "'."
00221       << "  Expected one of 'Online' or 'Offline'.";
00222 
00223   // If this isn't online convention, check workflow.
00224   if (convention_ != Online)
00225   {
00226     workflow_ = ps.getUntrackedParameter<std::string>("workflow", workflow_);
00227     if (workflow_.empty()
00228         || workflow_[0] != '/'
00229         || *workflow_.rbegin() == '/'
00230         || std::count(workflow_.begin(), workflow_.end(), '/') != 3
00231         || workflow_.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
00232                                        "abcdefghijklmnopqrstuvwxyz"
00233                                        "0123456789"
00234                                        "-_/") != std::string::npos)
00235       throw cms::Exception("DQMFileSaver")
00236         << "Invalid 'workflow' parameter '" << workflow_
00237         << "'.  Expected '/A/B/C'.";
00238   }
00239   else if (! ps.getUntrackedParameter<std::string>("workflow", "").empty())
00240     throw cms::Exception("DQMFileSaver")
00241       << "The 'workflow' parameter must be empty in 'Online' convention.";
00242   else // for online set parameters
00243   {
00244     workflow_="/Global/Online/P5";
00245   }
00246     
00247   // Allow file producer to be set to specific values in certain conditions.
00248   producer_ = ps.getUntrackedParameter<std::string>("producer", producer_);
00249   if (convention_ == Online
00250       && producer_ != "DQM"
00251       && producer_ != "HLTDQM"
00252       && producer_ != "Playback")
00253   {
00254     throw cms::Exception("DQMFileSaver")
00255       << "Invalid 'producer' parameter '" << producer_
00256       << "'.  Expected 'DQM', 'HLTDQM' or 'Playback'.";
00257   }
00258   else if (convention_ != Online && producer_ != "DQM")
00259   {
00260     throw cms::Exception("DQMFileSaver")
00261       << "Invalid 'producer' parameter '" << producer_
00262       << "'.  Expected 'DQM'.";
00263   }
00264 
00265   // version number to be used in filename
00266   version_ = ps.getUntrackedParameter<int>("version", version_);
00267   // flag to signal that file contains data from complete run
00268   runIsComplete_ = ps.getUntrackedParameter<bool>("runIsComplete", runIsComplete_);
00269 
00270   // Check how we should save the references.
00271   std::string refsave = ps.getUntrackedParameter<std::string>("referenceHandling", "default");
00272   if (refsave == "default")
00273     ;
00274   else if (refsave == "skip") 
00275   {
00276     saveReference_ = DQMStore::SaveWithoutReference;
00277   //  std::cout << "skip saving all references" << std::endl;
00278   }
00279   else if (refsave == "all")
00280   {
00281     saveReference_ = DQMStore::SaveWithReference;
00282   //  std::cout << "saving all references" << std::endl;
00283   }
00284   else if (refsave == "qtests")
00285   {
00286     saveReference_ = DQMStore::SaveWithReferenceForQTest;
00287   //  std::cout << "saving qtest references" << std::endl;
00288   }
00289   else
00290     throw cms::Exception("DQMFileSaver")
00291       << "Invalid 'referenceHandling' parameter '" << refsave
00292       << "'.  Expected 'default', 'skip', 'all' or 'qtests'.";
00293 
00294   // Check minimum required quality test result for which reference is saved.
00295   saveReferenceQMin_ = ps.getUntrackedParameter<int>("referenceRequireStatus", saveReferenceQMin_);
00296 
00297   // Get and check the output directory.
00298   struct stat s;
00299   dirName_ = ps.getUntrackedParameter<std::string>("dirName", dirName_);
00300   if (dirName_.empty() || stat(dirName_.c_str(), &s) == -1)
00301     throw cms::Exception("DQMFileSaver")
00302       << "Invalid 'dirName' parameter '" << dirName_ << "'.";
00303 
00304   // Find out when and how to save files.  The following contraints apply:
00305   // - For online, allow files to be saved at event and time intervals.
00306   // - For online and offline, allow files to be saved per run, lumi and job end
00307   // - For offline allow run number to be overridden (for mc data).
00308   if (convention_ == Online)
00309   {
00310     getAnInt(ps, saveByEvent_, "saveByEvent");
00311     getAnInt(ps, saveByMinute_, "saveByMinute");
00312     getAnInt(ps, saveByTime_, "saveByTime");
00313     getAnInt(ps, numKeepSavedFiles_, "maxSavedFilesCount");
00314   }
00315 
00316   if (convention_ == Online || convention_ == Offline)
00317   {
00318     getAnInt(ps, saveByRun_, "saveByRun");
00319     getAnInt(ps, saveByLumiSection_, "saveByLumiSection");
00320   }
00321 
00322   if (convention_ != Online)
00323   {
00324     getAnInt(ps, forceRunNumber_, "forceRunNumber");
00325     saveAtJobEnd_ = ps.getUntrackedParameter<bool>("saveAtJobEnd", saveAtJobEnd_);
00326   }
00327 
00328   if (saveAtJobEnd_ && forceRunNumber_ < 1)
00329     throw cms::Exception("DQMFileSaver")
00330       << "If saving at the end of the job, the run number must be"
00331       << " overridden to a specific value using 'forceRunNumber'.";
00332 
00333   
00334   // Set up base file name and determine the start time.
00335   char version[8];
00336   sprintf(version, "_V%04d_", int(version_));
00337   version[7]='\0';
00338   fileBaseName_ = dirName_ + "/" + producer_ + version;
00339   gettimeofday(&start_, 0);
00340   saved_ = start_;
00341 
00342   // Log some information what we will do.
00343   edm::LogInfo("DQMFileSaver")
00344     << "DQM file saving settings:\n"
00345     << " using base file name '" << fileBaseName_ << "'\n"
00346     << " forcing run number " << forceRunNumber_ << "\n"
00347     << " saving every " << saveByLumiSection_ << " lumi section(s)\n"
00348     << " saving every " << saveByEvent_ << " event(s)\n"
00349     << " saving every " << saveByMinute_ << " minute(s)\n"
00350     << " saving every 2^n*" << saveByTime_ << " minutes \n"
00351     << " saving every " << saveByRun_ << " run(s)\n"
00352     << " saving at job end: " << (saveAtJobEnd_ ? "yes" : "no") << "\n"
00353     << " keeping at most " << numKeepSavedFiles_ << " files\n";
00354 }
00355 
00356 //--------------------------------------------------------
00357 void
00358 DQMFileSaver::beginJob()
00359 {
00360   irun_ = ilumi_ = ilumiprev_ = ievent_ = -1;
00361   nrun_ = nlumi_ = nevent_ = 0;
00362 }
00363 
00364 void
00365 DQMFileSaver::beginRun(const edm::Run &r, const edm::EventSetup &)
00366 {
00367   irun_     = (forceRunNumber_ == -1 ? r.id().run() : forceRunNumber_);
00368   ++nrun_;
00369 }
00370 
00371 void
00372 DQMFileSaver::beginLuminosityBlock(const edm::LuminosityBlock &l, const edm::EventSetup &)
00373 {
00374   ilumi_    = l.id().luminosityBlock();
00375   if (ilumiprev_ == -1) ilumiprev_ = ilumi_;
00376   ++nlumi_;
00377 }
00378 
00379 void DQMFileSaver::analyze(const edm::Event &e, const edm::EventSetup &)
00380 {
00381   ++nevent_;
00382 
00383   ievent_   = e.id().event();
00384 
00385   // Check if we should save for this event.
00386   char suffix[64];
00387   if (ievent_ > 0 && saveByEvent_ > 0 && nevent_ == saveByEvent_)
00388   {
00389     if (convention_ != Online)
00390       throw cms::Exception("DQMFileSaver")
00391         << "Internal error, can save files by event"
00392         << " only in Online mode.";
00393 
00394     sprintf(suffix, "_R%09d_E%08d", irun_, ievent_);
00395     saveForOnline(suffix, "\\1\\2");
00396     nevent_ = 0;
00397   }
00398 
00399   // Check if we should save due to elapsed time.
00400   if ( ievent_ > 0 && ( saveByMinute_ > 0 || saveByTime_ > 0 ) )
00401   {
00402     if (convention_ != Online)
00403       throw cms::Exception("DQMFileSaver")
00404         << "Internal error, can save files by time"
00405         << " only in Online mode.";
00406 
00407     // Compute elapsed time in minutes.
00408     struct timeval tv;
00409     gettimeofday(&tv, 0);
00410 
00411     double totalelapsed = ((tv.tv_sec + tv.tv_usec*1e-6)
00412                  - (start_.tv_sec + start_.tv_usec*1e-6)) / 60;
00413     double elapsed = ((tv.tv_sec + tv.tv_usec*1e-6)
00414                       - (saved_.tv_sec + saved_.tv_usec*1e-6)) / 60;
00415 
00416     // Save if enough time has elapsed since the last save.
00417     if ( (saveByMinute_ > 0 && elapsed > saveByMinute_ ) ||
00418          (saveByTime_ > 0   && totalelapsed > saveByTime_ ) )
00419     {
00420       if ( saveByTime_ > 0 ) saveByTime_ *= 2;
00421       saved_ = tv;
00422       sprintf(suffix, "_R%09d_T%08d", irun_, int(totalelapsed));
00423       char rewrite[64]; sprintf(rewrite, "\\1Run %d/\\2/Run summary", irun_);
00424       saveForOnline(suffix, rewrite);
00425     }
00426   }
00427 }
00428 
00429 void
00430 DQMFileSaver::endLuminosityBlock(const edm::LuminosityBlock &, const edm::EventSetup &)
00431 {
00432 
00433   if (ilumi_ > 0 && saveByLumiSection_ > 0 )
00434   {
00435     if (convention_ != Online && convention_ != Offline )
00436       throw cms::Exception("DQMFileSaver")
00437         << "Internal error, can save files at end of lumi block"
00438         << " only in Online or Offline mode.";
00439 
00440     if (convention_ == Online && nlumi_ == saveByLumiSection_) // insist on lumi section ordering
00441     {
00442       char suffix[64];
00443       char rewrite[128];
00444       sprintf(suffix, "_R%09d_L%06d", irun_, ilumi_);
00445       sprintf(rewrite, "\\1Run %d/\\2/By Lumi Section %d-%d", irun_, ilumiprev_, ilumi_);
00446       saveForOnline(suffix, rewrite);
00447       ilumiprev_ = -1;
00448       nlumi_ = 0;
00449     }
00450     if (convention_ == Offline)
00451       saveForOffline(workflow_, irun_, ilumi_);
00452   }
00453 }
00454 
00455 void
00456 DQMFileSaver::endRun(const edm::Run &, const edm::EventSetup &)
00457 {
00458   if (irun_ > 0 && saveByRun_ > 0 && nrun_ == saveByRun_)
00459   {
00460     if (convention_ == Online)
00461     {
00462       char suffix[64]; sprintf(suffix, "_R%09d", irun_);
00463       char rewrite[64]; sprintf(rewrite, "\\1Run %d/\\2/Run summary", irun_);
00464       saveForOnline(suffix, rewrite);
00465     }
00466     else if (convention_ == Offline)
00467       saveForOffline(workflow_, irun_, 0);
00468     else
00469       throw cms::Exception("DQMFileSaver")
00470         << "Internal error.  Can only save files in endRun()"
00471         << " in Online and Offline modes.";
00472 
00473     nrun_ = 0;
00474   }
00475 }
00476 
00477 void
00478 DQMFileSaver::endJob(void)
00479 { 
00480   if (saveAtJobEnd_)
00481   {
00482     if (convention_ == Offline && forceRunNumber_ > 0)
00483       saveForOffline(workflow_, forceRunNumber_, 0);
00484     else
00485       throw cms::Exception("DQMFileSaver")
00486         << "Internal error.  Can only save files at the end of the"
00487         << " job in Offline mode with run number overridden.";
00488   }
00489     
00490 }