The Gaudi Framework  v36r16 (ea80daf8)
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
AvalancheSchedulerSvc.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 "AvalancheSchedulerSvc.h"
12 #include "AlgTask.h"
13 #include "ThreadPoolSvc.h"
14 
15 // Framework includes
18 #include "GaudiKernel/IAlgorithm.h"
21 #include <Gaudi/Algorithm.h> // can be removed ASA dynamic casts to Algorithm are removed
23 
24 // C++
25 #include <algorithm>
26 #include <map>
27 #include <queue>
28 #include <sstream>
29 #include <string_view>
30 #include <thread>
31 #include <unordered_set>
32 
33 // External libs
34 #include "boost/algorithm/string.hpp"
35 #include "boost/thread.hpp"
36 #include "boost/tokenizer.hpp"
37 // DP waiting for the TBB service
38 #include "tbb/tbb_stddef.h"
39 
40 // Instantiation of a static factory class used by clients to create instances of this service
42 
43 #define ON_DEBUG if ( msgLevel( MSG::DEBUG ) )
44 #define ON_VERBOSE if ( msgLevel( MSG::VERBOSE ) )
45 
46 namespace {
47  struct DataObjIDSorter {
48  bool operator()( const DataObjID* a, const DataObjID* b ) { return a->fullKey() < b->fullKey(); }
49  };
50 
51  // Sort a DataObjIDColl in a well-defined, reproducible manner.
52  // Used for making debugging dumps.
53  std::vector<const DataObjID*> sortedDataObjIDColl( const DataObjIDColl& coll ) {
55  v.reserve( coll.size() );
56  for ( const DataObjID& id : coll ) v.push_back( &id );
57  std::sort( v.begin(), v.end(), DataObjIDSorter() );
58  return v;
59  }
60 
61  bool subSlotAlgsInStates( const EventSlot& slot, std::initializer_list<AlgsExecutionStates::State> testStates ) {
62  return std::any_of( slot.allSubSlots.begin(), slot.allSubSlots.end(),
63  [testStates]( const EventSlot& ss ) { return ss.algsStates.containsAny( testStates ); } );
64  }
65 } // namespace
66 
67 //---------------------------------------------------------------------------
68 
76 
77  // Initialise mother class (read properties, ...)
79  if ( sc.isFailure() ) warning() << "Base class could not be initialized" << endmsg;
80 
81  // Get hold of the TBBSvc. This should initialize the thread pool
82  m_threadPoolSvc = serviceLocator()->service( "ThreadPoolSvc" );
83  if ( !m_threadPoolSvc.isValid() ) {
84  fatal() << "Error retrieving ThreadPoolSvc" << endmsg;
85  return StatusCode::FAILURE;
86  }
87  auto castTPS = dynamic_cast<ThreadPoolSvc*>( m_threadPoolSvc.get() );
88  if ( !castTPS ) {
89  fatal() << "Cannot cast ThreadPoolSvc" << endmsg;
90  return StatusCode::FAILURE;
91  }
92  m_arena = castTPS->getArena();
93  if ( !m_arena ) {
94  fatal() << "Cannot find valid TBB task_arena" << endmsg;
95  return StatusCode::FAILURE;
96  }
97 
98  // Activate the scheduler in another thread.
99  info() << "Activating scheduler in a separate thread" << endmsg;
100  m_thread = std::thread( [this]() { this->activate(); } );
101 
102  while ( m_isActive != ACTIVE ) {
103  if ( m_isActive == FAILURE ) {
104  fatal() << "Terminating initialization" << endmsg;
105  return StatusCode::FAILURE;
106  } else {
107  ON_DEBUG debug() << "Waiting for AvalancheSchedulerSvc to activate" << endmsg;
108  sleep( 1 );
109  }
110  }
111 
112  if ( m_enableCondSvc ) {
113  // Get hold of the CondSvc
114  m_condSvc = serviceLocator()->service( "CondSvc" );
115  if ( !m_condSvc.isValid() ) {
116  warning() << "No CondSvc found, or not enabled. "
117  << "Will not manage CondAlgorithms" << endmsg;
118  m_enableCondSvc = false;
119  }
120  }
121 
122  // Get the algo resource pool
123  m_algResourcePool = serviceLocator()->service( "AlgResourcePool" );
124  if ( !m_algResourcePool.isValid() ) {
125  fatal() << "Error retrieving AlgoResourcePool" << endmsg;
126  return StatusCode::FAILURE;
127  }
128 
129  m_algExecStateSvc = serviceLocator()->service( "AlgExecStateSvc" );
130  if ( !m_algExecStateSvc.isValid() ) {
131  fatal() << "Error retrieving AlgExecStateSvc" << endmsg;
132  return StatusCode::FAILURE;
133  }
134 
135  // Get Whiteboard
137  if ( !m_whiteboard.isValid() ) {
138  fatal() << "Error retrieving EventDataSvc interface IHiveWhiteBoard." << endmsg;
139  return StatusCode::FAILURE;
140  }
141 
142  // Set the MaxEventsInFlight parameters from the number of WB stores
143  m_maxEventsInFlight = m_whiteboard->getNumberOfStores();
144 
145  // Set the number of free slots
147 
148  // Get the list of algorithms
149  const std::list<IAlgorithm*>& algos = m_algResourcePool->getFlatAlgList();
150  const unsigned int algsNumber = algos.size();
151  if ( algsNumber != 0 ) {
152  info() << "Found " << algsNumber << " algorithms" << endmsg;
153  } else {
154  error() << "No algorithms found" << endmsg;
155  return StatusCode::FAILURE;
156  }
157 
158  /* Dependencies
159  1) Look for handles in algo, if none
160  2) Assume none are required
161  */
162 
163  DataObjIDColl globalInp, globalOutp;
164 
165  // figure out all outputs
166  std::map<std::string, DataObjIDColl> algosOutputDependenciesMap;
167  for ( IAlgorithm* ialgoPtr : algos ) {
168  Gaudi::Algorithm* algoPtr = dynamic_cast<Gaudi::Algorithm*>( ialgoPtr );
169  if ( !algoPtr ) {
170  fatal() << "Could not convert IAlgorithm into Gaudi::Algorithm: this will result in a crash." << endmsg;
171  return StatusCode::FAILURE;
172  }
173 
174  DataObjIDColl algoOutputs;
175  for ( auto id : algoPtr->outputDataObjs() ) {
176  globalOutp.insert( id );
177  algoOutputs.insert( id );
178  }
179  algosOutputDependenciesMap[algoPtr->name()] = algoOutputs;
180  }
181 
182  std::ostringstream ostdd;
183  ostdd << "Data Dependencies for Algorithms:";
184 
185  std::map<std::string, DataObjIDColl> algosInputDependenciesMap;
186  for ( IAlgorithm* ialgoPtr : algos ) {
187  Gaudi::Algorithm* algoPtr = dynamic_cast<Gaudi::Algorithm*>( ialgoPtr );
188  if ( nullptr == algoPtr ) {
189  fatal() << "Could not convert IAlgorithm into Gaudi::Algorithm for " << ialgoPtr->name()
190  << ": this will result in a crash." << endmsg;
191  return StatusCode::FAILURE;
192  }
193 
194  DataObjIDColl i1, i2;
195  DHHVisitor avis( i1, i2 );
196  algoPtr->acceptDHVisitor( &avis );
197 
198  ostdd << "\n " << algoPtr->name();
199 
200  auto write_owners = [&avis, &ostdd]( const DataObjID id ) {
201  auto owners = avis.owners_names_of( id );
202  if ( !owners.empty() ) { GaudiUtils::operator<<( ostdd << ' ', owners ); }
203  };
204 
205  DataObjIDColl algoDependencies;
206  if ( !algoPtr->inputDataObjs().empty() || !algoPtr->outputDataObjs().empty() ) {
207  for ( const DataObjID* idp : sortedDataObjIDColl( algoPtr->inputDataObjs() ) ) {
208  DataObjID id = *idp;
209  ostdd << "\n o INPUT " << id;
210  write_owners( id );
211  if ( id.key().find( ":" ) != std::string::npos ) {
212  ostdd << " contains alternatives which require resolution...\n";
213  auto tokens = boost::tokenizer<boost::char_separator<char>>{ id.key(), boost::char_separator<char>{ ":" } };
214  auto itok = std::find_if( tokens.begin(), tokens.end(), [&]( const std::string& t ) {
215  return globalOutp.find( DataObjID{ t } ) != globalOutp.end();
216  } );
217  if ( itok != tokens.end() ) {
218  ostdd << "found matching output for " << *itok << " -- updating scheduler info\n";
219  id.updateKey( *itok );
220  } else {
221  error() << "failed to find alternate in global output list"
222  << " for id: " << id << " in Alg " << algoPtr->name() << endmsg;
223  m_showDataDeps = true;
224  }
225  }
226  algoDependencies.insert( id );
227  globalInp.insert( id );
228  }
229  for ( const DataObjID* id : sortedDataObjIDColl( algoPtr->outputDataObjs() ) ) {
230  ostdd << "\n o OUTPUT " << *id;
231  write_owners( *id );
232  if ( id->key().find( ":" ) != std::string::npos ) {
233  error() << " in Alg " << algoPtr->name() << " alternatives are NOT allowed for outputs! id: " << *id
234  << endmsg;
235  m_showDataDeps = true;
236  }
237  }
238  } else {
239  ostdd << "\n none";
240  }
241  algosInputDependenciesMap[algoPtr->name()] = algoDependencies;
242  }
243 
244  if ( m_showDataDeps ) { info() << ostdd.str() << endmsg; }
245 
246  // Check if we have unmet global input dependencies, and, optionally, heal them
247  // WARNING: this step must be done BEFORE the Precedence Service is initialized
248  DataObjIDColl unmetDepInp, unusedOutp;
249  if ( m_checkDeps || m_checkOutput ) {
250  std::set<std::string> requiredInputKeys;
251  for ( auto o : globalInp ) {
252  // track aliases
253  // (assuming there should be no items with different class and same key corresponding to different objects)
254  requiredInputKeys.insert( o.key() );
255  if ( globalOutp.find( o ) == globalOutp.end() ) unmetDepInp.insert( o );
256  }
257  if ( m_checkOutput ) {
258  for ( auto o : globalOutp ) {
259  if ( globalInp.find( o ) == globalInp.end() && requiredInputKeys.find( o.key() ) == requiredInputKeys.end() ) {
260  // check ignores
261  bool ignored{};
262  for ( const std::string& algoName : m_checkOutputIgnoreList ) {
263  auto it = algosOutputDependenciesMap.find( algoName );
264  if ( it != algosOutputDependenciesMap.end() ) {
265  if ( it->second.find( o ) != it->second.end() ) {
266  ignored = true;
267  break;
268  }
269  }
270  }
271  if ( !ignored ) { unusedOutp.insert( o ); }
272  }
273  }
274  }
275  }
276 
277  if ( m_checkDeps ) {
278  if ( unmetDepInp.size() > 0 ) {
279 
280  auto printUnmet = [&]( auto msg ) {
281  for ( const DataObjID* o : sortedDataObjIDColl( unmetDepInp ) ) {
282  msg << " o " << *o << " required by Algorithm: " << endmsg;
283 
284  for ( const auto& p : algosInputDependenciesMap )
285  if ( p.second.find( *o ) != p.second.end() ) msg << " * " << p.first << endmsg;
286  }
287  };
288 
289  if ( !m_useDataLoader.empty() ) {
290 
291  // Find the DataLoader Alg
292  IAlgorithm* dataLoaderAlg( nullptr );
293  for ( IAlgorithm* algo : algos )
294  if ( m_useDataLoader == algo->name() ) {
295  dataLoaderAlg = algo;
296  break;
297  }
298 
299  if ( dataLoaderAlg == nullptr ) {
300  fatal() << "No DataLoader Algorithm \"" << m_useDataLoader.value()
301  << "\" found, and unmet INPUT dependencies "
302  << "detected:" << endmsg;
303  printUnmet( fatal() );
304  return StatusCode::FAILURE;
305  }
306 
307  info() << "Will attribute the following unmet INPUT dependencies to \"" << dataLoaderAlg->type() << "/"
308  << dataLoaderAlg->name() << "\" Algorithm" << endmsg;
309  printUnmet( info() );
310 
311  // Set the property Load of DataLoader Alg
312  Gaudi::Algorithm* dataAlg = dynamic_cast<Gaudi::Algorithm*>( dataLoaderAlg );
313  if ( !dataAlg ) {
314  fatal() << "Unable to dcast DataLoader \"" << m_useDataLoader.value() << "\" IAlg to Gaudi::Algorithm"
315  << endmsg;
316  return StatusCode::FAILURE;
317  }
318 
319  for ( auto& id : unmetDepInp ) {
320  ON_DEBUG debug() << "adding OUTPUT dep \"" << id << "\" to " << dataLoaderAlg->type() << "/"
321  << dataLoaderAlg->name() << endmsg;
323  }
324 
325  } else {
326  fatal() << "Auto DataLoading not requested, "
327  << "and the following unmet INPUT dependencies were found:" << endmsg;
328  printUnmet( fatal() );
329  return StatusCode::FAILURE;
330  }
331 
332  } else {
333  info() << "No unmet INPUT data dependencies were found" << endmsg;
334  }
335  }
336 
337  if ( m_checkOutput ) {
338  if ( unusedOutp.size() > 0 ) {
339 
340  auto printUnusedOutp = [&]( auto msg ) {
341  for ( const DataObjID* o : sortedDataObjIDColl( unusedOutp ) ) {
342  msg << " o " << *o << " produced by Algorithm: " << endmsg;
343 
344  for ( const auto& p : algosOutputDependenciesMap )
345  if ( p.second.find( *o ) != p.second.end() ) msg << " * " << p.first << endmsg;
346  }
347  };
348 
349  fatal() << "The following unused OUTPUT items were found:" << endmsg;
350  printUnusedOutp( fatal() );
351  return StatusCode::FAILURE;
352  } else {
353  info() << "No unused OUTPUT items were found" << endmsg;
354  }
355  }
356 
357  // Get the precedence service
358  m_precSvc = serviceLocator()->service( "PrecedenceSvc" );
359  if ( !m_precSvc.isValid() ) {
360  fatal() << "Error retrieving PrecedenceSvc" << endmsg;
361  return StatusCode::FAILURE;
362  }
363  const PrecedenceSvc* precSvc = dynamic_cast<const PrecedenceSvc*>( m_precSvc.get() );
364  if ( !precSvc ) {
365  fatal() << "Unable to dcast PrecedenceSvc" << endmsg;
366  return StatusCode::FAILURE;
367  }
368 
369  // Fill the containers to convert algo names to index
370  m_algname_vect.resize( algsNumber );
371  for ( IAlgorithm* algo : algos ) {
372  const std::string& name = algo->name();
373  auto index = precSvc->getRules()->getAlgorithmNode( name )->getAlgoIndex();
374  m_algname_index_map[name] = index;
375  m_algname_vect.at( index ) = name;
376  }
377 
378  // Shortcut for the message service
379  SmartIF<IMessageSvc> messageSvc( serviceLocator() );
380  if ( !messageSvc.isValid() ) error() << "Error retrieving MessageSvc interface IMessageSvc." << endmsg;
381 
382  m_eventSlots.reserve( m_maxEventsInFlight );
383  for ( size_t i = 0; i < m_maxEventsInFlight; ++i ) {
384  m_eventSlots.emplace_back( algsNumber, precSvc->getRules()->getControlFlowNodeCounter(), messageSvc );
385  m_eventSlots.back().complete = true;
386  }
387 
388  if ( m_threadPoolSize > 1 ) { m_maxAlgosInFlight = (size_t)m_threadPoolSize; }
389 
390  // Clearly inform about the level of concurrency
391  info() << "Concurrency level information:" << endmsg;
392  info() << " o Number of events in flight: " << m_maxEventsInFlight << endmsg;
393  info() << " o TBB thread pool size: " << m_threadPoolSize << endmsg;
394 
395  // Inform about task scheduling prescriptions
396  info() << "Task scheduling settings:" << endmsg;
397  info() << " o Avalanche generation mode: "
398  << ( m_optimizationMode.empty() ? "disabled" : m_optimizationMode.toString() ) << endmsg;
399  info() << " o Preemptive scheduling of CPU-blocking tasks: "
400  << ( m_enablePreemptiveBlockingTasks
401  ? ( "enabled (max. " + std::to_string( m_maxBlockingAlgosInFlight ) + " concurrent tasks)" )
402  : "disabled" )
403  << endmsg;
404  info() << " o Scheduling of condition tasks: " << ( m_enableCondSvc ? "enabled" : "disabled" ) << endmsg;
405 
406  if ( m_showControlFlow ) m_precSvc->dumpControlFlow();
407 
408  if ( m_showDataFlow ) m_precSvc->dumpDataFlow();
409 
410  // Simulate execution flow
411  if ( m_simulateExecution ) sc = m_precSvc->simulate( m_eventSlots[0] );
412 
413  return sc;
414 }
415 //---------------------------------------------------------------------------
416 
421 
423  if ( sc.isFailure() ) warning() << "Base class could not be finalized" << endmsg;
424 
425  sc = deactivate();
426  if ( sc.isFailure() ) warning() << "Scheduler could not be deactivated" << endmsg;
427 
428  info() << "Joining Scheduler thread" << endmsg;
429  m_thread.join();
430 
431  // Final error check after thread pool termination
432  if ( m_isActive == FAILURE ) {
433  error() << "problems in scheduler thread" << endmsg;
434  return StatusCode::FAILURE;
435  }
436 
437  return sc;
438 }
439 //---------------------------------------------------------------------------
440 
452 
453  ON_DEBUG debug() << "AvalancheSchedulerSvc::activate()" << endmsg;
454 
455  if ( m_threadPoolSvc->initPool( m_threadPoolSize ).isFailure() ) {
456  error() << "problems initializing ThreadPoolSvc" << endmsg;
458  return;
459  }
460 
461  // Wait for actions pushed into the queue by finishing tasks.
462  action thisAction;
464 
465  m_isActive = ACTIVE;
466 
467  // Continue to wait if the scheduler is running or there is something to do
468  ON_DEBUG debug() << "Start checking the actionsQueue" << endmsg;
469  while ( m_isActive == ACTIVE || m_actionsQueue.size() != 0 ) {
470  m_actionsQueue.pop( thisAction );
471  sc = thisAction();
472  ON_VERBOSE {
473  if ( sc.isFailure() )
474  verbose() << "Action did not succeed (which is not bad per se)." << endmsg;
475  else
476  verbose() << "Action succeeded." << endmsg;
477  }
478  else sc.ignore();
479 
480  // If all queued actions have been processed, update the slot states
481  if ( m_needsUpdate.load() && m_actionsQueue.empty() ) {
482  sc = iterate();
483  ON_VERBOSE {
484  if ( sc.isFailure() )
485  verbose() << "Iteration did not succeed (which is not bad per se)." << endmsg;
486  else
487  verbose() << "Iteration succeeded." << endmsg;
488  }
489  else sc.ignore();
490  }
491  }
492 
493  ON_DEBUG debug() << "Terminating thread-pool resources" << endmsg;
494  if ( m_threadPoolSvc->terminatePool().isFailure() ) {
495  error() << "Problems terminating thread pool" << endmsg;
497  }
498 }
499 
500 //---------------------------------------------------------------------------
501 
509 
510  if ( m_isActive == ACTIVE ) {
511 
512  // Set the number of slots available to an error code
513  m_freeSlots.store( 0 );
514 
515  // Empty queue
516  action thisAction;
517  while ( m_actionsQueue.try_pop( thisAction ) ) {};
518 
519  // This would be the last action
520  m_actionsQueue.push( [this]() -> StatusCode {
521  ON_VERBOSE verbose() << "Deactivating scheduler" << endmsg;
523  return StatusCode::SUCCESS;
524  } );
525  }
526 
527  return StatusCode::SUCCESS;
528 }
529 
530 //---------------------------------------------------------------------------
531 
532 // EventSlot management
540 
541  if ( !eventContext ) {
542  fatal() << "Event context is nullptr" << endmsg;
543  return StatusCode::FAILURE;
544  }
545 
546  if ( m_freeSlots.load() == 0 ) {
547  ON_DEBUG debug() << "A free processing slot could not be found." << endmsg;
548  return StatusCode::FAILURE;
549  }
550 
551  // no problem as push new event is only called from one thread (event loop manager)
552  --m_freeSlots;
553 
554  auto action = [this, eventContext]() -> StatusCode {
555  // Event processing slot forced to be the same as the wb slot
556  const unsigned int thisSlotNum = eventContext->slot();
557  EventSlot& thisSlot = m_eventSlots[thisSlotNum];
558  if ( !thisSlot.complete ) {
559  fatal() << "The slot " << thisSlotNum << " is supposed to be a finished event but it's not" << endmsg;
560  return StatusCode::FAILURE;
561  }
562 
563  ON_DEBUG debug() << "Executing event " << eventContext->evt() << " on slot " << thisSlotNum << endmsg;
564  thisSlot.reset( eventContext );
565 
566  // Result status code:
568 
569  // promote to CR and DR the initial set of algorithms
570  Cause cs = { Cause::source::Root, "RootDecisionHub" };
571  if ( m_precSvc->iterate( thisSlot, cs ).isFailure() ) {
572  error() << "Failed to call IPrecedenceSvc::iterate for slot " << thisSlotNum << endmsg;
573  result = StatusCode::FAILURE;
574  }
575 
576  if ( this->iterate().isFailure() ) {
577  error() << "Failed to call AvalancheSchedulerSvc::updateStates for slot " << thisSlotNum << endmsg;
578  result = StatusCode::FAILURE;
579  }
580 
581  return result;
582  }; // end of lambda
583 
584  // Kick off scheduling
585  ON_VERBOSE {
586  verbose() << "Pushing the action to update the scheduler for slot " << eventContext->slot() << endmsg;
587  verbose() << "Free slots available " << m_freeSlots.load() << endmsg;
588  }
589 
590  m_actionsQueue.push( action );
591 
592  return StatusCode::SUCCESS;
593 }
594 
595 //---------------------------------------------------------------------------
596 
598  StatusCode sc;
599  for ( auto context : eventContexts ) {
600  sc = pushNewEvent( context );
601  if ( sc != StatusCode::SUCCESS ) return sc;
602  }
603  return sc;
604 }
605 
606 //---------------------------------------------------------------------------
607 
608 unsigned int AvalancheSchedulerSvc::freeSlots() { return std::max( m_freeSlots.load(), 0 ); }
609 
610 //---------------------------------------------------------------------------
615 
616  // ON_DEBUG debug() << "popFinishedEvent: queue size: " << m_finishedEvents.size() << endmsg;
617  if ( m_freeSlots.load() == (int)m_maxEventsInFlight || m_isActive == INACTIVE ) {
618  // ON_DEBUG debug() << "freeslots: " << m_freeSlots << "/" << m_maxEventsInFlight
619  // << " active: " << m_isActive << endmsg;
620  return StatusCode::FAILURE;
621  } else {
622  // ON_DEBUG debug() << "freeslots: " << m_freeSlots << "/" << m_maxEventsInFlight
623  // << " active: " << m_isActive << endmsg;
624  m_finishedEvents.pop( eventContext );
625  ++m_freeSlots;
626  ON_DEBUG debug() << "Popped slot " << eventContext->slot() << " (event " << eventContext->evt() << ")" << endmsg;
627  return StatusCode::SUCCESS;
628  }
629 }
630 
631 //---------------------------------------------------------------------------
636 
637  if ( m_finishedEvents.try_pop( eventContext ) ) {
638  ON_DEBUG debug() << "Try Pop successful slot " << eventContext->slot() << "(event " << eventContext->evt() << ")"
639  << endmsg;
640  ++m_freeSlots;
641  return StatusCode::SUCCESS;
642  }
643  return StatusCode::FAILURE;
644 }
645 
646 //--------------------------------------------------------------------------
647 
656 
657  StatusCode global_sc( StatusCode::SUCCESS );
658 
659  // Retry algorithms
660  const size_t retries = m_retryQueue.size();
661  for ( unsigned int retryIndex = 0; retryIndex < retries; ++retryIndex ) {
662  TaskSpec retryTS = std::move( m_retryQueue.front() );
663  m_retryQueue.pop();
664  global_sc = schedule( std::move( retryTS ) );
665  }
666 
667  // Loop over all slots
668  OccupancySnapshot nextSnap;
669  auto now = std::chrono::system_clock::now();
670  for ( EventSlot& thisSlot : m_eventSlots ) {
671 
672  // Ignore slots without a valid context (relevant when populating scheduler for first time)
673  if ( !thisSlot.eventContext ) continue;
674 
675  int iSlot = thisSlot.eventContext->slot();
676 
677  // Cache the states of the algorithms to improve readability and performance
678  AlgsExecutionStates& thisAlgsStates = thisSlot.algsStates;
679 
680  StatusCode partial_sc = StatusCode::FAILURE;
681 
682  // Make an occupancy snapshot
685 
686  // Initialise snapshot
687  if ( nextSnap.states.empty() ) {
688  nextSnap.time = now;
689  nextSnap.states.resize( m_eventSlots.size() );
690  }
691 
692  // Store alg states
693  std::vector<int>& slotStateTotals = nextSnap.states[iSlot];
694  slotStateTotals.resize( AState::MAXVALUE );
695  for ( uint8_t state = 0; state < AState::MAXVALUE; ++state ) {
696  slotStateTotals[state] = thisSlot.algsStates.sizeOfSubset( AState( state ) );
697  }
698 
699  // Add subslot alg states
700  for ( auto& subslot : thisSlot.allSubSlots ) {
701  for ( uint8_t state = 0; state < AState::MAXVALUE; ++state ) {
702  slotStateTotals[state] += subslot.algsStates.sizeOfSubset( AState( state ) );
703  }
704  }
705  }
706 
707  // Perform DR->SCHEDULED
708  auto& drAlgs = thisAlgsStates.algsInState( AState::DATAREADY );
709  for ( uint algIndex : drAlgs ) {
710  const std::string& algName{ index2algname( algIndex ) };
711  unsigned int rank{ m_optimizationMode.empty() ? 0 : m_precSvc->getPriority( algName ) };
712  bool blocking{ m_enablePreemptiveBlockingTasks ? m_precSvc->isBlocking( algName ) : false };
713 
714  partial_sc =
715  schedule( TaskSpec( nullptr, algIndex, algName, rank, blocking, iSlot, thisSlot.eventContext.get() ) );
716 
717  ON_VERBOSE if ( partial_sc.isFailure() ) verbose()
718  << "Could not apply transition from " << AState::DATAREADY << " for algorithm " << algName
719  << " on processing slot " << iSlot << endmsg;
720  }
721 
722  // Check for algorithms ready in sub-slots
723  for ( auto& subslot : thisSlot.allSubSlots ) {
724  auto& drAlgsSubSlot = subslot.algsStates.algsInState( AState::DATAREADY );
725  for ( uint algIndex : drAlgsSubSlot ) {
726  const std::string& algName{ index2algname( algIndex ) };
727  unsigned int rank{ m_optimizationMode.empty() ? 0 : m_precSvc->getPriority( algName ) };
728  bool blocking{ m_enablePreemptiveBlockingTasks ? m_precSvc->isBlocking( algName ) : false };
729  partial_sc =
730  schedule( TaskSpec( nullptr, algIndex, algName, rank, blocking, iSlot, subslot.eventContext.get() ) );
731  }
732  }
733 
734  if ( m_dumpIntraEventDynamics ) {
736  s << "START, " << thisAlgsStates.sizeOfSubset( AState::CONTROLREADY ) << ", "
737  << thisAlgsStates.sizeOfSubset( AState::DATAREADY ) << ", " << thisAlgsStates.sizeOfSubset( AState::SCHEDULED )
738  << ", " << std::chrono::high_resolution_clock::now().time_since_epoch().count() << "\n";
741  std::ofstream myfile;
742  myfile.open( "IntraEventFSMOccupancy_" + threads + "T.csv", std::ios::app );
743  myfile << s.str();
744  myfile.close();
745  }
746 
747  // Not complete because this would mean that the slot is already free!
748  if ( m_precSvc->CFRulesResolved( thisSlot ) &&
749  !thisSlot.algsStates.containsAny(
750  { AState::CONTROLREADY, AState::DATAREADY, AState::SCHEDULED, AState::RESOURCELESS } ) &&
751  !subSlotAlgsInStates( thisSlot,
752  { AState::CONTROLREADY, AState::DATAREADY, AState::SCHEDULED, AState::RESOURCELESS } ) &&
753  !thisSlot.complete ) {
754 
755  thisSlot.complete = true;
756  // if the event did not fail, add it to the finished events
757  // otherwise it is taken care of in the error handling
758  if ( m_algExecStateSvc->eventStatus( *thisSlot.eventContext ) == EventStatus::Success ) {
759  ON_DEBUG debug() << "Event " << thisSlot.eventContext->evt() << " finished (slot "
760  << thisSlot.eventContext->slot() << ")." << endmsg;
761  m_finishedEvents.push( thisSlot.eventContext.release() );
762  }
763 
764  // now let's return the fully evaluated result of the control flow
765  ON_DEBUG debug() << m_precSvc->printState( thisSlot ) << endmsg;
766 
767  thisSlot.eventContext.reset( nullptr );
768 
769  } else if ( isStalled( thisSlot ) ) {
770  m_algExecStateSvc->setEventStatus( EventStatus::AlgStall, *thisSlot.eventContext );
771  eventFailed( thisSlot.eventContext.get() ); // can't release yet
772  }
773  partial_sc.ignore();
774  } // end loop on slots
775 
776  // Process snapshot
777  if ( !nextSnap.states.empty() ) {
778  m_lastSnapshot = nextSnap.time;
779  m_snapshotCallback( std::move( nextSnap ) );
780  }
781 
782  ON_VERBOSE verbose() << "Iteration done." << endmsg;
783  m_needsUpdate.store( false );
784  return global_sc;
785 }
786 
787 //---------------------------------------------------------------------------
788 // Update algorithm state and, optionally, revise states of other downstream algorithms
789 StatusCode AvalancheSchedulerSvc::revise( unsigned int iAlgo, EventContext* contextPtr, AState state, bool iterate ) {
790  StatusCode sc;
791  auto slotIndex = contextPtr->slot();
792  EventSlot& slot = m_eventSlots[slotIndex];
793  Cause cs = { Cause::source::Task, index2algname( iAlgo ) };
794 
795  if ( contextPtr->usesSubSlot() ) {
796  // Sub-slot
797  auto subSlotIndex = contextPtr->subSlot();
798  EventSlot& subSlot = slot.allSubSlots[subSlotIndex];
799 
800  sc = subSlot.algsStates.set( iAlgo, state );
801 
802  if ( sc.isSuccess() ) {
803  ON_VERBOSE verbose() << "Promoted " << index2algname( iAlgo ) << " to " << state << " [slot:" << slotIndex
804  << ", subslot:" << subSlotIndex << ", event:" << contextPtr->evt() << "]" << endmsg;
805  // Revise states of algorithms downstream the precedence graph
806  if ( iterate ) sc = m_precSvc->iterate( subSlot, cs );
807  }
808  } else {
809  // Event level (standard behaviour)
810  sc = slot.algsStates.set( iAlgo, state );
811 
812  if ( sc.isSuccess() ) {
813  ON_VERBOSE verbose() << "Promoted " << index2algname( iAlgo ) << " to " << state << " [slot:" << slotIndex
814  << ", event:" << contextPtr->evt() << "]" << endmsg;
815  // Revise states of algorithms downstream the precedence graph
816  if ( iterate ) sc = m_precSvc->iterate( slot, cs );
817  }
818  }
819  return sc;
820 }
821 
822 //---------------------------------------------------------------------------
823 
830 bool AvalancheSchedulerSvc::isStalled( const EventSlot& slot ) const {
831 
832  if ( !slot.algsStates.containsAny( { AState::DATAREADY, AState::SCHEDULED, AState::RESOURCELESS } ) &&
833  !subSlotAlgsInStates( slot, { AState::DATAREADY, AState::SCHEDULED, AState::RESOURCELESS } ) ) {
834 
835  error() << "*** Stall detected, event context: " << slot.eventContext.get() << endmsg;
836 
837  return true;
838  }
839  return false;
840 }
841 
842 //---------------------------------------------------------------------------
843 
849  const uint slotIdx = eventContext->slot();
850 
851  error() << "Event " << eventContext->evt() << " on slot " << slotIdx << " failed" << endmsg;
852 
853  dumpSchedulerState( msgLevel( MSG::VERBOSE ) ? -1 : slotIdx );
854 
855  // dump temporal and topological precedence analysis (if enabled in the PrecedenceSvc)
856  m_precSvc->dumpPrecedenceRules( m_eventSlots[slotIdx] );
857 
858  // Push into the finished events queue the failed context
859  m_eventSlots[slotIdx].complete = true;
860  m_finishedEvents.push( m_eventSlots[slotIdx].eventContext.release() );
861 }
862 
863 //---------------------------------------------------------------------------
864 
870 
871  // To have just one big message
872  std::ostringstream outputMS;
873 
874  outputMS << "Dumping scheduler state\n"
875  << "=========================================================================================\n"
876  << "++++++++++++++++++++++++++++++++++++ SCHEDULER STATE ++++++++++++++++++++++++++++++++++++\n"
877  << "=========================================================================================\n\n";
878 
879  //===========================================================================
880 
881  outputMS << "------------------ Last schedule: Task/Event/Slot/Thread/State Mapping "
882  << "------------------\n\n";
883 
884  // Figure if TimelineSvc is available (used below to detect threads IDs)
885  auto timelineSvc = serviceLocator()->service<ITimelineSvc>( "TimelineSvc", false );
886  if ( !timelineSvc.isValid() || !timelineSvc->isEnabled() ) {
887  outputMS << "WARNING Enable TimelineSvc in record mode (RecordTimeline = True) to trace the mapping\n";
888  } else {
889 
890  // Figure optimal printout layout
891  size_t indt( 0 );
892  for ( auto& slot : m_eventSlots ) {
893 
894  auto& schedAlgs = slot.algsStates.algsInState( AState::SCHEDULED );
895  for ( uint algIndex : schedAlgs ) {
896  if ( index2algname( algIndex ).length() > indt ) indt = index2algname( algIndex ).length();
897  }
898  }
899 
900  // Figure the last running schedule across all slots
901  for ( auto& slot : m_eventSlots ) {
902 
903  auto& schedAlgs = slot.algsStates.algsInState( AState::SCHEDULED );
904  for ( uint algIndex : schedAlgs ) {
905 
906  const std::string& algoName{ index2algname( algIndex ) };
907 
908  outputMS << " task: " << std::setw( indt ) << algoName << " evt/slot: " << slot.eventContext->evt() << "/"
909  << slot.eventContext->slot();
910 
911  // Try to get POSIX threads IDs the currently running tasks are scheduled to
912  if ( timelineSvc.isValid() ) {
913  TimelineEvent te{};
914  te.algorithm = algoName;
915  te.slot = slot.eventContext->slot();
916  te.event = slot.eventContext->evt();
917 
918  if ( timelineSvc->getTimelineEvent( te ) )
919  outputMS << " thread.id: 0x" << std::hex << te.thread << std::dec;
920  else
921  outputMS << " thread.id: [unknown]"; // this means a task has just
922  // been signed off as SCHEDULED,
923  // but has not been assigned to a thread yet
924  // (i.e., not running yet)
925  }
926  outputMS << " state: [" << m_algExecStateSvc->algExecState( algoName, *( slot.eventContext ) ) << "]\n";
927  }
928  }
929  }
930 
931  //===========================================================================
932 
933  outputMS << "\n---------------------------- Task/CF/FSM Mapping "
934  << ( 0 > iSlot ? "[all slots] --" : "[target slot] " ) << "--------------------------\n\n";
935 
936  int slotCount = -1;
937  bool wasAlgError = ( iSlot >= 0 ) ? m_eventSlots[iSlot].algsStates.containsAny( { AState::ERROR } ) ||
938  subSlotAlgsInStates( m_eventSlots[iSlot], { AState::ERROR } )
939  : false;
940 
941  for ( auto& slot : m_eventSlots ) {
942  ++slotCount;
943  if ( slot.complete ) continue;
944 
945  outputMS << "[ slot: "
946  << ( slot.eventContext->valid() ? std::to_string( slot.eventContext->slot() ) : "[ctx invalid]" )
947  << " event: "
948  << ( slot.eventContext->valid() ? std::to_string( slot.eventContext->evt() ) : "[ctx invalid]" )
949  << " ]:\n\n";
950 
951  if ( 0 > iSlot || iSlot == slotCount ) {
952 
953  // If an alg has thrown an error then it's not a failure of the CF/DF graph
954  if ( wasAlgError ) {
955  outputMS << "ERROR alg(s):";
956  int errorCount = 0;
957  auto& errorAlgs = slot.algsStates.algsInState( AState::ERROR );
958  for ( uint algIndex : errorAlgs ) {
959  outputMS << " " << index2algname( algIndex );
960  ++errorCount;
961  }
962  if ( errorCount == 0 ) outputMS << " in subslot(s)";
963  outputMS << "\n\n";
964  } else {
965  // Snapshot of the Control Flow and FSM states
966  outputMS << m_precSvc->printState( slot ) << "\n";
967  }
968 
969  // Mention sub slots (this is expensive if the number of sub-slots is high)
970  if ( m_verboseSubSlots && !slot.allSubSlots.empty() ) {
971  outputMS << "\nNumber of sub-slots: " << slot.allSubSlots.size() << "\n\n";
972  auto slotID = slot.eventContext->valid() ? std::to_string( slot.eventContext->slot() ) : "[ctx invalid]";
973  for ( auto& ss : slot.allSubSlots ) {
974  outputMS << "[ slot: " << slotID << ", sub-slot: "
975  << ( ss.eventContext->valid() ? std::to_string( ss.eventContext->subSlot() ) : "[ctx invalid]" )
976  << ", entry: " << ss.entryPoint << ", event: "
977  << ( ss.eventContext->valid() ? std::to_string( ss.eventContext->evt() ) : "[ctx invalid]" )
978  << " ]:\n\n";
979  if ( wasAlgError ) {
980  outputMS << "ERROR alg(s):";
981  auto& errorAlgs = ss.algsStates.algsInState( AState::ERROR );
982  for ( uint algIndex : errorAlgs ) { outputMS << " " << index2algname( algIndex ); }
983  outputMS << "\n\n";
984  } else {
985  // Snapshot of the Control Flow and FSM states in sub slot
986  outputMS << m_precSvc->printState( ss ) << "\n";
987  }
988  }
989  }
990  }
991  }
992 
993  //===========================================================================
994 
995  if ( 0 <= iSlot && !wasAlgError ) {
996  outputMS << "\n------------------------------ Algorithm Execution States -----------------------------\n\n";
997  m_algExecStateSvc->dump( outputMS, *( m_eventSlots[iSlot].eventContext ) );
998  }
999 
1000  outputMS << "\n=========================================================================================\n"
1001  << "++++++++++++++++++++++++++++++++++++++ END OF DUMP ++++++++++++++++++++++++++++++++++++++\n"
1002  << "=========================================================================================\n\n";
1003 
1004  info() << outputMS.str() << endmsg;
1005 }
1006 
1007 //---------------------------------------------------------------------------
1008 
1010 
1011  if ( ts.blocking && m_blockingAlgosInFlight == m_maxBlockingAlgosInFlight ) {
1012  m_retryQueue.push( std::move( ts ) );
1013  return StatusCode::SUCCESS;
1014  }
1015 
1016  // Check if a free Algorithm instance is available
1017  StatusCode getAlgSC( m_algResourcePool->acquireAlgorithm( ts.algName, ts.algPtr ) );
1018 
1019  // If an instance is available, proceed to scheduling
1020  StatusCode sc;
1021  if ( getAlgSC.isSuccess() ) {
1022 
1023  // Decide how to schedule the task and schedule it
1024  if ( -100 != m_threadPoolSize ) {
1025 
1026  // Cache values before moving the TaskSpec further
1027  unsigned int algIndex{ ts.algIndex };
1028  std::string_view algName( ts.algName );
1029  unsigned int algRank{ ts.algRank };
1030  bool blocking{ ts.blocking };
1031  int slotIndex{ ts.slotIndex };
1032  EventContext* contextPtr{ ts.contextPtr };
1033 
1034  if ( !blocking ) {
1035  // Add the algorithm to the scheduled queue
1036  m_scheduledQueue.push( std::move( ts ) );
1037 
1038  // Prepare a TBB task that will execute the Algorithm according to the above queued specs
1039  m_arena->enqueue( AlgTask( this, serviceLocator(), m_algExecStateSvc, false ) );
1040  ++m_algosInFlight;
1041 
1042  } else { // schedule blocking algorithm in independent thread
1044 
1045  // Schedule the blocking task in an independent thread
1047  std::thread _t( AlgTask( this, serviceLocator(), m_algExecStateSvc, true ) );
1048  _t.detach();
1049 
1050  } // end scheduling blocking Algorithm
1051 
1052  sc = revise( algIndex, contextPtr, AState::SCHEDULED );
1053 
1054  ON_DEBUG debug() << "Scheduled " << algName << " [slot:" << slotIndex << ", event:" << contextPtr->evt()
1055  << ", rank:" << algRank << ", blocking:" << ( blocking ? "yes" : "no" )
1056  << "]. Scheduled algorithms: " << m_algosInFlight + m_blockingAlgosInFlight
1058  ? " (including " + std::to_string( m_blockingAlgosInFlight ) + " - off TBB runtime)"
1059  : "" )
1060  << endmsg;
1061 
1062  } else { // Avoid scheduling via TBB if the pool size is -100. Instead, run here in the scheduler's control thread
1063  ++m_algosInFlight;
1064  sc = revise( ts.algIndex, ts.contextPtr, AState::SCHEDULED );
1065  AlgTask( this, serviceLocator(), m_algExecStateSvc, false )();
1066  --m_algosInFlight;
1067  }
1068  } else { // if no Algorithm instance available, retry later
1069 
1070  sc = revise( ts.algIndex, ts.contextPtr, AState::RESOURCELESS );
1071  // Add the algorithm to the retry queue
1072  m_retryQueue.push( std::move( ts ) );
1073  }
1074 
1076 
1077  return sc;
1078 }
1079 
1080 //---------------------------------------------------------------------------
1081 
1086 
1087  Gaudi::Hive::setCurrentContext( ts.contextPtr );
1088 
1089  if ( !ts.blocking )
1090  --m_algosInFlight;
1091  else
1093 
1094  const AlgExecState& algstate = m_algExecStateSvc->algExecState( ts.algPtr, *( ts.contextPtr ) );
1095  AState state = algstate.execStatus().isSuccess()
1096  ? ( algstate.filterPassed() ? AState::EVTACCEPTED : AState::EVTREJECTED )
1097  : AState::ERROR;
1098 
1099  // Update algorithm state and revise the downstream states
1100  auto sc = revise( ts.algIndex, ts.contextPtr, state, true );
1101 
1102  ON_DEBUG debug() << "Executed " << ts.algName << " [slot:" << ts.slotIndex << ", event:" << ts.contextPtr->evt()
1103  << ", rank:" << ts.algRank << ", blocking:" << ( ts.blocking ? "yes" : "no" )
1104  << "]. Scheduled algorithms: " << m_algosInFlight + m_blockingAlgosInFlight
1106  ? " (including " + std::to_string( m_blockingAlgosInFlight ) + " - off TBB runtime)"
1107  : "" )
1108  << endmsg;
1109 
1110  // Prompt a call to updateStates
1111  m_needsUpdate.store( true );
1112  return sc;
1113 }
1114 
1115 //---------------------------------------------------------------------------
1116 
1117 // Method to inform the scheduler about event views
1118 
1120  std::unique_ptr<EventContext> viewContext ) {
1121  // Prevent view nesting
1122  if ( sourceContext->usesSubSlot() ) {
1123  fatal() << "Attempted to nest EventViews at node " << nodeName << ": this is not supported" << endmsg;
1124  return StatusCode::FAILURE;
1125  }
1126 
1127  ON_VERBOSE verbose() << "Queuing a view for [" << viewContext.get() << "]" << endmsg;
1128 
1129  // It's not possible to create an std::functional from a move-capturing lambda
1130  // So, we have to release the unique pointer
1131  auto action = [this, slotIndex = sourceContext->slot(), viewContextPtr = viewContext.release(),
1132  &nodeName]() -> StatusCode {
1133  // Attach the sub-slot to the top-level slot
1134  EventSlot& topSlot = this->m_eventSlots[slotIndex];
1135 
1136  if ( viewContextPtr ) {
1137  // Re-create the unique pointer
1138  auto viewContext = std::unique_ptr<EventContext>( viewContextPtr );
1139  topSlot.addSubSlot( std::move( viewContext ), nodeName );
1140  return StatusCode::SUCCESS;
1141  } else {
1142  // Disable the view node if there are no views
1143  topSlot.disableSubSlots( nodeName );
1144  return StatusCode::SUCCESS;
1145  }
1146  };
1147 
1148  m_actionsQueue.push( std::move( action ) );
1149 
1150  return StatusCode::SUCCESS;
1151 }
1152 
1153 //---------------------------------------------------------------------------
1154 
1155 // Sample occupancy at fixed interval (ms)
1156 // Negative value to deactivate, 0 to snapshot every change
1157 // Each sample, apply the callback function to the result
1158 
1159 void AvalancheSchedulerSvc::recordOccupancy( int samplePeriod, std::function<void( OccupancySnapshot )> callback ) {
1160 
1161  auto action = [this, samplePeriod, callback{ std::move( callback ) }]() -> StatusCode {
1162  if ( samplePeriod < 0 ) {
1164  } else {
1167  }
1168  return StatusCode::SUCCESS;
1169  };
1170 
1171  m_actionsQueue.push( std::move( action ) );
1172 }
IOTest.evt
evt
Definition: IOTest.py:105
EventSlot::eventContext
std::unique_ptr< EventContext > eventContext
Cache for the eventContext.
Definition: EventSlot.h:83
AvalancheSchedulerSvc::m_whiteboard
SmartIF< IHiveWhiteBoard > m_whiteboard
A shortcut to the whiteboard.
Definition: AvalancheSchedulerSvc.h:240
Gaudi::Hive::setCurrentContext
GAUDI_API void setCurrentContext(const EventContext *ctx)
Definition: ThreadLocalContext.cpp:41
PrecedenceSvc
A service to resolve the task execution precedence.
Definition: PrecedenceSvc.h:31
std::vector::resize
T resize(T... args)
Service::initialize
StatusCode initialize() override
Definition: Service.cpp:118
std::string
STL class.
AvalancheSchedulerSvc::TaskSpec
Struct to hold entries in the alg queues.
Definition: AvalancheSchedulerSvc.h:295
AvalancheSchedulerSvc::finalize
StatusCode finalize() override
Finalise.
Definition: AvalancheSchedulerSvc.cpp:420
std::list< IAlgorithm * >
Gaudi::Algorithm::acceptDHVisitor
void acceptDHVisitor(IDataHandleVisitor *) const override
Definition: Algorithm.cpp:188
Read.app
app
Definition: Read.py:36
std::move
T move(T... args)
Gaudi::Algorithm::name
const std::string & name() const override
The identifying name of the algorithm object.
Definition: Algorithm.cpp:528
StatusCode::isSuccess
bool isSuccess() const
Definition: StatusCode.h:314
AvalancheSchedulerSvc::m_optimizationMode
Gaudi::Property< std::string > m_optimizationMode
Definition: AvalancheSchedulerSvc.h:176
std::unordered_set< DataObjID, DataObjID_Hasher >
ON_VERBOSE
#define ON_VERBOSE
Definition: AvalancheSchedulerSvc.cpp:44
AvalancheSchedulerSvc::ACTIVE
@ ACTIVE
Definition: AvalancheSchedulerSvc.h:158
concurrency::PrecedenceRulesGraph::getControlFlowNodeCounter
unsigned int getControlFlowNodeCounter() const
Get total number of control flow graph nodes.
Definition: PrecedenceRulesGraph.h:674
gaudirun.s
string s
Definition: gaudirun.py:348
std::vector
STL class.
std::find_if
T find_if(T... args)
std::unordered_set::size
T size(T... args)
AvalancheSchedulerSvc::iterate
StatusCode iterate()
Loop on all slots to schedule DATAREADY algorithms and sign off ready events.
Definition: AvalancheSchedulerSvc.cpp:655
EventSlot
Class representing an event slot.
Definition: EventSlot.h:24
AlgsExecutionStates
Definition: AlgsExecutionStates.h:38
DataHandleHolderBase::addDependency
void addDependency(const DataObjID &id, const Gaudi::DataHandle::Mode &mode) override
Definition: DataHandleHolderBase.h:86
std::chrono::duration
GaudiMP.FdsRegistry.msg
msg
Definition: FdsRegistry.py:19
AvalancheSchedulerSvc::m_lastSnapshot
std::chrono::system_clock::time_point m_lastSnapshot
Definition: AvalancheSchedulerSvc.h:162
PrecedenceSvc::getRules
const concurrency::PrecedenceRulesGraph * getRules() const
Precedence rules accessor.
Definition: PrecedenceSvc.h:73
std::stringstream
STL class.
std::unique_ptr::get
T get(T... args)
EventStatus::Success
@ Success
Definition: IAlgExecStateSvc.h:73
std::unique_ptr::release
T release(T... args)
ConcurrencyFlags.h
EventContext::usesSubSlot
bool usesSubSlot() const
Definition: EventContext.h:53
std::function
std::any_of
T any_of(T... args)
AvalancheSchedulerSvc::m_scheduledQueue
tbb::concurrent_priority_queue< TaskSpec, AlgQueueSort > m_scheduledQueue
Queues for scheduled algorithms.
Definition: AvalancheSchedulerSvc.h:331
AvalancheSchedulerSvc::schedule
StatusCode schedule(TaskSpec &&)
Definition: AvalancheSchedulerSvc.cpp:1009
AvalancheSchedulerSvc::m_needsUpdate
std::atomic< bool > m_needsUpdate
Definition: AvalancheSchedulerSvc.h:336
DHHVisitor
Definition: DataHandleHolderVisitor.h:21
std::sort
T sort(T... args)
AvalancheSchedulerSvc::m_enableCondSvc
Gaudi::Property< bool > m_enableCondSvc
Definition: AvalancheSchedulerSvc.h:197
AvalancheSchedulerSvc::deactivate
StatusCode deactivate()
Deactivate scheduler.
Definition: AvalancheSchedulerSvc.cpp:508
CommonMessaging< implements< IService, IProperty, IStateful > >::msgLevel
MSG::Level msgLevel() const
get the cached level (originally extracted from the embedded MsgStream)
Definition: CommonMessaging.h:148
Service::finalize
StatusCode finalize() override
Definition: Service.cpp:222
ThreadPoolSvc.h
AvalancheSchedulerSvc::m_eventSlots
std::vector< EventSlot > m_eventSlots
Vector of events slots.
Definition: AvalancheSchedulerSvc.h:243
Gaudi::DataHandle::Writer
@ Writer
Definition: DataHandle.h:40
std::thread::detach
T detach(T... args)
AvalancheSchedulerSvc::m_arena
tbb::task_arena * m_arena
Definition: AvalancheSchedulerSvc.h:342
AvalancheSchedulerSvc::m_algExecStateSvc
SmartIF< IAlgExecStateSvc > m_algExecStateSvc
Algorithm execution state manager.
Definition: AvalancheSchedulerSvc.h:252
EventSlot::complete
bool complete
Flags completion of the event.
Definition: EventSlot.h:89
DataObjID::fullKey
std::string fullKey() const
combination of the key and the ClassName, mostly for debugging
Definition: DataObjID.cpp:99
std::hex
T hex(T... args)
AvalancheSchedulerSvc::FAILURE
@ FAILURE
Definition: AvalancheSchedulerSvc.h:158
AvalancheSchedulerSvc::m_condSvc
SmartIF< ICondSvc > m_condSvc
A shortcut to service for Conditions handling.
Definition: AvalancheSchedulerSvc.h:255
AvalancheSchedulerSvc::eventFailed
void eventFailed(EventContext *eventContext)
Method to execute if an event failed.
Definition: AvalancheSchedulerSvc.cpp:848
TimelineEvent
Definition: ITimelineSvc.h:23
AvalancheSchedulerSvc::m_threadPoolSize
Gaudi::Property< int > m_threadPoolSize
Definition: AvalancheSchedulerSvc.h:165
bug_34121.t
t
Definition: bug_34121.py:30
DHHVisitor::owners_names_of
std::vector< std::string > owners_names_of(const DataObjID &id, bool with_main=false) const
Definition: DataHandleHolderVisitor.cpp:82
EventSlot::addSubSlot
void addSubSlot(std::unique_ptr< EventContext > viewContext, const std::string &nodeName)
Add a subslot to the slot (this constructs a new slot and registers it with the parent one)
Definition: EventSlot.h:61
EventStatus::AlgStall
@ AlgStall
Definition: IAlgExecStateSvc.h:73
AvalancheSchedulerSvc::m_maxEventsInFlight
size_t m_maxEventsInFlight
Definition: AvalancheSchedulerSvc.h:343
SmartIF::isValid
bool isValid() const
Allow for check if smart pointer is valid.
Definition: SmartIF.h:72
AvalancheSchedulerSvc::m_maxBlockingAlgosInFlight
Gaudi::Property< unsigned int > m_maxBlockingAlgosInFlight
Definition: AvalancheSchedulerSvc.h:171
TimingHistograms.name
name
Definition: TimingHistograms.py:25
GaudiUtils::operator<<
std::ostream & operator<<(std::ostream &s, const std::pair< T1, T2 > &p)
Serialize an std::pair in a python like format. E.g. "(1, 2)".
Definition: SerializeSTL.h:88
StatusCode
Definition: StatusCode.h:65
std::thread
STL class.
AlgTask.h
ITimelineSvc
Definition: ITimelineSvc.h:37
IAlgorithm
Definition: IAlgorithm.h:38
std::atomic::load
T load(T... args)
std::thread::hardware_concurrency
T hardware_concurrency(T... args)
std::ofstream
STL class.
compareRootHistos.ts
ts
Definition: compareRootHistos.py:490
EventContext::slot
ContextID_t slot() const
Definition: EventContext.h:51
AvalancheSchedulerSvc::m_enablePreemptiveBlockingTasks
Gaudi::Property< bool > m_enablePreemptiveBlockingTasks
Definition: AvalancheSchedulerSvc.h:180
Gaudi::Algorithm
Base class from which all concrete algorithm classes should be derived.
Definition: Algorithm.h:90
AvalancheSchedulerSvc::m_whiteboardSvcName
Gaudi::Property< std::string > m_whiteboardSvcName
Definition: AvalancheSchedulerSvc.h:170
AvalancheSchedulerSvc
Definition: AvalancheSchedulerSvc.h:112
EventSlot::reset
void reset(EventContext *theeventContext)
Reset all resources in order to reuse the slot (thread-unsafe)
Definition: EventSlot.h:49
DataHandleHolderVisitor.h
std::to_string
T to_string(T... args)
EventSlot::disableSubSlots
void disableSubSlots(const std::string &nodeName)
Disable event views for a given CF view node by registering an empty container Contact B.
Definition: EventSlot.h:78
AlgExecState::execStatus
const StatusCode & execStatus() const
Definition: IAlgExecStateSvc.h:43
std::ofstream::close
T close(T... args)
AvalancheSchedulerSvc::m_scheduledBlockingQueue
tbb::concurrent_priority_queue< TaskSpec, AlgQueueSort > m_scheduledBlockingQueue
Definition: AvalancheSchedulerSvc.h:332
AvalancheSchedulerSvc::recordOccupancy
virtual void recordOccupancy(int samplePeriod, std::function< void(OccupancySnapshot)> callback) override
Sample occupancy at fixed interval (ms) Negative value to deactivate, 0 to snapshot every change Each...
Definition: AvalancheSchedulerSvc.cpp:1159
AvalancheSchedulerSvc::index2algname
const std::string & index2algname(unsigned int index)
Convert an integer to a name.
Definition: AvalancheSchedulerSvc.h:231
Algorithm.h
EventSlot::allSubSlots
std::vector< EventSlot > allSubSlots
Actual sub-slot instances.
Definition: EventSlot.h:100
AvalancheSchedulerSvc::AState
AlgsExecutionStates::State AState
Definition: AvalancheSchedulerSvc.h:155
AvalancheSchedulerSvc::INACTIVE
@ INACTIVE
Definition: AvalancheSchedulerSvc.h:158
std::ofstream::open
T open(T... args)
SmartIF< IMessageSvc >
genconfuser.verbose
verbose
Definition: genconfuser.py:29
AvalancheSchedulerSvc::m_algosInFlight
unsigned int m_algosInFlight
Number of algorithms presently in flight.
Definition: AvalancheSchedulerSvc.h:258
endmsg
MsgStream & endmsg(MsgStream &s)
MsgStream Modifier: endmsg. Calls the output method of the MsgStream.
Definition: MsgStream.h:203
std::map
STL class.
AvalancheSchedulerSvc::tryPopFinishedEvent
StatusCode tryPopFinishedEvent(EventContext *&eventContext) override
Try to fetch an event from the scheduler.
Definition: AvalancheSchedulerSvc.cpp:635
AvalancheSchedulerSvc::scheduleEventView
virtual StatusCode scheduleEventView(const EventContext *sourceContext, const std::string &nodeName, std::unique_ptr< EventContext > viewContext) override
Method to inform the scheduler about event views.
Definition: AvalancheSchedulerSvc.cpp:1119
AvalancheSchedulerSvc::m_algResourcePool
SmartIF< IAlgResourcePool > m_algResourcePool
Cache for the algorithm resource pool.
Definition: AvalancheSchedulerSvc.h:287
AvalancheSchedulerSvc::freeSlots
unsigned int freeSlots() override
Get free slots number.
Definition: AvalancheSchedulerSvc.cpp:608
Cause::source::Root
@ Root
AvalancheSchedulerSvc::m_showDataDeps
Gaudi::Property< bool > m_showDataDeps
Definition: AvalancheSchedulerSvc.h:199
DataObjID
Definition: DataObjID.h:47
AvalancheSchedulerSvc::initialize
StatusCode initialize() override
Initialise.
Definition: AvalancheSchedulerSvc.cpp:75
AlgsExecutionStates::containsAny
bool containsAny(std::initializer_list< State > l) const
check if the collection contains at least one state of any listed types
Definition: AlgsExecutionStates.h:75
StatusCode::ignore
const StatusCode & ignore() const
Allow discarding a StatusCode without warning.
Definition: StatusCode.h:139
std::chrono::duration::min
T min(T... args)
HistoDumpEx.v
v
Definition: HistoDumpEx.py:27
std::ostringstream
STL class.
ON_DEBUG
#define ON_DEBUG
Definition: AvalancheSchedulerSvc.cpp:43
StatusCode::isFailure
bool isFailure() const
Definition: StatusCode.h:129
ThreadLocalContext.h
concurrency::PrecedenceRulesGraph::getAlgorithmNode
AlgorithmNode * getAlgorithmNode(const std::string &algoName) const
Get the AlgorithmNode from by algorithm name using graph index.
Definition: PrecedenceRulesGraph.h:666
AvalancheSchedulerSvc::m_dumpIntraEventDynamics
Gaudi::Property< bool > m_dumpIntraEventDynamics
Definition: AvalancheSchedulerSvc.h:178
AlgsExecutionStates::set
StatusCode set(unsigned int iAlgo, State newState)
Definition: AlgsExecutionStates.cpp:23
AvalancheSchedulerSvc::m_retryQueue
std::queue< TaskSpec > m_retryQueue
Definition: AvalancheSchedulerSvc.h:333
MSG::VERBOSE
@ VERBOSE
Definition: IMessageSvc.h:25
StatusCode::SUCCESS
constexpr static const auto SUCCESS
Definition: StatusCode.h:100
EventContext::subSlot
ContextID_t subSlot() const
Definition: EventContext.h:52
Cause::source::Task
@ Task
SmartIF::get
TYPE * get() const
Get interface pointer.
Definition: SmartIF.h:86
AtlasMCRecoScenario.threads
threads
Definition: AtlasMCRecoScenario.py:29
DataHandleHolderBase::outputDataObjs
const DataObjIDColl & outputDataObjs() const override
Definition: DataHandleHolderBase.h:84
AvalancheSchedulerSvc::m_snapshotInterval
std::chrono::duration< int64_t, std::milli > m_snapshotInterval
Definition: AvalancheSchedulerSvc.h:161
std::vector::begin
T begin(T... args)
std
STL namespace.
DECLARE_COMPONENT
#define DECLARE_COMPONENT(type)
Definition: PluginServiceV1.h:46
std::unordered_set::insert
T insert(T... args)
AvalancheSchedulerSvc::m_threadPoolSvc
SmartIF< IThreadPoolSvc > m_threadPoolSvc
Definition: AvalancheSchedulerSvc.h:341
MSG::ERROR
@ ERROR
Definition: IMessageSvc.h:25
EventContext
Definition: EventContext.h:34
AlgsExecutionStates::State
State
Execution states of the algorithms Must have contiguous integer values 0, 1...
Definition: AlgsExecutionStates.h:42
concurrency::AlgorithmNode::getAlgoIndex
const unsigned int & getAlgoIndex() const
Get algorithm index.
Definition: PrecedenceRulesGraph.h:525
TimelineEvent::algorithm
std::string algorithm
Definition: ITimelineSvc.h:31
AvalancheSchedulerSvc::revise
StatusCode revise(unsigned int iAlgo, EventContext *contextPtr, AState state, bool iterate=false)
Definition: AvalancheSchedulerSvc.cpp:789
AlgExecState::filterPassed
bool filterPassed() const
Definition: IAlgExecStateSvc.h:41
AvalancheSchedulerSvc::activate
void activate()
Activate scheduler.
Definition: AvalancheSchedulerSvc.cpp:451
AvalancheSchedulerSvc::m_actionsQueue
tbb::concurrent_bounded_queue< action > m_actionsQueue
Queue where closures are stored and picked for execution.
Definition: AvalancheSchedulerSvc.h:292
std::unordered_set::empty
T empty(T... args)
AvalancheSchedulerSvc::isStalled
bool isStalled(const EventSlot &) const
Check if scheduling in a particular slot is in a stall.
Definition: AvalancheSchedulerSvc.cpp:830
AvalancheSchedulerSvc::AlgTask
friend class AlgTask
Definition: AvalancheSchedulerSvc.h:114
std::atomic::store
T store(T... args)
SerializeSTL.h
DataHandleHolderBase::inputDataObjs
const DataObjIDColl & inputDataObjs() const override
Definition: DataHandleHolderBase.h:83
AvalancheSchedulerSvc::m_thread
std::thread m_thread
The thread in which the activate function runs.
Definition: AvalancheSchedulerSvc.h:222
std::vector::end
T end(T... args)
AvalancheSchedulerSvc::pushNewEvents
StatusCode pushNewEvents(std::vector< EventContext * > &eventContexts) override
Definition: AvalancheSchedulerSvc.cpp:597
IAlgorithm.h
AlgExecState
Definition: IAlgExecStateSvc.h:37
std::setw
T setw(T... args)
StatusCode::FAILURE
constexpr static const auto FAILURE
Definition: StatusCode.h:101
std::max
T max(T... args)
AvalancheSchedulerSvc::signoff
StatusCode signoff(const TaskSpec &)
The call to this method is triggered only from within the AlgTask.
Definition: AvalancheSchedulerSvc.cpp:1085
AlgsExecutionStates::sizeOfSubset
size_t sizeOfSubset(State state) const
Definition: AlgsExecutionStates.h:89
AvalancheSchedulerSvc::m_freeSlots
std::atomic_int m_freeSlots
Atomic to account for asyncronous updates by the scheduler wrt the rest.
Definition: AvalancheSchedulerSvc.h:246
compareRootHistos.state
state
Definition: compareRootHistos.py:498
AvalancheSchedulerSvc::m_blockingAlgosInFlight
unsigned int m_blockingAlgosInFlight
Number of algorithms presently in flight.
Definition: AvalancheSchedulerSvc.h:261
AvalancheSchedulerSvc::m_snapshotCallback
std::function< void(OccupancySnapshot)> m_snapshotCallback
Definition: AvalancheSchedulerSvc.h:163
AvalancheSchedulerSvc::pushNewEvent
StatusCode pushNewEvent(EventContext *eventContext) override
Make an event available to the scheduler.
Definition: AvalancheSchedulerSvc.cpp:539
AvalancheSchedulerSvc::popFinishedEvent
StatusCode popFinishedEvent(EventContext *&eventContext) override
Blocks until an event is available.
Definition: AvalancheSchedulerSvc.cpp:614
AlgsExecutionStates::algsInState
const boost::container::flat_set< int > algsInState(State state) const
Definition: AlgsExecutionStates.h:83
std::unique_ptr< EventContext >
ProduceConsume.key
key
Definition: ProduceConsume.py:81
EventSlot::algsStates
AlgsExecutionStates algsStates
Vector of algorithms states.
Definition: EventSlot.h:85
Cause
Definition: PrecedenceRulesGraph.h:399
AvalancheSchedulerSvc::m_precSvc
SmartIF< IPrecedenceSvc > m_precSvc
A shortcut to the Precedence Service.
Definition: AvalancheSchedulerSvc.h:237
AvalancheSchedulerSvc::m_isActive
std::atomic< ActivationState > m_isActive
Flag to track if the scheduler is active or not.
Definition: AvalancheSchedulerSvc.h:219
AvalancheSchedulerSvc::m_finishedEvents
tbb::concurrent_bounded_queue< EventContext * > m_finishedEvents
Queue of finished events.
Definition: AvalancheSchedulerSvc.h:249
std::set< std::string >
EventContext::evt
ContextEvt_t evt() const
Definition: EventContext.h:50
AvalancheSchedulerSvc::dumpSchedulerState
void dumpSchedulerState(int iSlot)
Dump the state of the scheduler.
Definition: AvalancheSchedulerSvc.cpp:869
IDataManagerSvc.h
std::thread::join
T join(T... args)
Service::serviceLocator
SmartIF< ISvcLocator > & serviceLocator() const override
Retrieve pointer to service locator
Definition: Service.cpp:335
AvalancheSchedulerSvc.h
ThreadPoolSvc
A service which initializes a TBB thread pool.
Definition: ThreadPoolSvc.h:38
std::initializer_list
gaudirun.callback
callback
Definition: gaudirun.py:204
std::chrono::system_clock::now
T now(T... args)