The Gaudi Framework  v33r1 (b1225454)
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 } // namespace
30 
31 //-----------------------------------------------------------------------------
32 // Implementation file for class : GaudiSequencer
33 //
34 // 2004-05-13 : Olivier Callot
35 //-----------------------------------------------------------------------------
36 
37 //=============================================================================
38 // Initialisation. Check parameters
39 //=============================================================================
41  // Note: not calling base class initialize because we want to reimplement the loop over sub algs
42  if ( msgLevel( MSG::DEBUG ) ) debug() << "==> Initialise" << endmsg;
43 
44  auto status = decodeNames();
45  if ( !status.isSuccess() ) return status;
46 
47  m_timerTool = tool<ISequencerTimerTool>( "SequencerTimerTool" );
48 
49  if ( m_timerTool->globalTiming() ) m_measureTime = true;
50 
51  if ( m_measureTime ) {
54  } else {
56  m_timerTool = nullptr;
57  }
58 
59  //== Initialize the algorithms
60  for ( auto& entry : m_entries ) {
61  if ( m_measureTime ) { entry.setTimer( m_timerTool->addTimer( entry.algorithm()->name() ) ); }
62 
63  status = entry.algorithm()->sysInitialize();
64  if ( !status.isSuccess() ) { return Error( "Can not initialize " + entry.algorithm()->name(), status ); }
65  }
67 
68  return StatusCode::SUCCESS;
69 }
70 
71 //=============================================================================
72 // Main execution
73 //=============================================================================
75 
77 
78  if ( msgLevel( MSG::DEBUG ) ) debug() << "==> Execute" << endmsg;
79 
80  StatusCode result = StatusCode( StatusCode::SUCCESS, true );
81 
82  bool seqPass = !m_modeOR; // for OR, result will be false, unless (at least) one is true
83  // for AND, result will be true, unless (at least) one is false
84  // also see comment below ....
85 
86  for ( auto& entry : m_entries ) {
87  Gaudi::Algorithm* myAlg = entry.algorithm();
88  if ( !myAlg->isEnabled() ) continue;
89  if ( myAlg->execState( ctx ).state() != AlgExecState::State::Done ) {
90 
91  if ( m_measureTime ) m_timerTool->start( entry.timer() );
92  result = myAlg->sysExecute( ctx );
93  if ( m_measureTime ) m_timerTool->stop( entry.timer() );
94  if ( !result.isSuccess() ) break; //== Abort and return bad status
95  }
96  //== Check the returned status
97  if ( !m_ignoreFilter ) {
98  bool passed = myAlg->execState( ctx ).filterPassed();
99  if ( msgLevel( MSG::VERBOSE ) )
100  verbose() << "Algorithm " << myAlg->name() << " returned filter passed " << ( passed ? "true" : "false" )
101  << endmsg;
102  if ( entry.reverse() ) passed = !passed;
103 
104  //== indicate our own result. For OR, exit as soon as true.
105  // If no more, will exit with false.
106  //== for AND, exit as soon as false. Else, will be true (default)
107 
108  // if not short-circuiting, make sure we latch iPass to 'true' in
109  // OR mode (i.e. it is sufficient for one item to be true in order
110  // to be true at the end, and thus we start out at 'false'), and latch
111  // to 'false' in AND mode (i.e. it is sufficient for one item to
112  // be false to the false in the end, and thus we start out at 'true')
113  // -- i.e. we should not just blindly return the 'last' passed status!
114 
115  // or to put it another way: in OR mode, we don't care about things
116  // which are false, as they leave our current state alone (provided
117  // we stared as 'false'!), and in AND mode, we keep our current
118  // state until someone returns 'false' (provided we started as 'true')
119  if ( m_modeOR ? passed : !passed ) {
120  seqPass = passed;
121  if ( msgLevel( MSG::VERBOSE ) ) verbose() << "SeqPass is now " << ( seqPass ? "true" : "false" ) << endmsg;
122  if ( m_shortCircuit ) break;
123  }
124  }
125  }
126  if ( msgLevel( MSG::VERBOSE ) ) verbose() << "SeqPass is " << ( seqPass ? "true" : "false" ) << endmsg;
127  auto& state = execState( ctx );
128  if ( !m_ignoreFilter && !m_entries.empty() ) state.setFilterPassed( m_invert ? !seqPass : seqPass );
129  state.setState( AlgExecState::State::Done );
130 
132 
133  return m_returnOK ? ( result.ignore(), StatusCode::SUCCESS ) : result;
134 }
135 
136 //=========================================================================
137 // Decode the input names and fills the m_algs vector.
138 //=========================================================================
141  m_entries.clear();
142 
143  //== Get the "Context" option if in the file...
144  auto jos = service<IJobOptionsSvc>( "JobOptionsSvc" );
145 
146  //= Get the Application manager, to see if algorithm exist
147  auto appMgr = service<IAlgManager>( "ApplicationMgr" );
148  for ( const auto& item : m_names.value() ) {
150  const std::string& theName = typeName.name();
151  const std::string& theType = typeName.type();
152 
153  //== Check wether the specified algorithm already exists. If not, create it
155  SmartIF<IAlgorithm> myIAlg = appMgr->algorithm( typeName, false ); // do not create it now
156  if ( !myIAlg ) {
157  Gaudi::Algorithm* myAlg = nullptr;
158  result = createSubAlgorithm( theType, theName, myAlg );
159  if ( myAlg ) {
160  // Override the default values of the special properties Context and RootInTES,
161  // which will be superseded by the explicit value in options (if present).
162  if ( !isDefault( context() ) && myAlg->hasProperty( "Context" ) ) {
163  myAlg->setProperty( "Context", context() ).ignore();
164  }
165  if ( !isDefault( rootInTES() ) && myAlg->hasProperty( "RootInTES" ) ) {
166  myAlg->setProperty( "RootInTES", rootInTES() ).ignore();
167  }
168  }
169  myIAlg = myAlg; // ensure that myIAlg.isValid() from here onwards!
170  } else {
171  Gaudi::Algorithm* myAlg = dynamic_cast<Gaudi::Algorithm*>( myIAlg.get() );
172  if ( myAlg ) {
173  subAlgorithms()->push_back( myAlg );
174  // when the algorithm is not created, the ref count is short by one, so we have to fix it.
175  myAlg->addRef();
176  }
177  }
178 
179  // propagate the sub-algorithm into own state.
180  if ( result.isSuccess() && Gaudi::StateMachine::INITIALIZED <= FSMState() && myIAlg &&
181  Gaudi::StateMachine::INITIALIZED > myIAlg->FSMState() ) {
182  StatusCode sc = myIAlg->sysInitialize();
183  if ( sc.isFailure() ) result = sc;
184  }
185 
186  // propagate the sub-algorithm into own state.
187  if ( result.isSuccess() && Gaudi::StateMachine::RUNNING <= FSMState() && myIAlg &&
188  Gaudi::StateMachine::RUNNING > myIAlg->FSMState() ) {
189  StatusCode sc = myIAlg->sysStart();
190  if ( sc.isFailure() ) result = sc;
191  }
192 
193  //== Is it an Algorithm ? Strange test...
194  if ( result.isSuccess() ) {
195  // TODO: (MCl) it is possible to avoid the dynamic_cast in most of the
196  // cases by keeping the result of createSubAlgorithm.
197  Gaudi::Algorithm* myAlg = dynamic_cast<Gaudi::Algorithm*>( myIAlg.get() );
198  if ( myAlg ) {
199  // Note: The reference counting is kept by the system of sub-algorithms
200  m_entries.emplace_back( myAlg );
201  if ( msgLevel( MSG::DEBUG ) ) debug() << "Added algorithm " << theName << endmsg;
202  } else {
203  warning() << theName << " is not a Gaudi::Algorithm - failed dynamic_cast" << endmsg;
204  final = StatusCode::FAILURE;
205  }
206  } else {
207  warning() << "Unable to find or create " << theName << endmsg;
208  final = result;
209  }
210  }
211 
212  //== Print the list of algorithms
213  MsgStream& msg = info();
214  if ( m_modeOR ) msg << "OR ";
215  msg << "Member list: ";
217  []( auto& os, const AlgorithmEntry& e ) -> decltype( auto ) {
219  std::string typ = System::typeinfoName( typeid( *alg ) );
220  os << typ;
221  if ( alg->name() != typ ) os << "/" << alg->name();
222  return os;
223  } );
224  if ( !isDefault( context() ) ) msg << ", with context '" << context() << "'";
225  if ( !isDefault( rootInTES() ) ) msg << ", with rootInTES '" << rootInTES() << "'";
226  msg << endmsg;
227 
228  return final;
229 }
230 
231 //=========================================================================
232 // Interface for the Property manager
233 //=========================================================================
235  // no action for not-yet initialized sequencer
236  if ( Gaudi::StateMachine::INITIALIZED > FSMState() ) return; // RETURN
237 
238  decodeNames().ignore();
239 
240  if ( !m_measureTime ) return; // RETURN
241 
242  // add the entries into timer table:
243 
244  if ( !m_timerTool ) { m_timerTool = tool<ISequencerTimerTool>( "SequencerTimerTool" ); }
245 
246  if ( m_timerTool->globalTiming() ) m_measureTime = true;
247 
250 
251  for ( auto& entry : m_entries ) { entry.setTimer( m_timerTool->addTimer( entry.algorithm()->name() ) ); }
252 
254 }
255 
257  if ( m_invert ) os << "~";
258  // the default filterpass value for an empty sequencer depends on ModeOR
259  if ( m_entries.empty() ) return os << ( ( !m_modeOR ) ? "CFTrue" : "CFFalse" );
260 
261  // if we have only one element, we do not need a name
262  if ( m_entries.size() > 1 ) os << "seq(";
263 
264  const auto op = m_modeOR ? " | " : " & ";
265  const auto last = end( m_entries );
266  const auto first = begin( m_entries );
267  for ( auto iterator = first; iterator != last; ++iterator ) {
268  if ( iterator != first ) os << op;
269  if ( iterator->reverse() ) os << "~";
270  iterator->algorithm()->toControlFlowExpression( os );
271  }
272 
273  if ( m_entries.size() > 1 ) os << ")";
274  return os;
275 }
276 
277 // ============================================================================
280 
281  IAlgContextSvc* algCtx = nullptr;
282  if ( registerContext() ) { algCtx = contextSvc(); }
283  // Lock the context
284  Gaudi::Utils::AlgContext cnt( this, algCtx, ctx );
285 
286  // Do not execute if one or more of the m_vetoObjs exist in TES
287  const auto it = find_if( begin( m_vetoObjs ), end( m_vetoObjs ),
288  [&]( const std::string& loc ) { return this->exist<DataObject>( evtSvc(), loc ); } );
289  if ( it != end( m_vetoObjs ) ) {
290  if ( msgLevel( MSG::DEBUG ) ) debug() << *it << " found, skipping event " << endmsg;
291  return sc;
292  }
293 
294  // Execute if m_requireObjs is empty
295  // or if one or more of the m_requireObjs exist in TES
296  bool doIt = m_requireObjs.empty() ||
297  any_of( begin( m_requireObjs ), end( m_requireObjs ),
298  [&]( const std::string& loc ) { return this->exist<DataObject>( evtSvc(), loc ); } );
299 
300  // execute the generic method:
301  if ( doIt ) sc = GaudiCommon<Gaudi::Sequence>::sysExecute( ctx );
302  return sc;
303 }
304 //=============================================================================
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.
Helper "sentry" class to automatize the safe register/unregister the algorithm's context.
virtual StatusCode sysStart()=0
Startup method invoked by the framework.
StatusCode setProperty(const Gaudi::Details::PropertyBase &p) override
set the property form another property
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
StatusCode Error(std::string_view msg, const StatusCode st=StatusCode::FAILURE, const size_t mx=10) const
Print the error message and return with the given StatusCode.
constexpr static const auto SUCCESS
Definition: StatusCode.h:100
bool filterPassed() const
virtual void increaseIndent()=0
Increase the indentation of the name.
TYPE * get() const
Get interface pointer.
Definition: SmartIF.h:86
bool hasProperty(const std::string &name) const override
Return true if we have a property with the given name.
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.
ISequencerTimerTool * m_timerTool
Pointer to the timer tool.
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
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:365
const std::string & context() const
Returns the "context" string. Used to identify different processing states.
Definition: GaudiCommon.h:694
Gaudi::Property< bool > m_modeOR
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:61
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:168
StatusCode execute(const EventContext &ctx) const override
AlgExecState & execState(const EventContext &ctx) const override
reference to AlgExecState of Alg
Definition: Algorithm.cpp:561
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:101
An abstract interface for Algorithm Context Service.
Gaudi::Property< bool > m_returnOK
bool isFailure() const
Definition: StatusCode.h:145
AttribStringParser::Iterator begin(const AttribStringParser &parser)
bool isEnabled() const override
Is this algorithm enabled or disabled?
Definition: Algorithm.cpp:559
Gaudi::Property< std::vector< std::string > > m_requireObjs
std::string typeName(const std::type_info &typ)
Definition: Dictionary.cpp:31
virtual double stop(int index)=0
stop the counter, return the elapsed time
STL class.
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:549
StatusCode sysExecute(const EventContext &ctx) override
The actions to be performed by the algorithm on an event.
Definition: Algorithm.cpp:338
std::ostream & toControlFlowExpression(std::ostream &os) const override
Produce string represention of the control flow expression.