Belle II Software  release-08-01-10
RootFileCreationManager.cc
1 /**************************************************************************
2  * basf2 (Belle II Analysis Software Framework) *
3  * Author: The Belle II Collaboration *
4  * *
5  * See git log for contributors and copyright holders. *
6  * This file is licensed under LGPL-3.0, see LICENSE.md. *
7  **************************************************************************/
8 
9 #include <framework/utilities/RootFileCreationManager.h>
10 #include <framework/logging/Logger.h>
11 #include <framework/core/MetadataService.h>
12 #include <iomanip>
13 
14 namespace {
16  void TFile_Deleter(TFile* file)
17  {
18  if (!file) return;
19  B2DEBUG(30, "Closing ROOT file");
20  if (file->IsOpen()) {
21  file->Close();
23  }
24  delete file;
25  }
26 }
27 
28 namespace Belle2 {
33  std::shared_ptr<TFile> RootFileCreationManager::getFile(std::string fileName, bool ignoreErrors)
34  {
35  std::shared_ptr<TFile> ptr = m_files[fileName].lock();
36  if (!ptr) {
37  // make sure stupid gDirectory is not modified ... that means that users
38  // have to ptr->cd() but plays nice with other modules which might not
39  // set their cd() correctly.
40  TDirectory::TContext gDirectoryGuard;
41  // Create shared ptr for the file which will correctly close it when the last user disconnects.
42  ptr = std::shared_ptr<TFile>(TFile::Open(fileName.c_str(), "RECREATE"), TFile_Deleter);
43  // Check if the file is actually open ... otherwise no use in returning it
44  if (!ptr || !ptr->IsOpen()) {
45  if (!ignoreErrors) B2ERROR("Could not create file " << std::quoted(fileName));
46  return nullptr;
47  }
48  //remember this ...
49  m_files[fileName] = ptr;
50  }
51  return ptr;
52  }
53 
55  {
56  static RootFileCreationManager instance;
57  return instance;
58  }
60 }
static MetadataService & Instance()
Static method to get a reference to the MetadataService instance.
void addRootNtupleFile(const std::string &fileName)
Add the metadata of a root ntuple file.
This single instance class takes track of all open ROOT files open in "create" mode,...
std::map< std::string, std::weak_ptr< TFile > > m_files
store for the open files
std::shared_ptr< TFile > getFile(std::string, bool ignoreErrors=false)
Get a file with a specific name, if is does not exist it will be created.
static RootFileCreationManager & getInstance()
Interface for the FileManager.
Abstract base class for different kinds of events.