9#include <boost/python.hpp>
11#include <daq/storage/modules/StorageRootOutputModule.h>
13#include <framework/io/RootIOUtilities.h>
14#include <framework/core/FileCatalog.h>
15#include <framework/core/MetadataService.h>
16#include <framework/core/RandomNumbers.h>
17#include <framework/database/Database.h>
19#include <framework/core/ModuleParam.templateDetails.h>
20#include <framework/utilities/EnvironmentVariables.h>
22#include <boost/format.hpp>
23#include <boost/algorithm/string.hpp>
25#include <TClonesArray.h>
27#include <nlohmann/json.hpp>
34#include <boost/date_time/posix_time/posix_time.hpp>
35#include <daq/slc/base/ConfigFile.h>
36#include <daq/slc/psql/PostgreSQLInterface.h>
37#include <daq/slc/database/DBHandlerException.h>
38#include <daq/slc/base/StringUtil.h>
43using namespace RootIOUtilities;
55 m_eventLow(0), m_experimentHigh(0), m_runHigh(0), m_eventHigh(0)
58 setDescription(
"Writes DataStore objects into a .root file. Data is stored in a TTree 'tree' for event-dependent and in 'persistent' for peristent data. You can use RootInput to read the files back into basf2.");
62 addParam(
"outputFileName", m_outputFileName,
"Name of the output file. Can be overridden using the -o argument to basf2.",
63 string(
"RootOutput.root"));
64 addParam(
"ignoreCommandLineOverride", m_ignoreCommandLineOverride,
65 "Ignore override of file name via command line argument -o. Useful if you have multiple output modules in one path.",
false);
66 addParam(
"compressionLevel", m_compressionLevel,
67 "0 for no, 1 for low, 9 for high compression. Level 1 usually reduces size by >50%, higher levels have no noticeable effect. On typical hard disks, disabling compression reduces write time by 10-20 %, but almost doubles read time, so you probably should leave this turned on.",
69 addParam(
"compressionAlgorithm", m_compressionAlgorithm,
70 "Set the Compression algorithm. Recommended values are 0 for default, 1 for zlib and 4 for lz4\n\n"
71 ".. versionadded:: release-03-00-00", m_compressionAlgorithm);
72 addParam(
"splitLevel", m_splitLevel,
73 "Branch split level: determines up to which depth object members will be saved in separate sub-branches in the tree. For arrays or objects with custom streamers, -1 is used instead to ensure the streamers are used. The default (99) usually gives the highest read performance with RootInput.",
75 addParam(
"updateFileCatalog", m_updateFileCatalog, R
"DOC(
76Flag that specifies whether the file metadata catalog is updated or created.
77This is only necessary in special cases and can always be done afterwards using
78``b2file-catalog-add filename.root``"
80(You can also set the ``BELLE2_FILECATALOG`` environment variable to NONE to get
81the same effect as setting this to false))DOC", false);
83 vector<string> emptyvector;
85 "Names of event durability branches to be saved. Empty means all branches. Objects with c_DontWriteOut flag added here will also be saved. (EventMetaData is always saved)",
88 "Names of persistent durability branches to be saved. Empty means all branches. Objects with c_DontWriteOut flag added here will also be saved. (FileMetaData is always saved)",
91 "Add additional event branch names without the need to specify all branchnames.",
94 "Add additional persistent branch names without the need to specify all branchnames.",
97 "Names of event durability branches NOT to be saved. Branches also in branchNames are not saved.", emptyvector);
99 "Names of persistent durability branches NOT to be saved. Branches also in branchNamesPersistent are not saved.", emptyvector);
100 addParam(
"autoFlushSize", m_autoflush,
101 "Value for TTree SetAutoFlush(): a positive value tells ROOT to flush all baskets to disk after n entries, a negative value to flush after -n bytes",
103 addParam(
"autoSaveSize", m_autosave,
104 "Value for TTree SetAutoSave(): a positive value tells ROOT to write the TTree metadata after n entries, a negative value to write the metadata after -n bytes",
106 addParam(
"basketSize", m_basketsize,
"Basketsize for Branches in the Tree in bytes", 32000);
107 addParam(
"additionalDataDescription", m_additionalDataDescription,
"Additional dictionary of "
108 "name->value pairs to be added to the file metadata to describe the data",
109 m_additionalDataDescription);
110 addParam(
"buildIndex", m_buildIndex,
"Build Event Index for faster finding of events by exp/run/event number", m_buildIndex);
111 addParam(
"keepParents", m_keepParents,
"Keep parents files of input files, input files will not be added as output file's parents",
113 addParam(
"outputSplitSize", m_outputSplitSize, R
"DOC(
114If given split the output file once the file has reached the given size in MB.
115If set the filename will end in ``.f{index:05d}.root``. So if for example
116``outputFileName`` is set to "RootOutput.root" then the files will be named
117``RootOutput.f00000.root``, ``RootOutput.f00001.root``,
118``RootOutput.f00002.root``, ...
120All created output files are complete and independent files and can
121subsequently processed completely independent.
124 The output files will be approximately of the size given by
125 ``outputSplitSize`` but they will be slightly larger since
126 additional information has to be written at the end of the file. If necessary
127 please account for this. Also, using ``buildIndex=False`` might be beneficial
128 to reduce the overshoot.
131 This will set the amount of generated events stored in the file metadata to
132 zero as it is not possible to determine which fraction ends up in which
135.. versionadded:: release-03-00-00
136)DOC", m_outputSplitSize);
141 addParam(
"runType", m_runType,
"Run type",
string(
"null"));
142 addParam(
"HLTName", m_HLTName,
"HLT name",
string(
"HLT00"));
143 addParam(
"nDisk", m_nDisk,
"The number of paratitions", 3);
144 addParam(
"skipFirstEvent", m_firstEvent,
"Boolean to skip the first event or not. "
145 "If the module is used inside the hbasf2, like HLT storage, the first event need to be skipped.", m_firstEvent);
146 addParam(
"ramdiskBuffer", m_ramdiskBuffer,
"Boolean to make small ramdisk buffer setup. "
147 "If this is false, assuming the buffer disks are large SSD.", m_ramdiskBuffer);
160 TTree::SetMaxTreeSize(1000 * 1000 * 100000000000LL);
167 if (*
m_outputSplitSize == 0) B2ERROR(
"outputSplitSize must be set to a positive value");
177 std::regex protocol(
"^([A-Za-z]*)://");
193 config.get(
"database.dbname"),
194 config.get(
"database.user"),
195 config.get(
"database.password"),
196 config.getInt(
"database.port"));
215 TDirectory* dir = gDirectory;
224 std::filesystem::path file{fileUrl.GetFile()};
225 file.replace_extension((boost::format(
"f%05d.root") %
m_fileIndex).str());
226 fileUrl.SetFile(file.c_str());
228 out =
m_regularFile? fileUrl.GetFileAndOptions() : fileUrl.GetUrl();
232 std::filesystem::path out_notmp = out;
233 out = std::filesystem::path{std::string(
"/buffer") + out.generic_string()};
235 m_file = TFile::Open(out.c_str(),
"RECREATE",
"basf2 Event File");
238 auto dirpath = out.parent_path();
240 if (std::filesystem::create_directories(dirpath)) {
241 B2INFO(
"Created missing directory " << dirpath <<
".");
243 m_file = TFile::Open(out.c_str(),
"RECREATE",
"basf2 Event File");
251 m_file = TFile::Open(out.c_str(),
"RECREATE",
"basf2 Event File");
252 B2INFO(
"process(" << m_processNumber <<
"), Try open: " << ++openCounter);
256 B2FATAL(
"Couldn't open file " << out <<
" for writing!");
263 set<string> branchList;
264 for (
const auto& pair : map)
265 branchList.insert(pair.first);
273 for (
auto & iter : map) {
274 const std::string& branchName = iter.first;
276 if (iter.second.dontWriteOut
282 if (branchList.count(branchName) == 0) {
292 (branchName !=
"FileMetaData" and branchName !=
"ProcessStatistics")) {
293 B2WARNING(
"Persistent branches might not be stored as expected when splitting the output by size" <<
LogVar(
"branch", branchName));
296 TClass* entryClass = iter.second.objClass;
305 if (!entryClass->HasDictionary()) {
307 B2WARNING(
"No dictionary found, object will not be saved (This is probably an obsolete class that is still present in the input file.)"
308 <<
LogVar(
"class", entryClass->GetName()) <<
LogVar(
"branch", branchName));
314 B2ERROR(
"The version number in the ClassDef() macro must be at least 1 to enable I/O!" <<
LogVar(
"class", entryClass->GetName()));
319 B2DEBUG(38,
"Class has custom streamer, setting split level -1 for this branch." <<
LogVar(
"class", entryClass->GetName()));
322 if (iter.second.isArray) {
324 static_cast<TClonesArray*
>(iter.second.object)->BypassStreamer(kFALSE);
327 m_tree[durability]->Branch(branchName.c_str(), &iter.second.object,
m_basketsize, splitLevel);
328 m_entries[durability].push_back(&iter.second);
329 B2DEBUG(39,
"The branch " << branchName <<
" was created.");
334 iter.second.isArray));
341 if (fileMetaDataBranch) {
349 B2INFO(
getName() <<
": Opened " << (
m_fileIndex > 0 ?
"new " :
"") <<
"file for writing" <<
LogVar(
"filename", out));
355 m_db->execute(
"INSERT INTO datafiles_root "
356 "(name, path, host, disk, runtype, expno, runno, compression_level, compression_algorithm, time_open, "
357 "size, nevents, nfullevents, correct_close, renamed, used_for_merge, removed) "
358 "VALUES ('%s', '%s', '%s', '%s','%s', %d, %d, %d, %d, '%s', 0, 0, 0, FALSE, FALSE, FALSE, FALSE);",
359 out_notmp.filename().c_str(), out_notmp.c_str(), m_HLTName.c_str(), m_disk.c_str(),
360 m_runType.c_str(),
m_expno, m_runno,
362 (boost::posix_time::to_iso_extended_string(boost::posix_time::microsec_clock::local_time())+std::string(
"+09")).c_str());
374 m_firstEvent =
false;
397 m_processNumber = atoi(
getName().substr(0,
getName().find(std::string(
"_"))).c_str());
398 m_disk = StringUtil::form(
"disk%02d", (m_processNumber%m_nDisk)+1);
399 m_outputFileName = StringUtil::form(
"/rawdata/%s/belle/Raw/%4.4d/%5.5d/%s.%4.4d.%5.5d.%s.p%02d.root",
400 m_disk.c_str(),
m_expno, m_runno, m_runType.c_str(),
401 m_expno, m_runno, m_HLTName.c_str(), m_processNumber);
418 for (
int iparent = 0; iparent <
m_fileMetaData->getNParents(); iparent++) {
462 B2INFO(
getName() <<
": Output size limit reached, closing file ...");
483 unsigned long numEntries = tree->GetEntries();
486 if (numEntries > 10000000) {
488 B2WARNING(
"Not building TTree index because of large number of events. The index object would conflict with ROOT limits on object size and cause problems.");
489 }
else if (tree->GetBranch(
"EventMetaData")) {
490 tree->SetBranchAddress(
"EventMetaData",
nullptr);
513 if(
m_fileIndex == 0) B2WARNING(
"Number of MC Events cannot be saved when splitting output files by size, setting to 0");
522 std::string lfn =
m_file->GetName();
524 lfn = std::filesystem::absolute(lfn).string();
528 if (!format.empty()) {
529 auto format_filename = boost::python::import(
"B2Tools.format").attr(
"format_filename");
557 TDirectory* dir = gDirectory;
561 B2DEBUG(30,
"Write TTree " <<
c_treeNames[durability]);
562 m_tree[durability]->Write(
c_treeNames[durability].c_str(), TObject::kWriteDelete);
563 delete m_tree[durability];
565 m_tree[durability] =
nullptr;
569 const std::string filename =
m_file->GetName();
571 B2INFO(
getName() <<
": Finished writing file." <<
LogVar(
"filename", filename));
575 const std::filesystem::path filename_path{filename};
576 std::string filename_notmp =
m_file->GetName();
577 filename_notmp.erase(0, 7);
578 const std::filesystem::path filename_notmp_path{filename_notmp};
581 m_db->execute(
"UPDATE datafiles_root SET "
582 "correct_close = TRUE, "
585 "nfullevents = %lu, "
588 "WHERE name = '%s' AND host = '%s';",
591 (boost::posix_time::to_iso_extended_string(boost::posix_time::microsec_clock::local_time())+std::string(
"+09")).c_str(),
592 filename_path.filename().c_str(), m_HLTName.c_str());
619 if (m_ramdiskBuffer) {
620 const std::string rsync_cmd = std::string(
"/usr/bin/rsync -a --remove-source-files --recursive ") + filename + std::string(
" ") + filename_notmp_path.parent_path().generic_string() + std::string(
"/ &");
621 B2INFO(
getName() <<
": system(" << rsync_cmd <<
")");
622 system(rsync_cmd.c_str());
629 if (!
m_tree[durability])
return;
631 TTree& tree = *
m_tree[durability];
632 for(
auto* entry:
m_entries[durability]) {
636 entry->object->SetBit(kInvalidObject);
639 if (entry->name ==
"FileMetaData") {
642 tree.SetBranchAddress(entry->name.c_str(), &entry->object);
646 for (
auto* entry:
m_entries[durability]) {
647 entry->object->ResetBit(kInvalidObject);
650 const bool writeError =
m_file->TestBit(TFile::kWriteError);
653 const std::string filename =
m_file->GetName();
655 B2FATAL(
"A write error occured while saving '" << filename <<
"', please check if enough disk space is available.");
StoreEntryMap & getStoreEntryMap(EDurability durability)
Get a reference to the object/array map.
static const int c_NDurabilityTypes
Number of Durability Types.
EDurability
Durability types.
@ c_Persistent
Object is available during entire execution time.
@ c_Event
Different object in each event, all objects/arrays are invalidated after event() function has been ca...
static DataStore & Instance()
Instance of singleton Store.
bool optionalInput(const StoreAccessorBase &accessor)
Register the given object/array as an optional input.
std::map< std::string, StoreEntry > StoreEntryMap
Map for StoreEntries.
unsigned int getNumberOfMCEvents() const
Number of generated events (from EventInfoSetter).
static Environment & Instance()
Static method to get a reference to the Environment instance.
static FileCatalog & Instance()
Static method to get a reference to the FileCatalog instance.
virtual bool registerFile(const std::string &fileName, FileMetaData &metaData, const std::string &oldLFN="")
Register a file in the (local) file catalog.
const std::string & getName() const
Returns the name of the module.
static std::string getSeed()
Get the random number generator seed.
Write objects from DataStore into a ROOT file.
unsigned long m_experimentLow
Lowest experiment number.
int m_expno
Variables for online storage.
std::vector< DataStore::StoreEntry * > m_entries[DataStore::c_NDurabilityTypes]
Vector of DataStore entries that are written to the output.
unsigned long m_experimentHigh
Highest experiment number.
unsigned long m_eventLow
Lowest event number in lowest run.
void fillFileMetaData()
Create and fill FileMetaData object.
int m_autosave
Number of entries (if >0) or number of bytes (if <0) after which write the tree metadata to disk.
bool m_regularFile
Whether this is a regular, local file where we can actually create directories.
unsigned long m_runLow
Lowest run number.
int m_compressionAlgorithm
TFile compression algorithm.
virtual void event() override
Write data in c_Event DataStore maps.
bool m_buildIndex
Whether or not we want to build an event index.
bool m_keepParents
Whether to keep parents same as that of input file.
virtual void endRun() override
Issued by the lastEventMessage = DAQ STOP.
virtual ~StorageRootOutputModule()
Destructor.
virtual void terminate() override
Write data in the c_Persistent DataStore maps.
TTree * m_tree[DataStore::c_NDurabilityTypes]
TTree for output.
unsigned int m_nFullEvents
Number of full events (aka number of events without an error flag)
unsigned long m_runHigh
Highest run number.
StoreObjPtr< EventMetaData > m_eventMetaData
Pointer to the event meta data.
std::vector< std::string > m_excludeBranchNames[DataStore::c_NDurabilityTypes]
Array for names of branches that should NOT be written out.
int m_basketsize
basket size for each branch in the file in bytes
std::vector< std::string > m_additionalBranchNames[DataStore::c_NDurabilityTypes]
Array of names of branches that should be written out although they are not flagged for writeout.
virtual void initialize() override
Setting up of various stuff.
FileMetaData * m_outputFileMetaData
File meta data stored in the output file.
TFile * m_file
TFile for output.
int m_fileIndex
Keep track of the file index: if we split files than we add '.f{fileIndex:05d}' in front of the ROOT ...
void fillTree(DataStore::EDurability durability)
Fill TTree.
void closeFile()
Finalize the output file.
std::optional< uint64_t > m_outputSplitSize
Maximum output file size in MB.
int m_compressionLevel
TFile compression level.
int m_autoflush
Number of entries (if >0) or number of bytes (if <0) after which to flush all baskets to disk.
bool m_updateFileCatalog
Flag to enable or disable the update of the metadata catalog.
int m_splitLevel
Branch split level.
void openFile()
Open the next output file.
unsigned long m_eventHigh
Highest event number in highest run.
std::map< std::string, std::string > m_additionalDataDescription
Map of additional metadata to be added to the output file.
std::vector< std::string > m_parentLfns
Vector of parent file LFNs.
std::vector< std::string > m_branchNames[DataStore::c_NDurabilityTypes]
Array for names of branches that should be written out.
virtual std::vector< std::string > getFileNames(bool outputFiles=true) override
Set the used output file, taking into account -o argument to basf2.
StoreObjPtr< FileMetaData > m_fileMetaData
Pointer to the input file meta data.
std::string m_outputFileName
Name for output file.
Base class for StoreObjPtr and StoreArray for easier common treatment.
Class to store variables with their name which were sent to the logging service.
static std::string get(const std::string &name, const std::string &fallback="")
Get the value of an environment variable or the given fallback value if the variable is not set.
static Database & Instance()
Instance of a singleton Database.
#define REG_MODULE(moduleName)
Register the given module (without 'Module' suffix) with the framework.
@ c_Output
Output Process.
bool hasCustomStreamer(const TClass *cl)
Returns true if and only if 'cl' has a user-defined streamer.
const std::string c_treeNames[]
Names of trees.
const std::string c_SteerExcludeBranchNames[]
Steering parameter names for m_excludeBranchNames.
const std::string c_SteerBranchNames[]
Steering parameter names for m_branchNames.
void setCreationData(FileMetaData &metadata)
Fill the creation info of a file meta data: site, user, data.
std::set< std::string > filterBranches(const std::set< std::string > &branchesToFilter, const std::vector< std::string > &branches, const std::vector< std::string > &excludeBranches, int durability, bool quiet=false)
Given a list of input branches and lists of branches to include/exclude, returns a list of branches t...
const std::string c_SteerAdditionalBranchNames[]
Steering parameter names for m_additionalBranchNames.
void buildIndex(TTree *tree)
Build TTreeIndex on tree (assumes EventMetaData branch exists there).
bool hasStreamer(const TClass *cl)
Returns true if and only if 'cl' or one of its bases has I/O streamers.
Abstract base class for different kinds of events.