All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
GaudiSequencer.cpp
Go to the documentation of this file.
1 // Include files
2 
3 // from Gaudi
8 
9 namespace
10 {
11 
12  // TODO: this adds C++14 'make_unique'... remove once we move to C++14...
13  template <typename T, typename... Args>
14  std::unique_ptr<T> make_unique_( Args&&... args )
15  {
16  return std::unique_ptr<T>( new T( std::forward<Args>( args )... ) );
17  }
18 
19  bool isDefault(const std::string& s) { return s.empty(); }
20 
21  // utility class to populate some properties in the job options service
22  // for a given instance name in case those options are not explicitly
23  // set a-priori (effectively inheriting their values from the GaudiSequencer)
24  class populate_JobOptionsSvc_t
25  {
27  IJobOptionsSvc* m_jos;
28  std::string m_name;
29 
30  template <typename T>
31  void process( T&& t )
32  {
33  static_assert( std::tuple_size<T>::value == 2, "Expecting an std::tuple key-value pair" );
35  using prop_t = Gaudi::Property<type>;
36  if ( !isDefault( std::get<1>( t ) ) )
37  m_props.push_back( make_unique_<prop_t>( std::get<0>( t ), std::get<1>( t ) ) );
38  }
39  template <typename T, typename... Args>
40  void process( T&& t, Args&&... args )
41  {
42  process( std::forward<T>( t ) );
43  process( std::forward<Args>( args )... );
44  }
45  void check_veto()
46  { // avoid changing properties expliclty present in the JOS...
47  const auto* props = m_jos->getProperties( m_name );
48  if ( !props ) return;
49  for ( const auto& i : *props ) {
50  auto j = std::find_if(
51  std::begin( m_props ), std::end( m_props ),
52  [&i]( const std::unique_ptr<Gaudi::Details::PropertyBase>& prop ) { return prop->name() == i->name(); } );
53  if ( j == std::end( m_props ) ) continue;
54  m_props.erase( j );
55  if ( m_props.empty() ) break; // done!
56  }
57  }
58 
59  public:
60  template <typename... Args>
61  populate_JobOptionsSvc_t( std::string name, IJobOptionsSvc* jos, Args&&... args )
62  : m_jos{jos}, m_name{std::move( name )}
63  {
64  process( std::forward<Args>( args )... );
65  if ( !m_props.empty() ) check_veto();
66  std::for_each( std::begin( m_props ), std::end( m_props ),
68  m_jos->addPropertyToCatalogue( m_name, *i ).ignore();
69  } );
70  }
71  ~populate_JobOptionsSvc_t()
72  {
73  std::for_each( std::begin( m_props ), std::end( m_props ),
75  m_jos->removePropertyFromCatalogue( m_name, i->name() ).ignore();
76  } );
77  }
78  };
79 
80  template <typename Stream, typename Container, typename Separator, typename Transform>
81  Stream& ostream_joiner( Stream& os, const Container& c, Separator sep, Transform trans )
82  {
83  auto first = std::begin( c );
84  auto last = std::end( c );
85  if ( first != last ) {
86  os << trans( *first );
87  ++first;
88  }
89  for ( ; first != last; ++first ) os << sep << trans( *first );
90  return os;
91  }
92 }
93 
94 //-----------------------------------------------------------------------------
95 // Implementation file for class : GaudiSequencer
96 //
97 // 2004-05-13 : Olivier Callot
98 //-----------------------------------------------------------------------------
99 
100 //=============================================================================
101 // Standard constructor, initializes variables
102 //=============================================================================
104  : GaudiAlgorithm( name, pSvcLocator )
105 {
106  m_names.declareUpdateHandler( &GaudiSequencer::membershipHandler, this );
107 }
108 //=============================================================================
109 // Initialisation. Check parameters
110 //=============================================================================
112 {
114 
115  if ( msgLevel( MSG::DEBUG ) ) debug() << "==> Initialise" << endmsg;
116 
117  StatusCode status = decodeNames();
118  if ( !status.isSuccess() ) return status;
119 
120  m_timerTool = tool<ISequencerTimerTool>( "SequencerTimerTool" );
121  if ( m_timerTool->globalTiming() ) m_measureTime = true;
122 
123  if ( m_measureTime ) {
126  } else {
127  release( m_timerTool );
128  m_timerTool = nullptr;
129  }
130 
131  //== Initialize the algorithms
132  for ( auto& entry : m_entries ) {
133  if ( m_measureTime ) {
134  entry.setTimer( m_timerTool->addTimer( entry.algorithm()->name() ) );
135  }
136 
137  status = entry.algorithm()->sysInitialize();
138  if ( !status.isSuccess() ) {
139  return Error( "Can not initialize " + entry.algorithm()->name(), status );
140  }
141  }
143 
144  return StatusCode::SUCCESS;
145 }
146 
147 //=============================================================================
148 // Main execution
149 //=============================================================================
151 {
152 
154 
155  if ( msgLevel( MSG::DEBUG ) ) debug() << "==> Execute" << endmsg;
156 
157  StatusCode result = StatusCode( StatusCode::SUCCESS, true );
158 
159  bool seqPass = !m_modeOR; // for OR, result will be false, unless (at least) one is true
160  // for AND, result will be true, unless (at least) one is false
161  // also see comment below ....
162 
163  for ( auto& entry : m_entries ) {
164  Algorithm* myAlg = entry.algorithm();
165  if ( ! myAlg->isEnabled() ) continue;
166  myAlg->setContext( getContext() );
167  if ( ! myAlg->isExecuted() ) {
168 
169  if ( m_measureTime ) m_timerTool->start( entry.timer() );
170  result = myAlg->sysExecute();
171  if ( m_measureTime ) m_timerTool->stop( entry.timer() );
172  myAlg->setExecuted( true );
173  if ( !result.isSuccess() ) break; //== Abort and return bad status
174  }
175  //== Check the returned status
176  if ( !m_ignoreFilter ) {
177  bool passed = myAlg->filterPassed();
178  if ( msgLevel( MSG::VERBOSE ) )
179  verbose() << "Algorithm " << myAlg->name() << " returned filter passed " << ( passed ? "true" : "false" )
180  << endmsg;
181  if ( entry.reverse() ) passed = !passed;
182 
183  //== indicate our own result. For OR, exit as soon as true.
184  // If no more, will exit with false.
185  //== for AND, exit as soon as false. Else, will be true (default)
186 
187  // if not short-circuiting, make sure we latch iPass to 'true' in
188  // OR mode (i.e. it is sufficient for one item to be true in order
189  // to be true at the end, and thus we start out at 'false'), and latch
190  // to 'false' in AND mode (i.e. it is sufficient for one item to
191  // be false to the false in the end, and thus we start out at 'true')
192  // -- i.e. we should not just blindly return the 'last' passed status!
193 
194  // or to put it another way: in OR mode, we don't care about things
195  // which are false, as they leave our current state alone (provided
196  // we stared as 'false'!), and in AND mode, we keep our current
197  // state until someone returns 'false' (provided we started as 'true')
198  if ( m_modeOR ? passed : !passed ) {
199  seqPass = passed;
200  if ( msgLevel( MSG::VERBOSE ) ) verbose() << "SeqPass is now " << ( seqPass ? "true" : "false" ) << endmsg;
201  if ( m_shortCircuit ) break;
202  }
203  }
204  }
205  if ( msgLevel( MSG::VERBOSE ) ) verbose() << "SeqPass is " << ( seqPass ? "true" : "false" ) << endmsg;
206  if ( !m_ignoreFilter && !m_entries.empty() ) setFilterPassed( seqPass );
207  setExecuted( true );
208 
210 
211  return m_returnOK ? ( result.ignore(), StatusCode::SUCCESS ) : result;
212 }
213 
214 //=============================================================================
215 // Finalize
216 //=============================================================================
218 {
219 
220  if ( msgLevel( MSG::DEBUG ) ) debug() << "==> Finalize" << endmsg;
221  return GaudiAlgorithm::finalize();
222 }
223 
224 //=========================================================================
225 // Execute the beginRun of every algorithm
226 //=========================================================================
228 {
229 
230  if ( !isEnabled() ) return StatusCode::SUCCESS;
231  if ( msgLevel( MSG::DEBUG ) ) debug() << "==> beginRun" << endmsg;
232  return StatusCode::SUCCESS;
233 }
234 
235 //=========================================================================
236 // Execute the endRun() of every algorithm
237 //=========================================================================
239 {
240 
241  if ( !isEnabled() ) return StatusCode::SUCCESS;
242  if ( msgLevel( MSG::DEBUG ) ) debug() << "==> endRun" << endmsg;
243  return StatusCode::SUCCESS;
244 }
245 
246 //=========================================================================
247 // Decode the input names and fills the m_algs vector.
248 //=========================================================================
250 {
251 
253  m_entries.clear();
254 
255  //== Get the "Context" option if in the file...
256  auto jos = service<IJobOptionsSvc>( "JobOptionsSvc" );
257 
258  //= Get the Application manager, to see if algorithm exist
259  auto appMgr = service<IAlgManager>( "ApplicationMgr" );
260  for ( const auto& item : m_names.value() ) {
262  const std::string& theName = typeName.name();
263  const std::string& theType = typeName.type();
264 
265  //== Check wether the specified algorithm already exists. If not, create it
267  SmartIF<IAlgorithm> myIAlg = appMgr->algorithm( typeName, false ); // do not create it now
268  if ( !myIAlg ) {
269  // ensure some magic properties are set while we create the subalgorithm so
270  // that it effectively inherites 'our' settings -- if they have non-default
271  // values... and are not set explicitly already.
272  populate_JobOptionsSvc_t populate_guard{theName, jos, std::forward_as_tuple( "Context", context() ),
273  std::forward_as_tuple( "RootInTES", rootInTES() )};
274  Algorithm* myAlg = nullptr;
275  result = createSubAlgorithm( theType, theName, myAlg );
276  myIAlg = myAlg; // ensure that myIAlg.isValid() from here onwards!
277  } else {
278  Algorithm* myAlg = dynamic_cast<Algorithm*>( myIAlg.get() );
279  if ( myAlg ) {
280  subAlgorithms()->push_back( myAlg );
281  // when the algorithm is not created, the ref count is short by one, so we have to fix it.
282  myAlg->addRef();
283  }
284  }
285 
286  // propagate the sub-algorithm into own state.
287  if ( result.isSuccess() && Gaudi::StateMachine::INITIALIZED <= FSMState() && myIAlg &&
288  Gaudi::StateMachine::INITIALIZED > myIAlg->FSMState() ) {
289  StatusCode sc = myIAlg->sysInitialize();
290  if ( sc.isFailure() ) {
291  result = sc;
292  }
293  }
294 
295  // propagate the sub-algorithm into own state.
296  if ( result.isSuccess() && Gaudi::StateMachine::RUNNING <= FSMState() && myIAlg &&
297  Gaudi::StateMachine::RUNNING > myIAlg->FSMState() ) {
298  StatusCode sc = myIAlg->sysStart();
299  if ( sc.isFailure() ) {
300  result = sc;
301  }
302  }
303 
304  //== Is it an Algorithm ? Strange test...
305  if ( result.isSuccess() ) {
306  // TODO: (MCl) it is possible to avoid the dynamic_cast in most of the
307  // cases by keeping the result of createSubAlgorithm.
308  Algorithm* myAlg = dynamic_cast<Algorithm*>( myIAlg.get() );
309  if ( myAlg ) {
310  // Note: The reference counting is kept by the system of sub-algorithms
311  m_entries.emplace_back( myAlg );
312  if ( msgLevel( MSG::DEBUG ) ) debug() << "Added algorithm " << theName << endmsg;
313  } else {
314  warning() << theName << " is not an Algorithm - failed dynamic_cast" << endmsg;
315  final = StatusCode::FAILURE;
316  }
317  } else {
318  warning() << "Unable to find or create " << theName << endmsg;
319  final = result;
320  }
321  }
322 
323  //== Print the list of algorithms
324  MsgStream& msg = info();
325  if ( m_modeOR ) msg << "OR ";
326  msg << "Member list: ";
327  ostream_joiner( msg, m_entries, ", ", []( const AlgorithmEntry& e ) {
328  Algorithm* alg = e.algorithm();
329  std::string typ = System::typeinfoName( typeid( *alg ) );
330  return ( alg->name() == typ ) ? alg->name() : ( typ + "/" + alg->name() );
331  } );
332  if ( !isDefault( context() ) ) msg << ", with context '" << context() << "'";
333  if ( !isDefault( rootInTES() ) ) msg << ", with rootInTES '" << rootInTES() << "'";
334  msg << endmsg;
335 
336  return final;
337 }
338 
339 //=========================================================================
340 // Interface for the Property manager
341 //=========================================================================
343 {
344  // no action for not-yet initialized sequencer
346  return;
347  } // RETURN
348 
349  decodeNames().ignore();
350 
351  if ( !m_measureTime ) {
352  return;
353  } // RETURN
354 
355  // add the entries into timer table:
356 
357  if ( !m_timerTool ) {
358  m_timerTool = tool<ISequencerTimerTool>( "SequencerTimerTool" );
359  }
360 
361  if ( m_timerTool->globalTiming() ) m_measureTime = true;
362 
365 
366  for ( auto& entry : m_entries ) {
367  entry.setTimer( m_timerTool->addTimer( entry.algorithm()->name() ) );
368  }
369 
371 }
372 //=============================================================================
Gaudi::Property< bool > m_measureTime
Definition of the MsgStream class used to transmit messages.
Definition: MsgStream.h:24
StatusCode execute() override
Algorithm execution.
MsgStream & msg() const
shortcut for the method msgStream(MSG::INFO)
T empty(T...args)
The ISvcLocator is the interface implemented by the Service Factory in the Application Manager to loc...
Definition: ISvcLocator.h:25
virtual void decreaseIndent()=0
Decrease the indentation of the name.
StatusCode createSubAlgorithm(const std::string &type, const std::string &name, Algorithm *&pSubAlg)
Create a sub algorithm.
Definition: Algorithm.cpp:862
T forward_as_tuple(T...args)
const std::string & name() const override
The identifying name of the algorithm object.
Definition: Algorithm.cpp:725
Implementation of property with value of concrete type.
Definition: Property.h:313
virtual StatusCode sysStart()=0
Startup method invoked by the framework.
const std::string & rootInTES() const
Returns the "rootInTES" string.
Definition: GaudiCommon.h:696
bool isExecuted() const override
Has this algorithm been executed since the last reset?
Definition: Algorithm.cpp:735
MsgStream & info() const
shortcut for the method msgStream(MSG::INFO)
StatusCode initialize() override
Algorithm initialization.
GAUDI_API const std::string typeinfoName(const std::type_info &)
Get platform independent information about the class type.
Definition: System.cpp:299
virtual int addTimer(const std::string &name)=0
add a timer entry with the specified name
StatusCode initialize() override
standard initialization method
const std::string name() const
property name
Definition: Property.h:40
bool isSuccess() const
Test for a status code of SUCCESS.
Definition: StatusCode.h:74
StatusCode Error(const std::string &msg, const StatusCode st=StatusCode::FAILURE, const size_t mx=10) const
Print the error message and return with the given StatusCode.
MsgStream & verbose() const
shortcut for the method msgStream(MSG::VERBOSE)
void setContext(const EventContext *context) override
set the context
Definition: Algorithm.h:438
const std::string & context() const
Returns the "context" string. Used to identify different processing states.
Definition: GaudiCommon.h:692
virtual void increaseIndent()=0
Increase the indentation of the name.
T end(T...args)
Algorithm * algorithm() const
bool isFailure() const
Test for a status code of FAILURE.
Definition: StatusCode.h:84
virtual bool globalTiming()=0
returns the flag telling that global timing is wanted
StatusCode endRun() override
Algorithm endRun.
virtual StatusCode sysInitialize()=0
Initialization method invoked by the framework.
STL class.
virtual StatusCode addPropertyToCatalogue(const std::string &client, const Gaudi::Details::PropertyBase &property)=0
Add a property into the JobOptions catalog.
TYPE * get() const
Get interface pointer.
Definition: SmartIF.h:76
ISequencerTimerTool * m_timerTool
Pointer to the timer tool.
T push_back(T...args)
bool isEnabled() const override
Is this algorithm enabled or disabled?
Definition: Algorithm.cpp:772
Gaudi::Property< bool > m_ignoreFilter
Helper class to parse a string of format "type/name".
void setExecuted(bool state) override
Set the executed flag to the specified state.
Definition: Algorithm.cpp:748
Gaudi::Property< std::vector< std::string > > m_names
Main interface for the JobOptions service.
MsgStream & warning() const
shortcut for the method msgStream(MSG::WARNING)
This class is used for returning status codes from appropriate routines.
Definition: StatusCode.h:26
StatusCode sysExecute() override
The actions to be performed by the algorithm on an event.
Definition: Algorithm.cpp:494
StatusCode finalize() override
standard finalization method
T erase(T...args)
The useful base class for data processing algorithms.
void membershipHandler(Gaudi::Details::PropertyBase &theProp)
for asynchronous changes in the list of algorithms
PropertyBase base class allowing PropertyBase* collections to be "homogeneous".
Definition: Property.h:32
StatusCode finalize() override
Algorithm finalization.
virtual const std::vector< const Gaudi::Details::PropertyBase * > * getProperties(const std::string &client) const =0
Get the properties associated to a given client.
Gaudi::Property< bool > m_modeOR
T move(T...args)
StatusCode decodeNames()
Decode a vector of string.
Stream & ostream_joiner(Stream &os, Iterator first, Iterator last, Separator sep, OutputElement output=OutputElement{})
Definition: SerializeSTL.h:35
Gaudi::Property< bool > m_shortCircuit
virtual void start(int index)=0
start the counter, i.e.
const std::vector< Algorithm * > * subAlgorithms() const
List of sub-algorithms. Returns a pointer to a vector of (sub) Algorithms.
Definition: Algorithm.cpp:801
Base class from which all concrete algorithm classes should be derived.
Definition: Algorithm.h:78
T find_if(T...args)
STL class.
STL class.
MsgStream & debug() const
shortcut for the method msgStream(MSG::DEBUG)
T begin(T...args)
const std::string & type() const
virtual StatusCode removePropertyFromCatalogue(const std::string &client, const std::string &name)=0
Remove a property from the JobOptions catalog.
bool filterPassed() const override
Did this algorithm pass or fail its filter criterion for the last event?
Definition: Algorithm.cpp:776
appMgr
Definition: IOTest.py:83
string s
Definition: gaudirun.py:245
Gaudi::Property< bool > m_returnOK
GaudiSequencer(const std::string &name, ISvcLocator *pSvcLocator)
Standard constructor.
const std::string & name() const
void ignore() const
Definition: StatusCode.h:106
std::string typeName(const std::type_info &typ)
Definition: Dictionary.cpp:21
MSG::Level msgLevel() const
get the output level from the embedded MsgStream
T for_each(T...args)
virtual double stop(int index)=0
stop the counter, return the elapsed time
StatusCode release(const IInterface *interface) const
Manual forced (and &#39;safe&#39;) release of the active tool or service.
void setFilterPassed(bool state) override
Set the filter passed flag to the specified state.
Definition: Algorithm.cpp:789
MsgStream & endmsg(MsgStream &s)
MsgStream Modifier: endmsg. Calls the output method of the MsgStream.
Definition: MsgStream.h:244
const EventContext * getContext() const override
get the context
Definition: Algorithm.h:435
int m_timer
Timer number for the sequencer.
std::vector< AlgorithmEntry > m_entries
List of algorithms to process.
Gaudi::StateMachine::State FSMState() const override
returns the current state of the algorithm
Definition: Algorithm.h:190
StatusCode beginRun() override
Algorithm beginRun.