The Gaudi Framework  v33r0 (d5ea422b)
GaudiSequencer.cpp
Go to the documentation of this file.
1 /***********************************************************************************\
2 * (c) Copyright 1998-2019 CERN for the benefit of the LHCb and ATLAS collaborations *
3 * *
4 * This software is distributed under the terms of the Apache version 2 licence, *
5 * copied verbatim in the file "LICENSE". *
6 * *
7 * In applying this licence, CERN does not waive the privileges and immunities *
8 * granted to it by virtue of its status as an Intergovernmental Organization *
9 * or submit itself to any jurisdiction. *
10 \***********************************************************************************/
11 // Include files
12 #include <initializer_list>
13 #include <tuple>
14 
15 // from Gaudi
21 
22 #include "GaudiCommon.icpp"
23 template class GaudiCommon<Gaudi::Sequence>;
24 
25 namespace {
26 
27  bool isDefault( const std::string& s ) { return s.empty(); }
28 
29  template <typename Container>
30  bool veto( const Container* props, const char* name ) { // avoid changing properties explicitly present in the JOS...
31  return props &&
32  std::any_of( begin( *props ), end( *props ), [name]( const auto* prop ) { return prop->name() == name; } );
33  }
34 
35  template <typename F, typename... Args>
36  void for_each_arg( F&& f, Args&&... args ) {
37  // the std::initializer_list only exists to provide a 'context' in which to
38  // expand the variadic pack
39  (void)std::initializer_list<int>{( f( std::forward<Args>( args ) ), 0 )...};
40  }
41 
42  // utility class to populate some properties in the job options service
43  // for a given instance name in case those options are not explicitly
44  // set a-priori (effectively inheriting their values from the GaudiSequencer)
45  class populate_JobOptionsSvc_t {
47  IJobOptionsSvc* m_jos;
48  std::string m_name;
49 
50  template <typename Properties, typename Key, typename Value>
51  void addPropertyToCatalogue( const Properties* props, const std::tuple<Key, Value>& arg ) {
52  const auto& key = std::get<0>( arg );
53  const auto& value = std::get<1>( arg );
54  if ( isDefault( value ) || veto( props, key ) ) return;
55  m_jos->addPropertyToCatalogue( m_name, Gaudi::Property<std::decay_t<Value>>{key, value} ).ignore();
56  m_props.push_back( key );
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  const auto* props = m_jos->getProperties( m_name );
64  for_each_arg( [&]( auto&& arg ) { this->addPropertyToCatalogue( props, std::forward<decltype( arg )>( arg ) ); },
65  std::forward<Args>( args )... );
66  }
67  ~populate_JobOptionsSvc_t() {
68  std::for_each( begin( m_props ), end( m_props ),
69  [&]( const std::string& key ) { m_jos->removePropertyFromCatalogue( m_name, key ).ignore(); } );
70  }
71  };
72 } // namespace
73 
74 //-----------------------------------------------------------------------------
75 // Implementation file for class : GaudiSequencer
76 //
77 // 2004-05-13 : Olivier Callot
78 //-----------------------------------------------------------------------------
79 
80 //=============================================================================
81 // Initialisation. Check parameters
82 //=============================================================================
84  // Note: not calling base class initialize because we want to reimplement the loop over sub algs
85  if ( msgLevel( MSG::DEBUG ) ) debug() << "==> Initialise" << endmsg;
86 
87  auto status = decodeNames();
88  if ( !status.isSuccess() ) return status;
89 
90  m_timerTool = tool<ISequencerTimerTool>( "SequencerTimerTool" );
91 
92  if ( m_timerTool->globalTiming() ) m_measureTime = true;
93 
94  if ( m_measureTime ) {
97  } else {
99  m_timerTool = nullptr;
100  }
101 
102  //== Initialize the algorithms
103  for ( auto& entry : m_entries ) {
104  if ( m_measureTime ) { entry.setTimer( m_timerTool->addTimer( entry.algorithm()->name() ) ); }
105 
106  status = entry.algorithm()->sysInitialize();
107  if ( !status.isSuccess() ) { return Error( "Can not initialize " + entry.algorithm()->name(), status ); }
108  }
110 
111  return StatusCode::SUCCESS;
112 }
113 
114 //=============================================================================
115 // Main execution
116 //=============================================================================
118 
120 
121  if ( msgLevel( MSG::DEBUG ) ) debug() << "==> Execute" << endmsg;
122 
123  StatusCode result = StatusCode( StatusCode::SUCCESS, true );
124 
125  bool seqPass = !m_modeOR; // for OR, result will be false, unless (at least) one is true
126  // for AND, result will be true, unless (at least) one is false
127  // also see comment below ....
128 
129  for ( auto& entry : m_entries ) {
130  Gaudi::Algorithm* myAlg = entry.algorithm();
131  if ( !myAlg->isEnabled() ) continue;
132  if ( myAlg->execState( ctx ).state() != AlgExecState::State::Done ) {
133 
134  if ( m_measureTime ) m_timerTool->start( entry.timer() );
135  result = myAlg->sysExecute( ctx );
136  if ( m_measureTime ) m_timerTool->stop( entry.timer() );
137  if ( !result.isSuccess() ) break; //== Abort and return bad status
138  }
139  //== Check the returned status
140  if ( !m_ignoreFilter ) {
141  bool passed = myAlg->execState( ctx ).filterPassed();
142  if ( msgLevel( MSG::VERBOSE ) )
143  verbose() << "Algorithm " << myAlg->name() << " returned filter passed " << ( passed ? "true" : "false" )
144  << endmsg;
145  if ( entry.reverse() ) passed = !passed;
146 
147  //== indicate our own result. For OR, exit as soon as true.
148  // If no more, will exit with false.
149  //== for AND, exit as soon as false. Else, will be true (default)
150 
151  // if not short-circuiting, make sure we latch iPass to 'true' in
152  // OR mode (i.e. it is sufficient for one item to be true in order
153  // to be true at the end, and thus we start out at 'false'), and latch
154  // to 'false' in AND mode (i.e. it is sufficient for one item to
155  // be false to the false in the end, and thus we start out at 'true')
156  // -- i.e. we should not just blindly return the 'last' passed status!
157 
158  // or to put it another way: in OR mode, we don't care about things
159  // which are false, as they leave our current state alone (provided
160  // we stared as 'false'!), and in AND mode, we keep our current
161  // state until someone returns 'false' (provided we started as 'true')
162  if ( m_modeOR ? passed : !passed ) {
163  seqPass = passed;
164  if ( msgLevel( MSG::VERBOSE ) ) verbose() << "SeqPass is now " << ( seqPass ? "true" : "false" ) << endmsg;
165  if ( m_shortCircuit ) break;
166  }
167  }
168  }
169  if ( msgLevel( MSG::VERBOSE ) ) verbose() << "SeqPass is " << ( seqPass ? "true" : "false" ) << endmsg;
170  auto& state = execState( ctx );
171  if ( !m_ignoreFilter && !m_entries.empty() ) state.setFilterPassed( m_invert ? !seqPass : seqPass );
172  state.setState( AlgExecState::State::Done );
173 
175 
176  return m_returnOK ? ( result.ignore(), StatusCode::SUCCESS ) : result;
177 }
178 
179 //=========================================================================
180 // Decode the input names and fills the m_algs vector.
181 //=========================================================================
184  m_entries.clear();
185 
186  //== Get the "Context" option if in the file...
187  auto jos = service<IJobOptionsSvc>( "JobOptionsSvc" );
188 
189  //= Get the Application manager, to see if algorithm exist
190  auto appMgr = service<IAlgManager>( "ApplicationMgr" );
191  for ( const auto& item : m_names.value() ) {
193  const std::string& theName = typeName.name();
194  const std::string& theType = typeName.type();
195 
196  //== Check wether the specified algorithm already exists. If not, create it
198  SmartIF<IAlgorithm> myIAlg = appMgr->algorithm( typeName, false ); // do not create it now
199  if ( !myIAlg ) {
200  // ensure some magic properties are set while we create the subalgorithm so
201  // that it effectively inherites 'our' settings -- if they have non-default
202  // values... and are not set explicitly already.
203  populate_JobOptionsSvc_t populate_guard{theName, jos, std::forward_as_tuple( "Context", context() ),
204  std::forward_as_tuple( "RootInTES", rootInTES() )};
205  Gaudi::Algorithm* myAlg = nullptr;
206  result = createSubAlgorithm( theType, theName, myAlg );
207  myIAlg = myAlg; // ensure that myIAlg.isValid() from here onwards!
208  } else {
209  Gaudi::Algorithm* myAlg = dynamic_cast<Gaudi::Algorithm*>( myIAlg.get() );
210  if ( myAlg ) {
211  subAlgorithms()->push_back( myAlg );
212  // when the algorithm is not created, the ref count is short by one, so we have to fix it.
213  myAlg->addRef();
214  }
215  }
216 
217  // propagate the sub-algorithm into own state.
218  if ( result.isSuccess() && Gaudi::StateMachine::INITIALIZED <= FSMState() && myIAlg &&
219  Gaudi::StateMachine::INITIALIZED > myIAlg->FSMState() ) {
220  StatusCode sc = myIAlg->sysInitialize();
221  if ( sc.isFailure() ) result = sc;
222  }
223 
224  // propagate the sub-algorithm into own state.
225  if ( result.isSuccess() && Gaudi::StateMachine::RUNNING <= FSMState() && myIAlg &&
226  Gaudi::StateMachine::RUNNING > myIAlg->FSMState() ) {
227  StatusCode sc = myIAlg->sysStart();
228  if ( sc.isFailure() ) result = sc;
229  }
230 
231  //== Is it an Algorithm ? Strange test...
232  if ( result.isSuccess() ) {
233  // TODO: (MCl) it is possible to avoid the dynamic_cast in most of the
234  // cases by keeping the result of createSubAlgorithm.
235  Gaudi::Algorithm* myAlg = dynamic_cast<Gaudi::Algorithm*>( myIAlg.get() );
236  if ( myAlg ) {
237  // Note: The reference counting is kept by the system of sub-algorithms
238  m_entries.emplace_back( myAlg );
239  if ( msgLevel( MSG::DEBUG ) ) debug() << "Added algorithm " << theName << endmsg;
240  } else {
241  warning() << theName << " is not a Gaudi::Algorithm - failed dynamic_cast" << endmsg;
242  final = StatusCode::FAILURE;
243  }
244  } else {
245  warning() << "Unable to find or create " << theName << endmsg;
246  final = result;
247  }
248  }
249 
250  //== Print the list of algorithms
251  MsgStream& msg = info();
252  if ( m_modeOR ) msg << "OR ";
253  msg << "Member list: ";
255  []( auto& os, const AlgorithmEntry& e ) -> decltype( auto ) {
257  std::string typ = System::typeinfoName( typeid( *alg ) );
258  os << typ;
259  if ( alg->name() != typ ) os << "/" << alg->name();
260  return os;
261  } );
262  if ( !isDefault( context() ) ) msg << ", with context '" << context() << "'";
263  if ( !isDefault( rootInTES() ) ) msg << ", with rootInTES '" << rootInTES() << "'";
264  msg << endmsg;
265 
266  return final;
267 }
268 
269 //=========================================================================
270 // Interface for the Property manager
271 //=========================================================================
273  // no action for not-yet initialized sequencer
274  if ( Gaudi::StateMachine::INITIALIZED > FSMState() ) return; // RETURN
275 
276  decodeNames().ignore();
277 
278  if ( !m_measureTime ) return; // RETURN
279 
280  // add the entries into timer table:
281 
282  if ( !m_timerTool ) { m_timerTool = tool<ISequencerTimerTool>( "SequencerTimerTool" ); }
283 
284  if ( m_timerTool->globalTiming() ) m_measureTime = true;
285 
288 
289  for ( auto& entry : m_entries ) { entry.setTimer( m_timerTool->addTimer( entry.algorithm()->name() ) ); }
290 
292 }
293 
295  if ( m_invert ) os << "~";
296  // the default filterpass value for an empty sequencer depends on ModeOR
297  if ( m_entries.empty() ) return os << ( ( !m_modeOR ) ? "CFTrue" : "CFFalse" );
298 
299  // if we have only one element, we do not need a name
300  if ( m_entries.size() > 1 ) os << "seq(";
301 
302  const auto op = m_modeOR ? " | " : " & ";
303  const auto last = end( m_entries );
304  const auto first = begin( m_entries );
305  for ( auto iterator = first; iterator != last; ++iterator ) {
306  if ( iterator != first ) os << op;
307  if ( iterator->reverse() ) os << "~";
308  iterator->algorithm()->toControlFlowExpression( os );
309  }
310 
311  if ( m_entries.size() > 1 ) os << ")";
312  return os;
313 }
314 
315 // ============================================================================
318 
319  IAlgContextSvc* algCtx = nullptr;
320  if ( registerContext() ) { algCtx = contextSvc(); }
321  // Lock the context
322  Gaudi::Utils::AlgContext cnt( this, algCtx, ctx );
323 
324  // Do not execute if one or more of the m_vetoObjs exist in TES
325  const auto it = find_if( begin( m_vetoObjs ), end( m_vetoObjs ),
326  [&]( const std::string& loc ) { return this->exist<DataObject>( evtSvc(), loc ); } );
327  if ( it != end( m_vetoObjs ) ) {
328  if ( msgLevel( MSG::DEBUG ) ) debug() << *it << " found, skipping event " << endmsg;
329  return sc;
330  }
331 
332  // Execute if m_requireObjs is empty
333  // or if one or more of the m_requireObjs exist in TES
334  bool doIt = m_requireObjs.empty() ||
335  any_of( begin( m_requireObjs ), end( m_requireObjs ),
336  [&]( const std::string& loc ) { return this->exist<DataObject>( evtSvc(), loc ); } );
337 
338  // execute the generic method:
339  if ( doIt ) sc = GaudiCommon<Gaudi::Sequence>::sysExecute( ctx );
340  return sc;
341 }
342 //=============================================================================
Gaudi::Property< bool > m_measureTime
Definition of the MsgStream class used to transmit messages.
Definition: MsgStream.h:34
virtual void decreaseIndent()=0
Decrease the indentation of the name.
T forward_as_tuple(T... args)
Helper "sentry" class to automatize the safe register/unregister the algorithm's context.
Implementation of property with value of concrete type.
Definition: Property.h:370
virtual StatusCode sysStart()=0
Startup method invoked by the framework.
StatusCode initialize() override
GAUDI_API const std::string typeinfoName(const std::type_info &)
Get platform independent information about the class type.
Definition: System.cpp:308
virtual int addTimer(const std::string &name)=0
add a timer entry with the specified name
bool PyHelper() addPropertyToCatalogue(IInterface *p, char *comp, char *name, char *value)
Definition: Bootstrap.cpp:255
WARN_UNUSED 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.
virtual const std::vector< const Gaudi::Details::PropertyBase * > * getProperties(const std::string &client) const =0
Get the properties associated to a given client.
constexpr static const auto SUCCESS
Definition: StatusCode.h:96
bool filterPassed() const
virtual void increaseIndent()=0
Increase the indentation of the name.
TYPE * get() const
Get interface pointer.
Definition: SmartIF.h:86
This class represents an entry point to all the event specific data.
Definition: EventContext.h:34
virtual bool globalTiming()=0
returns the flag telling that global timing is wanted
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.
ISequencerTimerTool * m_timerTool
Pointer to the timer tool.
T push_back(T... args)
StatusCode sysExecute(const EventContext &ctx) override
Gaudi::Property< bool > m_ignoreFilter
Helper class to parse a string of format "type/name".
Gaudi::Property< std::vector< std::string > > m_names
Gaudi::Property< bool > m_invert
Main interface for the JobOptions service.
This class is used for returning status codes from appropriate routines.
Definition: StatusCode.h:61
State state() const
Gaudi::Algorithm * algorithm() const
def end
Definition: IOTest.py:123
bool isSuccess() const
Definition: StatusCode.h:361
const std::string & context() const
Returns the "context" string. Used to identify different processing states.
Definition: GaudiCommon.h:717
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:47
Gaudi::Property< bool > m_shortCircuit
const std::string & rootInTES() const
Returns the "rootInTES" string.
Definition: FixTESPath.h:62
StatusCode release(const IInterface *interface) const
Manual forced (and 'safe') release of the active tool or service.
virtual void start(int index)=0
start the counter, i.e.
void membershipHandler()
for asynchronous changes in the list of algorithms
const StatusCode & ignore() const
Ignore/check StatusCode.
Definition: StatusCode.h:164
StatusCode execute(const EventContext &ctx) const override
AlgExecState & execState(const EventContext &ctx) const override
reference to AlgExecState of Alg
Definition: Algorithm.cpp:568
T any_of(T... args)
virtual StatusCode removePropertyFromCatalogue(const std::string &client, const std::string &name)=0
Remove a property from the JobOptions catalog.
virtual StatusCode sysInitialize()=0
Initialization of the Tool.
Base class from which all concrete algorithm classes should be derived.
Definition: Algorithm.h:89
appMgr
Definition: IOTest.py:103
string s
Definition: gaudirun.py:328
constexpr static const auto FAILURE
Definition: StatusCode.h:97
An abstract interface for Algorithm Context Service.
Gaudi::Property< bool > m_returnOK
bool isFailure() const
Definition: StatusCode.h:141
AttribStringParser::Iterator begin(const AttribStringParser &parser)
bool isEnabled() const override
Is this algorithm enabled or disabled?
Definition: Algorithm.cpp:566
Gaudi::Property< std::vector< std::string > > m_requireObjs
std::string typeName(const std::type_info &typ)
Definition: Dictionary.cpp:31
T for_each(T... args)
virtual double stop(int index)=0
stop the counter, return the elapsed time
STL class.
T forward(T... args)
Gaudi::Property< std::vector< std::string > > m_vetoObjs
MsgStream & endmsg(MsgStream &s)
MsgStream Modifier: endmsg. Calls the output method of the MsgStream.
Definition: MsgStream.h:202
int m_timer
Timer number for the sequencer.
std::vector< AlgorithmEntry > m_entries
List of algorithms to process.
const std::string & name() const override
The identifying name of the algorithm object.
Definition: Algorithm.cpp:556
StatusCode sysExecute(const EventContext &ctx) override
The actions to be performed by the algorithm on an event.
Definition: Algorithm.cpp:345
std::ostream & toControlFlowExpression(std::ostream &os) const override
Produce string represention of the control flow expression.