Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2022-05-01 22:51:58

0001 // -*- C++ -*-
0002 //
0003 // Package:     FwkIO
0004 // Class  :     DQMRootSource
0005 //
0006 // Implementation:
0007 //     [Notes on implementation]
0008 //
0009 // Original Author:  Chris Jones
0010 //         Created:  Tue May  3 11:13:47 CDT 2011
0011 //
0012 
0013 // system include files
0014 #include <memory>
0015 
0016 #include "TFile.h"
0017 #include "TString.h"
0018 #include "TTree.h"
0019 #include <map>
0020 #include <string>
0021 #include <vector>
0022 
0023 #include "DQMServices/Core/interface/DQMStore.h"
0024 #include "DataFormats/Histograms/interface/DQMToken.h"
0025 #include "FWCore/ServiceRegistry/interface/Service.h"
0026 
0027 #include "FWCore/Framework/interface/InputSource.h"
0028 #include "FWCore/Sources/interface/PuttableSourceBase.h"
0029 #include "FWCore/Catalog/interface/InputFileCatalog.h"
0030 #include "FWCore/ParameterSet/interface/ParameterSet.h"
0031 #include "FWCore/Utilities/interface/ExceptionPropagate.h"
0032 
0033 #include "FWCore/Framework/interface/RunPrincipal.h"
0034 #include "FWCore/Framework/interface/LuminosityBlockPrincipal.h"
0035 
0036 #include "FWCore/Framework/interface/Run.h"
0037 #include "FWCore/Framework/interface/LuminosityBlock.h"
0038 #include "DataFormats/Provenance/interface/LuminosityBlockID.h"
0039 #include "DataFormats/Provenance/interface/LuminosityBlockRange.h"
0040 #include "DataFormats/Provenance/interface/ProcessHistoryRegistry.h"
0041 
0042 #include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
0043 #include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
0044 
0045 #include "FWCore/Framework/interface/InputSourceMacros.h"
0046 #include "FWCore/Framework/interface/FileBlock.h"
0047 
0048 #include "FWCore/MessageLogger/interface/MessageLogger.h"
0049 #include "FWCore/MessageLogger/interface/JobReport.h"
0050 #include "FWCore/Utilities/interface/TimeOfDay.h"
0051 
0052 #include "format.h"
0053 
0054 // class rather than namespace so we can make this a friend of the
0055 // MonitorElement to get access to constructors etc.
0056 struct DQMTTreeIO {
0057   typedef dqm::harvesting::MonitorElement MonitorElement;
0058   typedef dqm::harvesting::DQMStore DQMStore;
0059 
0060   // TODO: this should probably be moved somewhere else
0061   class DQMMergeHelper {
0062   public:
0063     // Utility function to check the consistency of the axis labels
0064     // Taken from TH1::CheckBinLabels which is not public
0065     static bool CheckBinLabels(const TAxis* a1, const TAxis* a2) {
0066       // Check that axis have same labels
0067       THashList* l1 = (const_cast<TAxis*>(a1))->GetLabels();
0068       THashList* l2 = (const_cast<TAxis*>(a2))->GetLabels();
0069 
0070       if (!l1 && !l2)
0071         return true;
0072       if (!l1 || !l2) {
0073         return false;
0074       }
0075 
0076       // Check now labels sizes  are the same
0077       if (l1->GetSize() != l2->GetSize()) {
0078         return false;
0079       }
0080 
0081       for (int i = 1; i <= a1->GetNbins(); ++i) {
0082         std::string_view label1 = a1->GetBinLabel(i);
0083         std::string_view label2 = a2->GetBinLabel(i);
0084         if (label1 != label2) {
0085           return false;
0086         }
0087       }
0088 
0089       return true;
0090     }
0091 
0092     // NOTE: the merge logic comes from DataFormats/Histograms/interface/MEtoEDMFormat.h
0093     static void mergeTogether(TH1* original, TH1* toAdd) {
0094       if (original->CanExtendAllAxes() && toAdd->CanExtendAllAxes()) {
0095         TList list;
0096         list.Add(toAdd);
0097         if (original->Merge(&list) == -1) {
0098           edm::LogError("MergeFailure") << "Failed to merge DQM element " << original->GetName();
0099         }
0100       } else {
0101         // TODO: Redo. This is both more strict than what ROOT checks for yet
0102         // allows cases where ROOT fails with merging.
0103         if (original->GetNbinsX() == toAdd->GetNbinsX() &&
0104             original->GetXaxis()->GetXmin() == toAdd->GetXaxis()->GetXmin() &&
0105             original->GetXaxis()->GetXmax() == toAdd->GetXaxis()->GetXmax() &&
0106             original->GetNbinsY() == toAdd->GetNbinsY() &&
0107             original->GetYaxis()->GetXmin() == toAdd->GetYaxis()->GetXmin() &&
0108             original->GetYaxis()->GetXmax() == toAdd->GetYaxis()->GetXmax() &&
0109             original->GetNbinsZ() == toAdd->GetNbinsZ() &&
0110             original->GetZaxis()->GetXmin() == toAdd->GetZaxis()->GetXmin() &&
0111             original->GetZaxis()->GetXmax() == toAdd->GetZaxis()->GetXmax() &&
0112             CheckBinLabels(original->GetXaxis(), toAdd->GetXaxis()) &&
0113             CheckBinLabels(original->GetYaxis(), toAdd->GetYaxis()) &&
0114             CheckBinLabels(original->GetZaxis(), toAdd->GetZaxis())) {
0115           original->Add(toAdd);
0116         } else {
0117           edm::LogError("MergeFailure") << "Found histograms with different axis limits or different labels '"
0118                                         << original->GetName() << "' not merged.";
0119         }
0120       }
0121     }
0122   };
0123 
0124   // This struct allows to find all MEs belonging to a run-lumi pair
0125   // All files will be open at once so m_file property indicates the file where data is saved.
0126   struct FileMetadata {
0127     unsigned int m_run;
0128     unsigned int m_lumi;
0129     ULong64_t m_beginTime;
0130     ULong64_t m_endTime;
0131     ULong64_t m_firstIndex;
0132     ULong64_t m_lastIndex;  // Last is inclusive
0133     unsigned int m_type;
0134     TFile* m_file;
0135 
0136     // This will be used when sorting a vector
0137     bool operator<(const FileMetadata& obj) const {
0138       if (m_run == obj.m_run)
0139         return m_lumi < obj.m_lumi;
0140       else
0141         return m_run < obj.m_run;
0142     }
0143 
0144     void describe() {
0145       std::cout << "read r:" << m_run << " l:" << m_lumi << " bt:" << m_beginTime << " et:" << m_endTime
0146                 << " fi:" << m_firstIndex << " li:" << m_lastIndex << " type:" << m_type << " file: " << m_file
0147                 << std::endl;
0148     }
0149   };
0150 
0151   class TreeReaderBase {
0152   public:
0153     TreeReaderBase(MonitorElementData::Kind kind, MonitorElementData::Scope rescope)
0154         : m_kind(kind), m_rescope(rescope) {}
0155     virtual ~TreeReaderBase() {}
0156 
0157     MonitorElementData::Key makeKey(std::string const& fullname, int run, int lumi) {
0158       MonitorElementData::Key key;
0159       key.kind_ = m_kind;
0160       key.path_.set(fullname, MonitorElementData::Path::Type::DIR_AND_NAME);
0161       if (m_rescope == MonitorElementData::Scope::LUMI) {
0162         // no rescoping
0163         key.scope_ = lumi == 0 ? MonitorElementData::Scope::RUN : MonitorElementData::Scope::LUMI;
0164         key.id_ = edm::LuminosityBlockID(run, lumi);
0165       } else if (m_rescope == MonitorElementData::Scope::RUN) {
0166         // everything becomes run, we'll never see Scope::JOB inside DQMIO files.
0167         key.scope_ = MonitorElementData::Scope::RUN;
0168         key.id_ = edm::LuminosityBlockID(run, 0);
0169       } else if (m_rescope == MonitorElementData::Scope::JOB) {
0170         // Everything is aggregated over the entire job.
0171         key.scope_ = MonitorElementData::Scope::JOB;
0172         key.id_ = edm::LuminosityBlockID(0, 0);
0173       } else {
0174         assert(!"Invalid Scope in rescope option.");
0175       }
0176       return key;
0177     }
0178     virtual void read(ULong64_t iIndex, DQMStore* dqmstore, int run, int lumi) = 0;
0179     virtual void setTree(TTree* iTree) = 0;
0180 
0181   protected:
0182     MonitorElementData::Kind m_kind;
0183     MonitorElementData::Scope m_rescope;
0184   };
0185 
0186   template <class T>
0187   class TreeObjectReader : public TreeReaderBase {
0188   public:
0189     TreeObjectReader(MonitorElementData::Kind kind, MonitorElementData::Scope rescope) : TreeReaderBase(kind, rescope) {
0190       assert(m_kind != MonitorElementData::Kind::INT);
0191       assert(m_kind != MonitorElementData::Kind::REAL);
0192       assert(m_kind != MonitorElementData::Kind::STRING);
0193     }
0194 
0195     void read(ULong64_t iIndex, DQMStore* dqmstore, int run, int lumi) override {
0196       // This will populate the fields as defined in setTree method
0197       m_tree->GetEntry(iIndex);
0198 
0199       auto key = makeKey(*m_fullName, run, lumi);
0200       auto existing = dqmstore->findOrRecycle(key);
0201       if (existing) {
0202         // TODO: make sure there is sufficient locking here.
0203         DQMMergeHelper::mergeTogether(existing->getTH1(), m_buffer);
0204       } else {
0205         // We make our own MEs here, to avoid a round-trip through the booking API.
0206         MonitorElementData meData;
0207         meData.key_ = key;
0208         meData.value_.object_ = std::unique_ptr<T>((T*)(m_buffer->Clone()));
0209         auto me = new MonitorElement(std::move(meData));
0210         dqmstore->putME(me);
0211       }
0212     }
0213 
0214     void setTree(TTree* iTree) override {
0215       m_tree = iTree;
0216       m_tree->SetBranchAddress(kFullNameBranch, &m_fullName);
0217       m_tree->SetBranchAddress(kFlagBranch, &m_tag);
0218       m_tree->SetBranchAddress(kValueBranch, &m_buffer);
0219     }
0220 
0221   private:
0222     TTree* m_tree = nullptr;
0223     std::string* m_fullName = nullptr;
0224     T* m_buffer = nullptr;
0225     uint32_t m_tag = 0;
0226   };
0227 
0228   class TreeStringReader : public TreeReaderBase {
0229   public:
0230     TreeStringReader(MonitorElementData::Kind kind, MonitorElementData::Scope rescope) : TreeReaderBase(kind, rescope) {
0231       assert(m_kind == MonitorElementData::Kind::STRING);
0232     }
0233 
0234     void read(ULong64_t iIndex, DQMStore* dqmstore, int run, int lumi) override {
0235       // This will populate the fields as defined in setTree method
0236       m_tree->GetEntry(iIndex);
0237 
0238       auto key = makeKey(*m_fullName, run, lumi);
0239       auto existing = dqmstore->findOrRecycle(key);
0240 
0241       if (existing) {
0242         existing->Fill(*m_value);
0243       } else {
0244         // We make our own MEs here, to avoid a round-trip through the booking API.
0245         MonitorElementData meData;
0246         meData.key_ = key;
0247         meData.value_.scalar_.str = *m_value;
0248         auto me = new MonitorElement(std::move(meData));
0249         dqmstore->putME(me);
0250       }
0251     }
0252 
0253     void setTree(TTree* iTree) override {
0254       m_tree = iTree;
0255       m_tree->SetBranchAddress(kFullNameBranch, &m_fullName);
0256       m_tree->SetBranchAddress(kFlagBranch, &m_tag);
0257       m_tree->SetBranchAddress(kValueBranch, &m_value);
0258     }
0259 
0260   private:
0261     TTree* m_tree = nullptr;
0262     std::string* m_fullName = nullptr;
0263     std::string* m_value = nullptr;
0264     uint32_t m_tag = 0;
0265   };
0266 
0267   template <class T>
0268   class TreeSimpleReader : public TreeReaderBase {
0269   public:
0270     TreeSimpleReader(MonitorElementData::Kind kind, MonitorElementData::Scope rescope) : TreeReaderBase(kind, rescope) {
0271       assert(m_kind == MonitorElementData::Kind::INT || m_kind == MonitorElementData::Kind::REAL);
0272     }
0273 
0274     void read(ULong64_t iIndex, DQMStore* dqmstore, int run, int lumi) override {
0275       // This will populate the fields as defined in setTree method
0276       m_tree->GetEntry(iIndex);
0277 
0278       auto key = makeKey(*m_fullName, run, lumi);
0279       auto existing = dqmstore->findOrRecycle(key);
0280 
0281       if (existing) {
0282         existing->Fill(m_buffer);
0283       } else {
0284         // We make our own MEs here, to avoid a round-trip through the booking API.
0285         MonitorElementData meData;
0286         meData.key_ = key;
0287         if (m_kind == MonitorElementData::Kind::INT)
0288           meData.value_.scalar_.num = m_buffer;
0289         else if (m_kind == MonitorElementData::Kind::REAL)
0290           meData.value_.scalar_.real = m_buffer;
0291         auto me = new MonitorElement(std::move(meData));
0292         dqmstore->putME(me);
0293       }
0294     }
0295 
0296     void setTree(TTree* iTree) override {
0297       m_tree = iTree;
0298       m_tree->SetBranchAddress(kFullNameBranch, &m_fullName);
0299       m_tree->SetBranchAddress(kFlagBranch, &m_tag);
0300       m_tree->SetBranchAddress(kValueBranch, &m_buffer);
0301     }
0302 
0303   private:
0304     TTree* m_tree = nullptr;
0305     std::string* m_fullName = nullptr;
0306     T m_buffer = 0;
0307     uint32_t m_tag = 0;
0308   };
0309 };
0310 
0311 class DQMRootSource : public edm::PuttableSourceBase, DQMTTreeIO {
0312 public:
0313   DQMRootSource(edm::ParameterSet const&, const edm::InputSourceDescription&);
0314   DQMRootSource(const DQMRootSource&) = delete;
0315   ~DQMRootSource() override;
0316 
0317   // ---------- const member functions ---------------------
0318 
0319   const DQMRootSource& operator=(const DQMRootSource&) = delete;  // stop default
0320 
0321   // ---------- static member functions --------------------
0322 
0323   // ---------- member functions ---------------------------
0324   static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
0325 
0326 private:
0327   edm::InputSource::ItemType getNextItemType() override;
0328 
0329   std::shared_ptr<edm::FileBlock> readFile_() override;
0330   std::shared_ptr<edm::RunAuxiliary> readRunAuxiliary_() override;
0331   std::shared_ptr<edm::LuminosityBlockAuxiliary> readLuminosityBlockAuxiliary_() override;
0332   void readRun_(edm::RunPrincipal& rpCache) override;
0333   void readLuminosityBlock_(edm::LuminosityBlockPrincipal& lbCache) override;
0334   void readEvent_(edm::EventPrincipal&) override;
0335 
0336   // Read MEs from m_fileMetadatas to DQMStore  till run or lumi transition
0337   void readElements();
0338   // True if m_currentIndex points to an element that has a different
0339   // run or lumi than the previous element (a transition needs to happen).
0340   // False otherwise.
0341   bool isRunOrLumiTransition() const;
0342   void readNextItemType();
0343 
0344   // These methods will be called by the framework.
0345   // MEs in DQMStore  will be put to products.
0346   void beginRun(edm::Run& run) override;
0347   void beginLuminosityBlock(edm::LuminosityBlock& lumi) override;
0348 
0349   // If the run matches the filterOnRun configuration parameter, the run
0350   // (and all its lumis) will be kept.
0351   // Otherwise, check if a run and a lumi are in the range that needs to be processed.
0352   // Range is retrieved from lumisToProcess configuration parameter.
0353   // If at least one lumi of a run needs to be kept, per run MEs of that run will also be kept.
0354   bool keepIt(edm::RunNumber_t, edm::LuminosityBlockNumber_t) const;
0355   void logFileAction(char const* msg, char const* fileName) const;
0356 
0357   // ---------- member data --------------------------------
0358 
0359   // Properties from python config
0360   bool m_skipBadFiles;
0361   unsigned int m_filterOnRun;
0362   edm::InputFileCatalog m_catalog;
0363   std::vector<edm::LuminosityBlockRange> m_lumisToProcess;
0364   MonitorElementData::Scope m_rescope;
0365 
0366   edm::InputSource::ItemType m_nextItemType;
0367   // Each ME type gets its own reader
0368   std::vector<std::shared_ptr<TreeReaderBase>> m_treeReaders;
0369 
0370   // Index of currenlty processed row in m_fileMetadatas
0371   unsigned int m_currentIndex;
0372 
0373   // All open DQMIO files
0374   struct OpenFileInfo {
0375     OpenFileInfo(TFile* file, edm::JobReport::Token jrToken) : m_file(file), m_jrToken(jrToken) {}
0376     ~OpenFileInfo() {
0377       edm::Service<edm::JobReport> jr;
0378       jr->inputFileClosed(edm::InputType::Primary, m_jrToken);
0379     }
0380 
0381     OpenFileInfo(OpenFileInfo&&) = default;
0382     OpenFileInfo& operator=(OpenFileInfo&&) = default;
0383 
0384     std::unique_ptr<TFile> m_file;
0385     edm::JobReport::Token m_jrToken;
0386   };
0387   std::vector<OpenFileInfo> m_openFiles;
0388 
0389   // An item here is a row read from DQMIO indices (metadata) table
0390   std::vector<FileMetadata> m_fileMetadatas;
0391 };
0392 
0393 //
0394 // constants, enums and typedefs
0395 //
0396 
0397 //
0398 // static data member definitions
0399 //
0400 
0401 void DQMRootSource::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
0402   edm::ParameterSetDescription desc;
0403   desc.addUntracked<std::vector<std::string>>("fileNames")->setComment("Names of files to be processed.");
0404   desc.addUntracked<unsigned int>("filterOnRun", 0)->setComment("Just limit the process to the selected run.");
0405   desc.addUntracked<std::string>("reScope", "JOB")
0406       ->setComment(
0407           "Accumulate histograms more coarsely."
0408           " Options: \"\": keep unchanged, \"RUN\": turn LUMI histograms into RUN histograms, \"JOB\": turn everything "
0409           "into JOB histograms.");
0410   desc.addUntracked<bool>("skipBadFiles", false)->setComment("Skip the file if it is not valid");
0411   desc.addUntracked<std::string>("overrideCatalog", std::string())
0412       ->setComment("An alternate file catalog to use instead of the standard site one.");
0413   std::vector<edm::LuminosityBlockRange> defaultLumis;
0414   desc.addUntracked<std::vector<edm::LuminosityBlockRange>>("lumisToProcess", defaultLumis)
0415       ->setComment("Skip any lumi inside the specified run:lumi range.");
0416 
0417   descriptions.addDefault(desc);
0418 }
0419 
0420 //
0421 // constructors and destructor
0422 //
0423 
0424 DQMRootSource::DQMRootSource(edm::ParameterSet const& iPSet, const edm::InputSourceDescription& iDesc)
0425     : edm::PuttableSourceBase(iPSet, iDesc),
0426       m_skipBadFiles(iPSet.getUntrackedParameter<bool>("skipBadFiles", false)),
0427       m_filterOnRun(iPSet.getUntrackedParameter<unsigned int>("filterOnRun", 0)),
0428       m_catalog(iPSet.getUntrackedParameter<std::vector<std::string>>("fileNames"),
0429                 iPSet.getUntrackedParameter<std::string>("overrideCatalog")),
0430       m_lumisToProcess(iPSet.getUntrackedParameter<std::vector<edm::LuminosityBlockRange>>(
0431           "lumisToProcess", std::vector<edm::LuminosityBlockRange>())),
0432       m_rescope(std::map<std::string, MonitorElementData::Scope>{
0433           {"", MonitorElementData::Scope::LUMI},
0434           {"LUMI", MonitorElementData::Scope::LUMI},
0435           {"RUN", MonitorElementData::Scope::RUN},
0436           {"JOB", MonitorElementData::Scope::JOB}}[iPSet.getUntrackedParameter<std::string>("reScope", "JOB")]),
0437       m_nextItemType(edm::InputSource::IsFile),
0438       m_treeReaders(kNIndicies, std::shared_ptr<TreeReaderBase>()),
0439       m_currentIndex(0),
0440       m_openFiles(std::vector<OpenFileInfo>()),
0441       m_fileMetadatas(std::vector<FileMetadata>()) {
0442   edm::sortAndRemoveOverlaps(m_lumisToProcess);
0443 
0444   if (m_catalog.fileNames(0).empty()) {
0445     m_nextItemType = edm::InputSource::IsStop;
0446   } else {
0447     m_treeReaders[kIntIndex].reset(new TreeSimpleReader<Long64_t>(MonitorElementData::Kind::INT, m_rescope));
0448     m_treeReaders[kFloatIndex].reset(new TreeSimpleReader<double>(MonitorElementData::Kind::REAL, m_rescope));
0449     m_treeReaders[kStringIndex].reset(new TreeStringReader(MonitorElementData::Kind::STRING, m_rescope));
0450     m_treeReaders[kTH1FIndex].reset(new TreeObjectReader<TH1F>(MonitorElementData::Kind::TH1F, m_rescope));
0451     m_treeReaders[kTH1SIndex].reset(new TreeObjectReader<TH1S>(MonitorElementData::Kind::TH1S, m_rescope));
0452     m_treeReaders[kTH1DIndex].reset(new TreeObjectReader<TH1D>(MonitorElementData::Kind::TH1D, m_rescope));
0453     m_treeReaders[kTH1IIndex].reset(new TreeObjectReader<TH1I>(MonitorElementData::Kind::TH1I, m_rescope));
0454     m_treeReaders[kTH2FIndex].reset(new TreeObjectReader<TH2F>(MonitorElementData::Kind::TH2F, m_rescope));
0455     m_treeReaders[kTH2SIndex].reset(new TreeObjectReader<TH2S>(MonitorElementData::Kind::TH2S, m_rescope));
0456     m_treeReaders[kTH2DIndex].reset(new TreeObjectReader<TH2D>(MonitorElementData::Kind::TH2D, m_rescope));
0457     m_treeReaders[kTH2IIndex].reset(new TreeObjectReader<TH2I>(MonitorElementData::Kind::TH2I, m_rescope));
0458     m_treeReaders[kTH3FIndex].reset(new TreeObjectReader<TH3F>(MonitorElementData::Kind::TH3F, m_rescope));
0459     m_treeReaders[kTProfileIndex].reset(new TreeObjectReader<TProfile>(MonitorElementData::Kind::TPROFILE, m_rescope));
0460     m_treeReaders[kTProfile2DIndex].reset(
0461         new TreeObjectReader<TProfile2D>(MonitorElementData::Kind::TPROFILE2D, m_rescope));
0462   }
0463 
0464   produces<DQMToken, edm::Transition::BeginRun>("DQMGenerationRecoRun");
0465   produces<DQMToken, edm::Transition::BeginLuminosityBlock>("DQMGenerationRecoLumi");
0466 }
0467 
0468 DQMRootSource::~DQMRootSource() {
0469   for (auto& file : m_openFiles) {
0470     if (file.m_file && file.m_file->IsOpen()) {
0471       logFileAction("Closed file", "");
0472     }
0473   }
0474 }
0475 
0476 //
0477 // member functions
0478 //
0479 
0480 edm::InputSource::ItemType DQMRootSource::getNextItemType() { return m_nextItemType; }
0481 
0482 // We will read the metadata of all files and fill m_fileMetadatas vector
0483 std::shared_ptr<edm::FileBlock> DQMRootSource::readFile_() {
0484   const int numFiles = m_catalog.fileNames(0).size();
0485   m_openFiles.reserve(numFiles);
0486 
0487   for (auto& fileitem : m_catalog.fileCatalogItems()) {
0488     TFile* file;
0489     std::string pfn;
0490     std::string lfn;
0491     std::list<std::string> exInfo;
0492     //loop over names of a file, each of them corresponds to a data catalog
0493     bool isGoodFile(true);
0494     //get all names of a file, each of them corresponds to a data catalog
0495     const std::vector<std::string>& fNames = fileitem.fileNames();
0496     for (std::vector<std::string>::const_iterator it = fNames.begin(); it != fNames.end(); ++it) {
0497       // Try to open a file
0498       try {
0499         file = TFile::Open(it->c_str());
0500 
0501         // Exception will be trapped so we pull it out ourselves
0502         std::exception_ptr e = edm::threadLocalException::getException();
0503         if (e != std::exception_ptr()) {
0504           edm::threadLocalException::setException(std::exception_ptr());
0505           std::rethrow_exception(e);
0506         }
0507 
0508       } catch (cms::Exception const& e) {
0509         file = nullptr;                       // is there anything we need to free?
0510         if (std::next(it) == fNames.end()) {  //last name corresponding to the last data catalog to try
0511           if (!m_skipBadFiles) {
0512             edm::Exception ex(edm::errors::FileOpenError, "", e);
0513             ex.addContext("Opening DQM Root file");
0514             ex << "\nInput file " << *it << " was not found, could not be opened, or is corrupted.\n";
0515             //report previous exceptions when use other names to open file
0516             for (auto const& s : exInfo)
0517               ex.addAdditionalInfo(s);
0518             throw ex;
0519           }
0520           isGoodFile = false;
0521         }
0522         // save in case of error when trying next name
0523         for (auto const& s : e.additionalInfo())
0524           exInfo.push_back(s);
0525       }
0526 
0527       // Check if a file is usable
0528       if (file && !file->IsZombie()) {
0529         logFileAction("Successfully opened file ", it->c_str());
0530         pfn = *it;
0531         lfn = fileitem.logicalFileName();
0532         break;
0533       } else {
0534         if (std::next(it) == fNames.end()) {
0535           if (!m_skipBadFiles) {
0536             edm::Exception ex(edm::errors::FileOpenError);
0537             ex << "Input file " << *it << " could not be opened.\n";
0538             ex.addContext("Opening DQM Root file");
0539             //report previous exceptions when use other names to open file
0540             for (auto const& s : exInfo)
0541               ex.addAdditionalInfo(s);
0542             throw ex;
0543           }
0544           isGoodFile = false;
0545         }
0546         if (file) {
0547           delete file;
0548           file = nullptr;
0549         }
0550       }
0551     }  //end loop over names of the file
0552 
0553     if (!isGoodFile && m_skipBadFiles)
0554       continue;
0555 
0556     std::unique_ptr<std::string> guid{file->Get<std::string>(kCmsGuid)};
0557     if (not guid) {
0558       guid = std::make_unique<std::string>(file->GetUUID().AsString());
0559       std::transform(guid->begin(), guid->end(), guid->begin(), (int (*)(int))std::toupper);
0560     }
0561 
0562     edm::Service<edm::JobReport> jr;
0563     auto jrToken = jr->inputFileOpened(
0564         pfn, lfn, std::string(), std::string(), "DQMRootSource", "source", *guid, std::vector<std::string>());
0565     m_openFiles.emplace_back(file, jrToken);
0566 
0567     // Check file format version, which is encoded in the Title of the TFile
0568     if (strcmp(file->GetTitle(), "1") != 0) {
0569       edm::Exception ex(edm::errors::FileReadError);
0570       ex << "Input file " << fNames[0] << " does not appear to be a DQM Root file.\n";
0571     }
0572 
0573     // Read metadata from the file
0574     TTree* indicesTree = dynamic_cast<TTree*>(file->Get(kIndicesTree));
0575     assert(indicesTree != nullptr);
0576 
0577     FileMetadata temp;
0578     // Each line of metadata will be read into the coresponding fields of temp.
0579     indicesTree->SetBranchAddress(kRunBranch, &temp.m_run);
0580     indicesTree->SetBranchAddress(kLumiBranch, &temp.m_lumi);
0581     indicesTree->SetBranchAddress(kBeginTimeBranch, &temp.m_beginTime);
0582     indicesTree->SetBranchAddress(kEndTimeBranch, &temp.m_endTime);
0583     indicesTree->SetBranchAddress(kTypeBranch, &temp.m_type);
0584     indicesTree->SetBranchAddress(kFirstIndex, &temp.m_firstIndex);
0585     indicesTree->SetBranchAddress(kLastIndex, &temp.m_lastIndex);
0586 
0587     for (Long64_t index = 0; index != indicesTree->GetEntries(); ++index) {
0588       indicesTree->GetEntry(index);
0589       temp.m_file = file;
0590 
0591       if (keepIt(temp.m_run, temp.m_lumi)) {
0592         m_fileMetadatas.push_back(temp);
0593       }
0594     }
0595 
0596   }  //end loop over files
0597 
0598   // Sort to make sure runs and lumis appear in sequential order
0599   std::stable_sort(m_fileMetadatas.begin(), m_fileMetadatas.end());
0600 
0601   // If we have lumisections without matching runs, insert dummy runs here.
0602   unsigned int run = 0;
0603   auto toadd = std::vector<FileMetadata>();
0604   for (auto& metadata : m_fileMetadatas) {
0605     if (run < metadata.m_run && metadata.m_lumi != 0) {
0606       // run transition and lumi transition at the same time!
0607       FileMetadata dummy{};  // zero initialize
0608       dummy.m_run = metadata.m_run;
0609       dummy.m_lumi = 0;
0610       dummy.m_type = kNoTypesStored;
0611       toadd.push_back(dummy);
0612     }
0613     run = metadata.m_run;
0614   }
0615 
0616   if (!toadd.empty()) {
0617     // rather than trying to insert at the right places, just append and sort again.
0618     m_fileMetadatas.insert(m_fileMetadatas.end(), toadd.begin(), toadd.end());
0619     std::stable_sort(m_fileMetadatas.begin(), m_fileMetadatas.end());
0620   }
0621 
0622   //for (auto& metadata : m_fileMetadatas)
0623   //  metadata.describe();
0624 
0625   // Stop if there's nothing to process. Otherwise start the run.
0626   if (m_fileMetadatas.empty())
0627     m_nextItemType = edm::InputSource::IsStop;
0628   else
0629     m_nextItemType = edm::InputSource::IsRun;
0630 
0631   // We have to return something but not sure why
0632   return std::make_shared<edm::FileBlock>();
0633 }
0634 
0635 std::shared_ptr<edm::RunAuxiliary> DQMRootSource::readRunAuxiliary_() {
0636   FileMetadata metadata = m_fileMetadatas[m_currentIndex];
0637   auto runAux =
0638       edm::RunAuxiliary(metadata.m_run, edm::Timestamp(metadata.m_beginTime), edm::Timestamp(metadata.m_endTime));
0639   return std::make_shared<edm::RunAuxiliary>(runAux);
0640 }
0641 
0642 std::shared_ptr<edm::LuminosityBlockAuxiliary> DQMRootSource::readLuminosityBlockAuxiliary_() {
0643   FileMetadata metadata = m_fileMetadatas[m_currentIndex];
0644   auto lumiAux = edm::LuminosityBlockAuxiliary(edm::LuminosityBlockID(metadata.m_run, metadata.m_lumi),
0645                                                edm::Timestamp(metadata.m_beginTime),
0646                                                edm::Timestamp(metadata.m_endTime));
0647   return std::make_shared<edm::LuminosityBlockAuxiliary>(lumiAux);
0648 }
0649 
0650 void DQMRootSource::readRun_(edm::RunPrincipal& rpCache) {
0651   // Read elements of a current run.
0652   do {
0653     FileMetadata metadata = m_fileMetadatas[m_currentIndex];
0654     if (metadata.m_lumi == 0) {
0655       readElements();
0656     }
0657     m_currentIndex++;
0658   } while (!isRunOrLumiTransition());
0659 
0660   readNextItemType();
0661 
0662   edm::Service<edm::JobReport> jr;
0663   jr->reportInputRunNumber(rpCache.id().run());
0664   rpCache.fillRunPrincipal(processHistoryRegistryForUpdate());
0665 }
0666 
0667 void DQMRootSource::readLuminosityBlock_(edm::LuminosityBlockPrincipal& lbCache) {
0668   // Read elements of a current lumi.
0669   do {
0670     readElements();
0671     m_currentIndex++;
0672   } while (!isRunOrLumiTransition());
0673 
0674   readNextItemType();
0675 
0676   edm::Service<edm::JobReport> jr;
0677   jr->reportInputLumiSection(lbCache.id().run(), lbCache.id().luminosityBlock());
0678   lbCache.fillLuminosityBlockPrincipal(processHistoryRegistry().getMapped(lbCache.aux().processHistoryID()));
0679 }
0680 
0681 void DQMRootSource::readEvent_(edm::EventPrincipal&) {}
0682 
0683 void DQMRootSource::readElements() {
0684   FileMetadata metadata = m_fileMetadatas[m_currentIndex];
0685 
0686   if (metadata.m_type != kNoTypesStored) {
0687     std::shared_ptr<TreeReaderBase> reader = m_treeReaders[metadata.m_type];
0688     TTree* tree = dynamic_cast<TTree*>(metadata.m_file->Get(kTypeNames[metadata.m_type]));
0689     // The Reset() below screws up the tree, so we need to re-read it from file
0690     // before use here.
0691     tree->Refresh();
0692 
0693     reader->setTree(tree);
0694 
0695     ULong64_t index = metadata.m_firstIndex;
0696     ULong64_t endIndex = metadata.m_lastIndex + 1;
0697 
0698     for (; index != endIndex; ++index) {
0699       reader->read(index, edm::Service<DQMStore>().operator->(), metadata.m_run, metadata.m_lumi);
0700     }
0701     // Drop buffers in the TTree. This reduces memory consuption while the tree
0702     // just sits there and waits for the next block to be read.
0703     tree->Reset();
0704   }
0705 }
0706 
0707 bool DQMRootSource::isRunOrLumiTransition() const {
0708   if (m_currentIndex == 0) {
0709     return false;
0710   }
0711 
0712   if (m_currentIndex > m_fileMetadatas.size() - 1) {
0713     // We reached the end
0714     return true;
0715   }
0716 
0717   FileMetadata previousMetadata = m_fileMetadatas[m_currentIndex - 1];
0718   FileMetadata metadata = m_fileMetadatas[m_currentIndex];
0719 
0720   return previousMetadata.m_run != metadata.m_run || previousMetadata.m_lumi != metadata.m_lumi;
0721 }
0722 
0723 void DQMRootSource::readNextItemType() {
0724   if (m_currentIndex == 0) {
0725     m_nextItemType = edm::InputSource::IsRun;
0726   } else if (m_currentIndex > m_fileMetadatas.size() - 1) {
0727     // We reached the end
0728     m_nextItemType = edm::InputSource::IsStop;
0729   } else {
0730     FileMetadata previousMetadata = m_fileMetadatas[m_currentIndex - 1];
0731     FileMetadata metadata = m_fileMetadatas[m_currentIndex];
0732 
0733     if (previousMetadata.m_run != metadata.m_run) {
0734       m_nextItemType = edm::InputSource::IsRun;
0735     } else if (previousMetadata.m_lumi != metadata.m_lumi) {
0736       m_nextItemType = edm::InputSource::IsLumi;
0737     }
0738   }
0739 }
0740 
0741 void DQMRootSource::beginRun(edm::Run& run) {
0742   std::unique_ptr<DQMToken> product = std::make_unique<DQMToken>();
0743   run.put(std::move(product), "DQMGenerationRecoRun");
0744 }
0745 
0746 void DQMRootSource::beginLuminosityBlock(edm::LuminosityBlock& lumi) {
0747   std::unique_ptr<DQMToken> product = std::make_unique<DQMToken>();
0748   lumi.put(std::move(product), "DQMGenerationRecoLumi");
0749 }
0750 
0751 bool DQMRootSource::keepIt(edm::RunNumber_t run, edm::LuminosityBlockNumber_t lumi) const {
0752   if (m_filterOnRun != 0 && run != m_filterOnRun) {
0753     return false;
0754   }
0755 
0756   if (m_lumisToProcess.empty()) {
0757     return true;
0758   }
0759 
0760   for (edm::LuminosityBlockRange const& lumiToProcess : m_lumisToProcess) {
0761     if (run >= lumiToProcess.startRun() && run <= lumiToProcess.endRun()) {
0762       if (lumi >= lumiToProcess.startLumi() && lumi <= lumiToProcess.endLumi()) {
0763         return true;
0764       } else if (lumi == 0) {
0765         return true;
0766       }
0767     }
0768   }
0769   return false;
0770 }
0771 
0772 void DQMRootSource::logFileAction(char const* msg, char const* fileName) const {
0773   edm::LogAbsolute("fileAction") << std::setprecision(0) << edm::TimeOfDay() << msg << fileName;
0774   edm::FlushMessageLog();
0775 }
0776 
0777 //
0778 // const member functions
0779 //
0780 
0781 //
0782 // static member functions
0783 //
0784 DEFINE_FWK_INPUT_SOURCE(DQMRootSource);