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