Belle II Software development
pEventProcessor.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/pcore/pEventProcessor.h>
10#include <framework/pcore/ProcHandler.h>
11#include <framework/pcore/RingBuffer.h>
12#include <framework/pcore/RxModule.h>
13#include <framework/pcore/TxModule.h>
14#include <framework/pcore/DataStoreStreamer.h>
15#include <framework/pcore/RbTuple.h>
16#include <framework/pcore/PathUtils.h>
17
18#include <framework/core/ModuleManager.h>
19#include <framework/core/Environment.h>
20#include <framework/logging/LogSystem.h>
21
22#include <TROOT.h>
23
24#include <csignal>
25#include <memory>
26
27
28using namespace std;
29using namespace Belle2;
30
31namespace {
32 static int gSignalReceived = 0;
33
34 static pEventProcessor* g_pEventProcessor = nullptr;
35
36 void cleanupIPC()
37 {
38 if (g_pEventProcessor)
39 g_pEventProcessor->cleanup();
40 }
41 void cleanupAndStop(int sig)
42 {
43 cleanupIPC();
44
45 //uninstall current handler and call default one.
46 signal(sig, SIG_DFL);
47 raise(sig);
48 }
49
50 static void parentSignalHandler(int signal)
51 {
52 //signal handlers are called asynchronously, making many standard functions (including output) dangerous
53 if (signal == SIGINT) {
54 g_pEventProcessor->gotSigINT();
55 } else if (signal == SIGTERM or signal == SIGQUIT) {
56 g_pEventProcessor->killRingBuffers();
57 }
58 if (gSignalReceived == 0)
59 gSignalReceived = signal;
60 }
61}
62
64 m_histoman(nullptr)
65{
66 g_pEventProcessor = this;
67}
68
69
71{
72 cleanup();
73 g_pEventProcessor = nullptr;
74}
75
77{
79 delete m_rbin;
80 m_rbin = nullptr;
81 delete m_rbout;
82 m_rbout = nullptr;
83 }
84}
85
86
88{
89 EventProcessor::writeToStdErr("\nStopping basf2...\n");
91}
92
94{
95 m_rbin->kill();
96 //these might be locked by _this_ process, so we cannot escape
97 m_rbout->kill(); //atomic, so doesn't lock
98}
99
101{
102 //B2WARNING("list of files: " << gROOT->GetListOfFiles()->GetEntries());
103 //clear list, but don't actually delete the objects
104 gROOT->GetListOfFiles()->Clear("nodelete");
105}
106
107
108void pEventProcessor::process(const PathPtr& spath, long maxEvent)
109{
110 if (spath->getModules().size() == 0) return;
111
112 const int numProcesses = Environment::Instance().getNumberProcesses();
113
114 //Check whether the number of events was set via command line argument
115 unsigned int numEventsArgument = Environment::Instance().getNumberEventsOverride();
116 if ((numEventsArgument > 0) && ((maxEvent == 0) || (maxEvent > numEventsArgument))) {
117 maxEvent = numEventsArgument;
118 }
119
120 if (numProcesses == 0)
121 B2FATAL("pEventProcessor::process() called for serial processing! Most likely a bug in Framework.");
122
123 // 1. Analyze start path and split into parallel paths
124 analyzePath(spath);
125
126
127 if (m_inputPath) {
128 B2INFO("Input Path " << m_inputPath->getPathString());
129 }
130 if (m_mainPath) {
131 if (m_mainPath->getModules().size() <= 5) {
132 B2INFO("Main Path " << m_mainPath->getPathString());
133 } else {
134 B2INFO("Main Path [" << m_mainPath->getModules().front()->getName() << " -> ... (" << m_mainPath->getModules().size() - 2 <<
135 " further modules) ... -> " << m_mainPath->getModules().back()->getName() << " ]");
136 }
137 }
138 if (m_outputPath) {
139 B2INFO("Output Path " << m_outputPath->getPathString());
140 }
141 if (not m_mainPath) {
142 B2WARNING("Cannot run any modules in parallel (no c_ParallelProcessingCertified flag), falling back to single-core mode.");
143 EventProcessor::process(spath, maxEvent);
144 return;
145 }
146
147 installMainSignalHandlers(cleanupAndStop);
148
149 //inserts Rx/Tx modules into path (sets up IPC structures)
150 preparePaths();
151
152 // ensure that we free the IPC resources!
153 atexit(cleanupIPC);
154
155
156 //init statistics
157 {
158 m_processStatisticsPtr.registerInDataStore();
160 m_processStatisticsPtr.create();
161 Path mergedPath;
162 if (m_inputPath)
163 mergedPath.addPath(m_inputPath);
164 mergedPath.addPath(m_mainPath);
165 if (m_outputPath)
166 mergedPath.addPath(m_outputPath);
167 for (const ModulePtr& module : mergedPath.buildModulePathList())
168 m_processStatisticsPtr->initModule(module.get());
169 }
170
171 // 2. Initialization
172 ModulePtrList modulelist = spath->buildModulePathList();
174 //dump_modules("Initializing globally: ", initGlobally);
175 processInitialize(initGlobally);
176
178
179 //Don't start processing in case of no master module
180 if (!m_master) {
181 B2ERROR("There is no module that provides event and run numbers. You must either add the EventInfoSetter module to your path, or, if using an input module, read EventMetaData objects from file.");
182 }
183
184 //Check if errors appeared. If yes, don't start the event processing.
186 if (numLogError != 0) {
187 B2FATAL(numLogError << " ERROR(S) occurred! The processing of events will not be started.");
188 }
189
190 //disable ROOT's management of TFiles
192
193
194 //install new signal handlers before forking
195 installMainSignalHandlers(parentSignalHandler);
196
197 //Path for current process
198 PathPtr localPath;
199
200 m_procHandler = std::make_unique<ProcHandler>(numProcesses);
201
202 // 3. Fork input path
203 m_procHandler->startInputProcess();
204 if (m_procHandler->isInputProcess()) { // In input process
205 localPath = m_inputPath;
206 } else {
207 // This is not the input path, clean up datastore to not contain the first event
209 }
210
211 if (localPath == nullptr) { //not forked yet
212 // 5. Fork out worker path (parallel section)
213 m_procHandler->startWorkerProcesses();
214 if (m_procHandler->isWorkerProcess()) {
215 localPath = m_mainPath;
216 m_master = localPath->getModules().begin()->get(); //set Rx as master
217 }
218 }
219
220 if (localPath == nullptr) { //not forked yet -> this process is the output process
221 m_procHandler->startOutputProcess();
222 if (m_outputPath) {
223 localPath = m_outputPath;
224 m_master = localPath->getModules().begin()->get(); //set Rx as master
225 }
226 }
227
228
229 if (!m_procHandler->isOutputProcess()) {
231 }
232
233 bool gotSigINT = false;
234 if (localPath != nullptr) {
235 ModulePtrList localModules = localPath->buildModulePathList();
236 ModulePtrList procinitmodules = getModulesWithFlag(localModules, Module::c_InternalSerializer);
237 //dump_modules("processInitialize for ", procinitmodules);
238 processInitialize(procinitmodules);
239
240 //input: handle signals normally, will slowly cascade down
241 if (m_procHandler->isInputProcess())
243 //workers will have to ignore the signals, there's no good way to do this safely
244 if (m_procHandler->isWorkerProcess())
246
247 try {
248 processCore(localPath, localModules, maxEvent, m_procHandler->isInputProcess());
249 } catch (StoppedBySignalException& e) {
250 if (e.signal != SIGINT) {
251 B2FATAL(e.what());
252 }
253 //in case of SIGINT, we move on to processTerminate() to shut down safely
254 gotSigINT = true;
255 }
256 prependModulesIfNotPresent(&localModules, terminateGlobally);
257 processTerminate(localModules);
258 }
259
260 B2INFO(m_procHandler->getProcessName() << " process finished.");
261
262 //all processes except output stop here
263 if (!m_procHandler->isOutputProcess()) {
264 if (gotSigINT) {
265 installSignalHandler(SIGINT, SIG_DFL);
266 raise(SIGINT);
267 } else {
268 exit(0);
269 }
270 }
271
272 //output process: do final cleanup
273 m_procHandler->waitForAllProcesses();
274 B2INFO("All processes completed");
275
276 //finished, disable handler again
277 installSignalHandler(SIGINT, SIG_IGN);
278
279 cleanup();
280 B2INFO("Global process: completed");
281
282 if (m_histoman) {
283 B2INFO("HistoManager:: adding histogram files");
285 }
286
287 //did anything bad happen?
288 if (gSignalReceived) {
289 B2ERROR("Processing aborted via signal " << gSignalReceived <<
290 ", terminating. Output files have been closed safely and should be readable.");
291 installSignalHandler(gSignalReceived, SIG_DFL);
292 raise(gSignalReceived);
293 }
294
295}
296
298{
299 //NOTE: PathUtils::splitPath() is a copy of this function, used by the ZMQ processor. The two
300 //share PathUtils::isWorthParallelising() but nothing else; keep them in sync.
301
302 PathPtr inpath(new Path);
303 PathPtr mainpath(new Path);
304 PathPtr outpath(new Path);
305
306 // only collected here, and added below once the splitting is done: the merge-back
307 // discards and restarts the main path, taking anything put on it along
308 ModulePtrList histogramManagers;
309
310 int stage = 0; //0: in, 1: event/main, 2: out
311 for (const ModulePtr& module : path->getModules()) {
312 bool hasParallelFlag = module->hasProperties(Module::c_ParallelProcessingCertified);
313 // entire conditional path must also be compatible
314 if (hasParallelFlag and module->hasCondition()) {
315 for (const auto& conditionPath : module->getAllConditionPaths()) {
317 hasParallelFlag = false;
318 }
319 }
320 }
321
322 // update stage?
323 if ((stage == 0 and hasParallelFlag) or (stage == 1 and !hasParallelFlag)) {
324 stage++;
325
326 if (stage == 2) {
327 if (not PathUtils::isWorthParallelising(*mainpath)) {
328 // merge mainpath back into input path
329 inpath->addPath(mainpath);
330 mainpath.reset(new Path);
331 // and search for further parallel sections
332 stage = 0;
333 }
334 }
335 }
336
337 if (stage == 0) { //fill input path
338 inpath->addModule(module);
339
340 if (module->hasProperties(Module::c_HistogramManager)) {
341 // Initialize histogram manager if found in the path
342 m_histoman = module;
343 histogramManagers.push_back(module);
344 }
345 }
346
347 if (stage == 1)
348 mainpath->addModule(module);
349 if (stage == 2)
350 outpath->addModule(module);
351 }
352
353 // the histogram manager has to run in every process
354 PathUtils::prependModules(mainpath, histogramManagers);
355 PathUtils::prependModules(outpath, histogramManagers);
356
357 bool createAllPaths = false; // usually we might not need e.g. an output path
358 for (const ModulePtr& module : path->getModules()) {
359 if (module->hasProperties(Module::c_TerminateInAllProcesses))
360 createAllPaths = true; // ensure there are all kinds of processes
361 }
362
363 // if main path is empty, createAllPaths doesn't really matter, since we'll fall back to single-core processing
364 if (!mainpath->isEmpty())
365 m_mainPath = mainpath;
366 if (createAllPaths or !inpath->isEmpty())
367 m_inputPath = inpath;
368 if (createAllPaths or !outpath->isEmpty())
369 m_outputPath = outpath;
370}
371
373{
374 //create ringbuffers and add rx/tx where needed
375 const char* inrbname = getenv(name);
376 RingBuffer* rbuf;
377 if (inrbname == nullptr) {
378 rbuf = new RingBuffer();
379 } else {
380 string rbname(inrbname + to_string(0)); //currently at most one input, one output buffer
381 rbuf = new RingBuffer(rbname.c_str(), RingBuffer::c_DefaultSize);
382 }
383
384 // Insert Tx at the end of current path
385 ModulePtr txptr(new TxModule(rbuf));
386 a->addModule(txptr);
387 // Insert Rx at beginning of next path
388 ModulePtr rxptr(new RxModule(rbuf));
389 PathPtr newB(new Path());
390 newB->addModule(rxptr);
391 newB->addPath(b);
392 b.swap(newB);
393
394 return rbuf;
395}
396
398{
399 if (m_histoman) {
400 m_histoman->initialize();
401 }
402 if (not m_mainPath)
403 return; //we'll fall back to single-core
404
405 if (m_inputPath)
407 if (m_outputPath)
409}
410
411
412void pEventProcessor::dump_modules(const std::string& title, const ModulePtrList& modlist)
413{
414 ModulePtrList::const_iterator it;
415 std::ostringstream strbuf;
416 strbuf << title << " : ";
417 for (it = modlist.begin(); it != modlist.end(); ++it) {
418 const Module* module = it->get();
419 strbuf << module->getName();
420 if (module->hasCondition()) {
421 for (const auto& conditionPath : module->getAllConditionPaths()) {
422 strbuf << "[->" << conditionPath.get() << "] ";
423 }
424 }
425 if (*it != modlist.back())
426 strbuf << " -> ";
427 }
428 B2INFO(strbuf.str());
429}
430
431
433{
434 ModulePtrList tmpModuleList;
435 for (const ModulePtr& m : modules) {
436 if (m->hasProperties(flag))
437 tmpModuleList.push_back(m);
438 }
439
440 return tmpModuleList;
441}
443{
444 ModulePtrList tmpModuleList;
445 for (const ModulePtr& m : modules) {
446 if (!m->hasProperties(flag))
447 tmpModuleList.push_back(m);
448 }
449 return tmpModuleList;
450}
451
453{
454 for (const ModulePtr& m : prependModules) {
455 if (std::find(modules->begin(), modules->end(), m) == modules->end()) { //not present
456 modules->push_front(m);
457 }
458 }
459}
static void removeSideEffects()
call clear() and removeSideEffects() for all Mergeable objects in datastore (for c_Persistent durabil...
@ c_Event
Different object in each event, all objects/arrays are invalidated after event() function has been ca...
Definition DataStore.h:59
static DataStore & Instance()
Instance of singleton Store.
Definition DataStore.cc:53
void invalidateData(EDurability durability)
Clears all registered StoreEntry objects of a specified durability, invalidating all objects.
Definition DataStore.cc:713
int getNumberProcesses() const
Returns the number of worker processes which should be used for the parallel processing.
static Environment & Instance()
Static method to get a reference to the Environment instance.
unsigned int getNumberEventsOverride() const
Returns number of events in run 1 for EventInfoSetter module, or 0 for no override.
Definition Environment.h:68
Exception thrown when execution is stopped by a signal.
void processInitialize(const ModulePtrList &modulePathList, bool setEventInfo=true)
Initializes the modules.
void processCore(const PathPtr &startPath, const ModulePtrList &modulePathList, long maxEvent=0, bool isInputProcess=true)
Processes the full module chain consisting of an arbitrary number of connected paths,...
static void installSignalHandler(int sig, void(*fn)(int))
Install a signal handler 'fn' for given signal.
StoreObjPtr< ProcessStatistics > m_processStatisticsPtr
Also used in a number of places.
void process(const PathPtr &startPath, long maxEvent=0)
Processes the full module chain, starting with the first module in the given path.
void processTerminate(const ModulePtrList &modulePathList)
Terminates the modules.
static void writeToStdErr(const char msg[])
async-safe method to write something to STDERR.
const Module * m_master
The master module that determines the experiment/run/event number.
EventProcessor()
Constructor.
static void installMainSignalHandlers(void(*fn)(int)=nullptr)
Install signal handler for INT, TERM and QUIT signals.
@ c_Error
Error: for things that went wrong and have to be fixed.
Definition LogConfig.h:30
int getMessageCounter(LogConfig::ELogLevel logLevel) const
Returns the number of logging calls per log level.
Definition LogSystem.cc:158
static LogSystem & Instance()
Static method to get a reference to the LogSystem instance.
Definition LogSystem.cc:28
static bool allModulesHaveFlag(const std::list< std::shared_ptr< Module > > &list, unsigned int flag)
Returns true if and only if all modules in list have the given flag (or list is empty).
Base class for Modules.
Definition Module.h:72
EModulePropFlags
Each module can be tagged with property flags, which indicate certain features of the module.
Definition Module.h:77
@ c_HistogramManager
This module is used to manage histograms accumulated by other modules.
Definition Module.h:81
@ c_ParallelProcessingCertified
This module can be run in parallel processing mode safely (All I/O must be done through the data stor...
Definition Module.h:80
@ c_InternalSerializer
This module is an internal serializer/deserializer for parallel processing.
Definition Module.h:82
@ c_TerminateInAllProcesses
When using parallel processing, call this module's terminate() function in all processes().
Definition Module.h:83
static void prependModules(PathPtr &path, const ModulePtrList &modules)
Prepend the given modules to the path, keeping their order.
Definition PathUtils.cc:216
static bool isWorthParallelising(const Path &path)
Is a parallel section made up of these modules worth creating processes for?
Definition PathUtils.cc:16
Implements a path consisting of Module and/or Path objects.
Definition Path.h:38
std::list< std::shared_ptr< Module > > buildModulePathList(bool unique=true) const
Builds a list of all modules which could be executed during the data processing.
Definition Path.cc:67
void addPath(const PathPtr &path)
See 'pydoc3 basf2.Path'.
Definition Path.cc:37
void addModule(const std::shared_ptr< Module > &module)
Adds a module to the path.
Definition Path.cc:32
bool isEmpty() const
Returns true if this Path doesn't contain any elements.
Definition Path.cc:45
std::list< std::shared_ptr< Module > > getModules() const override
Returns a list of the modules in this path.
Definition Path.cc:50
static bool isOutputProcess()
Return true if the process is an output process.
static bool parallelProcessingUsed()
Returns true if multiple processes have been spawned, false in single-core mode.
static RbTupleManager & Instance()
Access to singleton.
Definition RbTuple.cc:38
int hadd(bool deleteflag=true)
Functions to add up all histogram files.
Definition RbTuple.cc:136
Class to manage a Ring Buffer placed in an IPC shared memory.
Definition RingBuffer.h:39
static const int c_DefaultSize
Standard size of buffer, in integers (~60MB).
Definition RingBuffer.h:42
Module to decode data store contents from RingBuffer.
Definition RxModule.h:27
Module for encoding data store contents into a RingBuffer.
Definition TxModule.h:25
This class provides the core event processing loop for parallel processing.
void preparePaths()
Adds internal modules to paths, prepare RingBuffers.
void dump_modules(const std::string &, const ModulePtrList &)
Dump module names in the ModulePtrList.
PathPtr m_outputPath
Output path.
static ModulePtrList getModulesWithFlag(const ModulePtrList &modules, Module::EModulePropFlags flag)
Return only modules which have the given Module flag set.
RingBuffer * m_rbin
input RingBuffer
RingBuffer * m_rbout
output RingBuffer
std::unique_ptr< ProcHandler > m_procHandler
handler to fork and manage processes.
void cleanup()
clean up IPC resources (should only be called in one process).
void process(const PathPtr &spath, long maxEvent)
Processes the full module chain, starting with the first module in the given path.
RingBuffer * connectViaRingBuffer(const char *name, const PathPtr &a, PathPtr &b)
Create RingBuffer with name from given environment variable, add Tx and Rx modules to a and b.
ModulePtr m_histoman
Pointer to HistoManagerModule, or nullptr if not found.
void analyzePath(const PathPtr &path)
Analyze given path.
virtual ~pEventProcessor() override
Destructor.
void gotSigINT()
signal handler for Ctrl+C (async-safe)
static void prependModulesIfNotPresent(ModulePtrList *modules, const ModulePtrList &prependModules)
Prepend given 'prependModules' to 'modules', if they're not already present.
PathPtr m_mainPath
Main (parallel section) path.
static ModulePtrList getModulesWithoutFlag(const ModulePtrList &modules, Module::EModulePropFlags flag)
Return only modules which do not have the given Module flag set.
PathPtr m_inputPath
Input path.
void killRingBuffers()
signal handler (async-safe)
static void clearFileList()
TFiles are stored in a global list and cleaned up by root since this will happen in all forked proces...
std::shared_ptr< Path > PathPtr
Defines a pointer to a path object as a boost shared pointer.
Definition Path.h:35
std::shared_ptr< Module > ModulePtr
Defines a pointer to a module object as a boost shared pointer.
Definition Module.h:43
std::list< ModulePtr > ModulePtrList
Defines a std::list of shared module pointers.
Definition Module.h:584
Abstract base class for different kinds of events.
STL namespace.