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