The Gaudi Framework  master (f31ba9ee)
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 // figure out all outputs
177 std::map<std::string, DataObjIDColl> algosOutputDependenciesMap;
178 for ( IAlgorithm* ialgoPtr : algos ) {
179 Gaudi::Algorithm* algoPtr = dynamic_cast<Gaudi::Algorithm*>( ialgoPtr );
180 if ( !algoPtr ) {
181 fatal() << "Could not convert IAlgorithm into Gaudi::Algorithm: this will result in a crash." << endmsg;
182 return StatusCode::FAILURE;
183 }
184
185 DataObjIDColl algoOutputs;
186 for ( auto id : algoPtr->outputDataObjs() ) {
187 globalOutp.insert( id );
188 algoOutputs.insert( id );
189 }
190 algosOutputDependenciesMap[algoPtr->name()] = algoOutputs;
191 }
192
193 std::ostringstream ostdd;
194 ostdd << "Data Dependencies for Algorithms:";
195
196 std::map<std::string, DataObjIDColl> algosInputDependenciesMap;
197 for ( IAlgorithm* ialgoPtr : algos ) {
198 Gaudi::Algorithm* algoPtr = dynamic_cast<Gaudi::Algorithm*>( ialgoPtr );
199 if ( nullptr == algoPtr ) {
200 fatal() << "Could not convert IAlgorithm into Gaudi::Algorithm for " << ialgoPtr->name()
201 << ": this will result in a crash." << endmsg;
202 return StatusCode::FAILURE;
203 }
204
205 DataObjIDColl i1, i2;
206 DHHVisitor avis( i1, i2 );
207 algoPtr->acceptDHVisitor( &avis );
208
209 ostdd << "\n " << algoPtr->name();
210
211 auto write_owners = [&avis, &ostdd]( const DataObjID& id ) {
212 auto owners = avis.owners_names_of( id );
213 if ( !owners.empty() ) { GaudiUtils::operator<<( ostdd << ' ', owners ); }
214 };
215
216 DataObjIDColl algoDependencies;
217 if ( !algoPtr->inputDataObjs().empty() || !algoPtr->outputDataObjs().empty() ) {
218 for ( const DataObjID* idp : sortedDataObjIDColl( algoPtr->inputDataObjs() ) ) {
219 DataObjID id = *idp;
220 ostdd << "\n o INPUT " << id;
221 write_owners( id );
222 algoDependencies.insert( id );
223 globalInp.insert( id );
224 }
225 for ( const DataObjID* id : sortedDataObjIDColl( algoPtr->outputDataObjs() ) ) {
226 ostdd << "\n o OUTPUT " << *id;
227 write_owners( *id );
228 if ( id->key().find( ":" ) != std::string::npos ) {
229 error() << " in Alg " << algoPtr->name() << " alternatives are NOT allowed for outputs! id: " << *id
230 << endmsg;
231 m_showDataDeps = true;
232 }
233 }
234 } else {
235 ostdd << "\n none";
236 }
237 algosInputDependenciesMap[algoPtr->name()] = algoDependencies;
238 }
239
240 if ( m_showDataDeps ) { info() << ostdd.str() << endmsg; }
241
242 // If requested, dump a graph of the data dependencies in a .dot, .md or .graphml file
243 if ( not m_dataDepsGraphFile.empty() ) {
244 if ( dumpDataDepsGraphFile( algosInputDependenciesMap, algosOutputDependenciesMap ).isFailure() ) {
245 return StatusCode::FAILURE;
246 }
247 }
248
249 // Check if we have unmet global input dependencies, and, optionally, heal them
250 // WARNING: this step must be done BEFORE the Precedence Service is initialized
251 DataObjIDColl unmetDepInp, unusedOutp;
252 if ( m_checkDeps || m_checkOutput ) {
253 std::set<std::string> requiredInputKeys;
254 for ( auto o : globalInp ) {
255 // track aliases
256 // (assuming there should be no items with different class and same key corresponding to different objects)
257 requiredInputKeys.insert( o.key() );
258 if ( globalOutp.find( o ) == globalOutp.end() ) unmetDepInp.insert( o );
259 }
260 if ( m_checkOutput ) {
261 for ( auto o : globalOutp ) {
262 if ( globalInp.find( o ) == globalInp.end() && requiredInputKeys.find( o.key() ) == requiredInputKeys.end() ) {
263 // check ignores
264 bool ignored{};
265 for ( const std::string& algoName : m_checkOutputIgnoreList ) {
266 auto it = algosOutputDependenciesMap.find( algoName );
267 if ( it != algosOutputDependenciesMap.end() ) {
268 if ( it->second.find( o ) != it->second.end() ) {
269 ignored = true;
270 break;
271 }
272 }
273 }
274 if ( !ignored ) { unusedOutp.insert( o ); }
275 }
276 }
277 }
278 }
279
280 if ( m_checkDeps ) {
281 if ( unmetDepInp.size() > 0 ) {
282
283 auto printUnmet = [&]( auto msg ) {
284 for ( const DataObjID* o : sortedDataObjIDColl( unmetDepInp ) ) {
285 msg << " o " << *o << " required by Algorithm: " << endmsg;
286
287 for ( const auto& p : algosInputDependenciesMap )
288 if ( p.second.find( *o ) != p.second.end() ) msg << " * " << p.first << endmsg;
289 }
290 };
291
292 if ( !m_useDataLoader.empty() ) {
293
294 // Find the DataLoader Alg
295 IAlgorithm* dataLoaderAlg( nullptr );
296 for ( IAlgorithm* algo : algos )
297 if ( m_useDataLoader == algo->name() ) {
298 dataLoaderAlg = algo;
299 break;
300 }
301
302 if ( dataLoaderAlg == nullptr ) {
303 fatal() << "No DataLoader Algorithm \"" << m_useDataLoader.value()
304 << "\" found, and unmet INPUT dependencies "
305 << "detected:" << endmsg;
306 printUnmet( fatal() );
307 return StatusCode::FAILURE;
308 }
309
310 info() << "Will attribute the following unmet INPUT dependencies to \"" << dataLoaderAlg->type() << "/"
311 << dataLoaderAlg->name() << "\" Algorithm" << endmsg;
312 printUnmet( info() );
313
314 // Set the property Load of DataLoader Alg
315 Gaudi::Algorithm* dataAlg = dynamic_cast<Gaudi::Algorithm*>( dataLoaderAlg );
316 if ( !dataAlg ) {
317 fatal() << "Unable to dcast DataLoader \"" << m_useDataLoader.value() << "\" IAlg to Gaudi::Algorithm"
318 << endmsg;
319 return StatusCode::FAILURE;
320 }
321
322 for ( auto& id : unmetDepInp ) {
323 ON_DEBUG debug() << "adding OUTPUT dep \"" << id << "\" to " << dataLoaderAlg->type() << "/"
324 << dataLoaderAlg->name() << endmsg;
326 }
327
328 } else {
329 fatal() << "Auto DataLoading not requested, "
330 << "and the following unmet INPUT dependencies were found:" << endmsg;
331 printUnmet( fatal() );
332 return StatusCode::FAILURE;
333 }
334
335 } else {
336 info() << "No unmet INPUT data dependencies were found" << endmsg;
337 }
338 }
339
340 if ( m_checkOutput ) {
341 if ( unusedOutp.size() > 0 ) {
342
343 auto printUnusedOutp = [&]( auto msg ) {
344 for ( const DataObjID* o : sortedDataObjIDColl( unusedOutp ) ) {
345 msg << " o " << *o << " produced by Algorithm: " << endmsg;
346
347 for ( const auto& p : algosOutputDependenciesMap )
348 if ( p.second.find( *o ) != p.second.end() ) msg << " * " << p.first << endmsg;
349 }
350 };
351
352 fatal() << "The following unused OUTPUT items were found:" << endmsg;
353 printUnusedOutp( fatal() );
354 return StatusCode::FAILURE;
355 } else {
356 info() << "No unused OUTPUT items were found" << endmsg;
357 }
358 }
359
360 // Get the precedence service
361 m_precSvc = serviceLocator()->service( "PrecedenceSvc" );
362 if ( !m_precSvc.isValid() ) {
363 fatal() << "Error retrieving PrecedenceSvc" << endmsg;
364 return StatusCode::FAILURE;
365 }
366 const PrecedenceSvc* precSvc = dynamic_cast<const PrecedenceSvc*>( m_precSvc.get() );
367 if ( !precSvc ) {
368 fatal() << "Unable to dcast PrecedenceSvc" << endmsg;
369 return StatusCode::FAILURE;
370 }
371
372 // Fill the containers to convert algo names to index
373 m_algname_vect.resize( algsNumber );
374 for ( IAlgorithm* algo : algos ) {
375 const std::string& name = algo->name();
376 auto index = precSvc->getRules()->getAlgorithmNode( name )->getAlgoIndex();
377 m_algname_index_map[name] = index;
378 m_algname_vect.at( index ) = name;
379 }
380
381 // Shortcut for the message service
382 SmartIF<IMessageSvc> messageSvc( serviceLocator() );
383 if ( !messageSvc.isValid() ) error() << "Error retrieving MessageSvc interface IMessageSvc." << endmsg;
384
386 for ( size_t i = 0; i < m_maxEventsInFlight; ++i ) {
387 m_eventSlots.emplace_back( algsNumber, precSvc->getRules()->getControlFlowNodeCounter(), messageSvc );
388 m_eventSlots.back().complete = true;
389 }
390
391 // Clearly inform about the level of concurrency
392 info() << "Concurrency level information:" << endmsg;
393 info() << " o Number of events in flight: " << m_maxEventsInFlight << endmsg;
394 info() << " o TBB thread pool size: " << m_threadPoolSize << endmsg;
395 info() << " o Fiber thread pool size: " << m_numOffloadThreads << endmsg;
396
397 // Inform about task scheduling prescriptions
398 info() << "Task scheduling settings:" << endmsg;
399 info() << " o Avalanche generation mode: "
400 << ( m_optimizationMode.empty() ? "disabled" : m_optimizationMode.toString() ) << endmsg;
401 info() << " o Scheduling of condition tasks: " << ( m_enableCondSvc ? "enabled" : "disabled" ) << endmsg;
402
403 if ( m_showControlFlow ) m_precSvc->dumpControlFlow();
404
405 if ( m_showDataFlow ) m_precSvc->dumpDataFlow();
406
407 // Simulate execution flow
408 if ( m_simulateExecution ) sc = m_precSvc->simulate( m_eventSlots[0] );
409
410 return sc;
411}
412//---------------------------------------------------------------------------
413
418
420 if ( sc.isFailure() ) warning() << "Base class could not be finalized" << endmsg;
421
422 sc = deactivate();
423 if ( sc.isFailure() ) warning() << "Scheduler could not be deactivated" << endmsg;
424
425 debug() << "Deleting FiberManager" << endmsg;
426 m_fiberManager.reset();
427
428 info() << "Joining Scheduler thread" << endmsg;
429 m_thread.join();
430
431 // Final error check after thread pool termination
432 if ( m_isActive == FAILURE ) {
433 error() << "problems in scheduler thread" << endmsg;
434 return StatusCode::FAILURE;
435 }
436
437 return sc;
438}
439//---------------------------------------------------------------------------
440
452
453 ON_DEBUG debug() << "AvalancheSchedulerSvc::activate()" << endmsg;
454
455 if ( m_threadPoolSvc->initPool( m_threadPoolSize, m_maxParallelismExtra ).isFailure() ) {
456 error() << "problems initializing ThreadPoolSvc" << endmsg;
458 return;
459 }
460
461 // Wait for actions pushed into the queue by finishing tasks.
462 action thisAction;
464
466
467 // Continue to wait if the scheduler is running or there is something to do
468 ON_DEBUG debug() << "Start checking the actionsQueue" << endmsg;
469 while ( m_isActive == ACTIVE || m_actionsQueue.size() != 0 ) {
470 m_actionsQueue.pop( thisAction );
471 sc = thisAction();
472 ON_VERBOSE {
473 if ( sc.isFailure() )
474 verbose() << "Action did not succeed (which is not bad per se)." << endmsg;
475 else
476 verbose() << "Action succeeded." << endmsg;
477 }
478 else sc.ignore();
479
480 // If all queued actions have been processed, update the slot states
481 if ( m_needsUpdate.load() && m_actionsQueue.empty() ) {
482 sc = iterate();
483 ON_VERBOSE {
484 if ( sc.isFailure() )
485 verbose() << "Iteration did not succeed (which is not bad per se)." << endmsg;
486 else
487 verbose() << "Iteration succeeded." << endmsg;
488 }
489 else sc.ignore();
490 }
491 }
492
493 ON_DEBUG debug() << "Terminating thread-pool resources" << endmsg;
494 if ( m_threadPoolSvc->terminatePool().isFailure() ) {
495 error() << "Problems terminating thread pool" << endmsg;
497 }
498}
499
500//---------------------------------------------------------------------------
501
509
510 if ( m_isActive == ACTIVE ) {
511
512 // Set the number of slots available to an error code
513 m_freeSlots.store( 0 );
514
515 // Empty queue
516 action thisAction;
517 while ( m_actionsQueue.try_pop( thisAction ) ) {};
518
519 // This would be the last action
520 m_actionsQueue.push( [this]() -> StatusCode {
521 ON_VERBOSE verbose() << "Deactivating scheduler" << endmsg;
523 return StatusCode::SUCCESS;
524 } );
525 }
526
527 return StatusCode::SUCCESS;
528}
529
530//---------------------------------------------------------------------------
531
532// EventSlot management
540
541 if ( !eventContext ) {
542 fatal() << "Event context is nullptr" << endmsg;
543 return StatusCode::FAILURE;
544 }
545
546 if ( m_freeSlots.load() == 0 ) {
547 ON_DEBUG debug() << "A free processing slot could not be found." << endmsg;
548 return StatusCode::FAILURE;
549 }
550
551 // no problem as push new event is only called from one thread (event loop manager)
552 --m_freeSlots;
553
554 auto action = [this, eventContext]() -> StatusCode {
555 // Event processing slot forced to be the same as the wb slot
556 const unsigned int thisSlotNum = eventContext->slot();
557 EventSlot& thisSlot = m_eventSlots[thisSlotNum];
558 if ( !thisSlot.complete ) {
559 fatal() << "The slot " << thisSlotNum << " is supposed to be a finished event but it's not" << endmsg;
560 return StatusCode::FAILURE;
561 }
562
563 ON_DEBUG debug() << "Executing event " << eventContext->evt() << " on slot " << thisSlotNum << endmsg;
564 thisSlot.reset( eventContext );
565
566 // Result status code:
568
569 // promote to CR and DR the initial set of algorithms
570 Cause cs = { Cause::source::Root, "RootDecisionHub" };
571 if ( m_precSvc->iterate( thisSlot, cs ).isFailure() ) {
572 error() << "Failed to call IPrecedenceSvc::iterate for slot " << thisSlotNum << endmsg;
573 result = StatusCode::FAILURE;
574 }
575
576 if ( this->iterate().isFailure() ) {
577 error() << "Failed to call AvalancheSchedulerSvc::updateStates for slot " << thisSlotNum << endmsg;
578 result = StatusCode::FAILURE;
579 }
580
581 return result;
582 }; // end of lambda
583
584 // Kick off scheduling
585 ON_VERBOSE {
586 verbose() << "Pushing the action to update the scheduler for slot " << eventContext->slot() << endmsg;
587 verbose() << "Free slots available " << m_freeSlots.load() << endmsg;
588 }
589
590 m_actionsQueue.push( action );
591
592 return StatusCode::SUCCESS;
593}
594
595//---------------------------------------------------------------------------
596
597StatusCode AvalancheSchedulerSvc::pushNewEvents( std::vector<EventContext*>& eventContexts ) {
598 StatusCode sc;
599 for ( auto context : eventContexts ) {
600 sc = pushNewEvent( context );
601 if ( sc != StatusCode::SUCCESS ) return sc;
602 }
603 return sc;
604}
605
606//---------------------------------------------------------------------------
607
608unsigned int AvalancheSchedulerSvc::freeSlots() { return std::max( m_freeSlots.load(), 0 ); }
609
610//---------------------------------------------------------------------------
611
613
614//---------------------------------------------------------------------------
619
620 // ON_DEBUG debug() << "popFinishedEvent: queue size: " << m_finishedEvents.size() << endmsg;
621 if ( m_freeSlots.load() == (int)m_maxEventsInFlight || m_isActive == INACTIVE ) {
622 // ON_DEBUG debug() << "freeslots: " << m_freeSlots << "/" << m_maxEventsInFlight
623 // << " active: " << m_isActive << endmsg;
624 return StatusCode::FAILURE;
625 } else {
626 // ON_DEBUG debug() << "freeslots: " << m_freeSlots << "/" << m_maxEventsInFlight
627 // << " active: " << m_isActive << endmsg;
628 m_finishedEvents.pop( eventContext );
629 ++m_freeSlots;
630 ON_DEBUG debug() << "Popped slot " << eventContext->slot() << " (event " << eventContext->evt() << ")" << endmsg;
631 return StatusCode::SUCCESS;
632 }
633}
634
635//---------------------------------------------------------------------------
640
641 if ( m_finishedEvents.try_pop( eventContext ) ) {
642 ON_DEBUG debug() << "Try Pop successful slot " << eventContext->slot() << "(event " << eventContext->evt() << ")"
643 << endmsg;
644 ++m_freeSlots;
645 return StatusCode::SUCCESS;
646 }
647 return StatusCode::FAILURE;
648}
649
650//--------------------------------------------------------------------------
651
660
661 StatusCode global_sc( StatusCode::SUCCESS );
662
663 // Retry algorithms
664 const size_t retries = m_retryQueue.size();
665 for ( unsigned int retryIndex = 0; retryIndex < retries; ++retryIndex ) {
666 TaskSpec retryTS = std::move( m_retryQueue.front() );
667 m_retryQueue.pop();
668 global_sc = schedule( std::move( retryTS ) );
669 }
670
671 // Loop over all slots
672 OccupancySnapshot nextSnap;
673 auto now = std::chrono::system_clock::now();
674 for ( EventSlot& thisSlot : m_eventSlots ) {
675
676 // Ignore slots without a valid context (relevant when populating scheduler for first time)
677 if ( !thisSlot.eventContext ) continue;
678
679 int iSlot = thisSlot.eventContext->slot();
680
681 // Cache the states of the algorithms to improve readability and performance
682 AlgsExecutionStates& thisAlgsStates = thisSlot.algsStates;
683
684 StatusCode partial_sc = StatusCode::FAILURE;
685
686 // Make an occupancy snapshot
687 if ( m_snapshotInterval != std::chrono::duration<int64_t, std::milli>::min() &&
689
690 // Initialise snapshot
691 if ( nextSnap.states.empty() ) {
692 nextSnap.time = now;
693 nextSnap.states.resize( m_eventSlots.size() );
694 }
695
696 // Store alg states
697 std::vector<int>& slotStateTotals = nextSnap.states[iSlot];
698 slotStateTotals.resize( AState::MAXVALUE );
699 for ( uint8_t state = 0; state < AState::MAXVALUE; ++state ) {
700 slotStateTotals[state] = thisSlot.algsStates.sizeOfSubset( AState( state ) );
701 }
702
703 // Add subslot alg states
704 for ( auto& subslot : thisSlot.allSubSlots ) {
705 for ( uint8_t state = 0; state < AState::MAXVALUE; ++state ) {
706 slotStateTotals[state] += subslot.algsStates.sizeOfSubset( AState( state ) );
707 }
708 }
709 }
710
711 // Perform DR->SCHEDULED
712 const auto& drAlgs = thisAlgsStates.algsInState( AState::DATAREADY );
713 for ( uint algIndex : drAlgs ) {
714 const std::string& algName{ index2algname( algIndex ) };
715 unsigned int rank{ m_optimizationMode.empty() ? 0 : m_precSvc->getPriority( algName ) };
716 bool asynchronous{ m_precSvc->isAsynchronous( algName ) };
717
718 partial_sc =
719 schedule( TaskSpec( nullptr, algIndex, algName, rank, asynchronous, iSlot, thisSlot.eventContext.get() ) );
720
721 ON_VERBOSE if ( partial_sc.isFailure() ) verbose()
722 << "Could not apply transition from " << AState::DATAREADY << " for algorithm " << algName
723 << " on processing slot " << iSlot << endmsg;
724 }
725
726 // Check for algorithms ready in sub-slots
727 for ( auto& subslot : thisSlot.allSubSlots ) {
728 const auto& drAlgsSubSlot = subslot.algsStates.algsInState( AState::DATAREADY );
729 for ( uint algIndex : drAlgsSubSlot ) {
730 const std::string& algName{ index2algname( algIndex ) };
731 unsigned int rank{ m_optimizationMode.empty() ? 0 : m_precSvc->getPriority( algName ) };
732 bool asynchronous{ m_precSvc->isAsynchronous( algName ) };
733 partial_sc =
734 schedule( TaskSpec( nullptr, algIndex, algName, rank, asynchronous, iSlot, subslot.eventContext.get() ) );
735 }
736 }
737
739 std::stringstream s;
740 s << "START, " << thisAlgsStates.sizeOfSubset( AState::CONTROLREADY ) << ", "
741 << thisAlgsStates.sizeOfSubset( AState::DATAREADY ) << ", " << thisAlgsStates.sizeOfSubset( AState::SCHEDULED )
742 << ", " << std::chrono::high_resolution_clock::now().time_since_epoch().count() << "\n";
743 auto threads = ( m_threadPoolSize != -1 ) ? std::to_string( m_threadPoolSize )
744 : std::to_string( std::thread::hardware_concurrency() );
745 std::ofstream myfile;
746 myfile.open( "IntraEventFSMOccupancy_" + threads + "T.csv", std::ios::app );
747 myfile << s.str();
748 myfile.close();
749 }
750
751 // Not complete because this would mean that the slot is already free!
752 if ( m_precSvc->CFRulesResolved( thisSlot ) &&
753 !thisSlot.algsStates.containsAny(
754 { AState::CONTROLREADY, AState::DATAREADY, AState::SCHEDULED, AState::RESOURCELESS } ) &&
755 !subSlotAlgsInStates( thisSlot,
756 { AState::CONTROLREADY, AState::DATAREADY, AState::SCHEDULED, AState::RESOURCELESS } ) &&
757 !thisSlot.complete ) {
758
759 thisSlot.complete = true;
760 // if the event did not fail, add it to the finished events
761 // otherwise it is taken care of in the error handling
762 if ( m_algExecStateSvc->eventStatus( *thisSlot.eventContext ) == EventStatus::Success ) {
763 ON_DEBUG debug() << "Event " << thisSlot.eventContext->evt() << " finished (slot "
764 << thisSlot.eventContext->slot() << ")." << endmsg;
765 m_finishedEvents.push( thisSlot.eventContext.release() );
766 }
767
768 // now let's return the fully evaluated result of the control flow
769 ON_DEBUG debug() << m_precSvc->printState( thisSlot ) << endmsg;
770
771 thisSlot.eventContext.reset( nullptr );
772
773 } else if ( isStalled( thisSlot ) ) {
774 m_algExecStateSvc->setEventStatus( EventStatus::AlgStall, *thisSlot.eventContext );
775 eventFailed( thisSlot.eventContext.get() ); // can't release yet
776 }
777 partial_sc.ignore();
778 } // end loop on slots
779
780 // Process snapshot
781 if ( !nextSnap.states.empty() ) {
782 m_lastSnapshot = nextSnap.time;
783 m_snapshotCallback( std::move( nextSnap ) );
784 }
785
786 ON_VERBOSE verbose() << "Iteration done." << endmsg;
787 m_needsUpdate.store( false );
788 return global_sc;
789}
790
791//---------------------------------------------------------------------------
792// Update algorithm state and, optionally, revise states of other downstream algorithms
793StatusCode AvalancheSchedulerSvc::revise( unsigned int iAlgo, EventContext* contextPtr, AState state, bool iterate ) {
794 StatusCode sc;
795 auto slotIndex = contextPtr->slot();
796 EventSlot& slot = m_eventSlots[slotIndex];
797 Cause cs = { Cause::source::Task, index2algname( iAlgo ) };
798
799 if ( contextPtr->usesSubSlot() ) {
800 // Sub-slot
801 auto subSlotIndex = contextPtr->subSlot();
802 EventSlot& subSlot = slot.allSubSlots[subSlotIndex];
803
804 sc = subSlot.algsStates.set( iAlgo, state );
805
806 if ( sc.isSuccess() ) {
807 ON_VERBOSE verbose() << "Promoted " << index2algname( iAlgo ) << " to " << state << " [slot:" << slotIndex
808 << ", subslot:" << subSlotIndex << ", event:" << contextPtr->evt() << "]" << endmsg;
809 // Revise states of algorithms downstream the precedence graph
810 if ( iterate ) sc = m_precSvc->iterate( subSlot, cs );
811 }
812 } else {
813 // Event level (standard behaviour)
814 sc = slot.algsStates.set( iAlgo, state );
815
816 if ( sc.isSuccess() ) {
817 ON_VERBOSE verbose() << "Promoted " << index2algname( iAlgo ) << " to " << state << " [slot:" << slotIndex
818 << ", event:" << contextPtr->evt() << "]" << endmsg;
819 // Revise states of algorithms downstream the precedence graph
820 if ( iterate ) sc = m_precSvc->iterate( slot, cs );
821 }
822 }
823 return sc;
824}
825
826//---------------------------------------------------------------------------
827
835
836 if ( !slot.algsStates.containsAny( { AState::DATAREADY, AState::SCHEDULED, AState::RESOURCELESS } ) &&
837 !subSlotAlgsInStates( slot, { AState::DATAREADY, AState::SCHEDULED, AState::RESOURCELESS } ) ) {
838
839 error() << "*** Stall detected, event context: " << slot.eventContext.get() << endmsg;
840
841 return true;
842 }
843 return false;
844}
845
846//---------------------------------------------------------------------------
847
853 const uint slotIdx = eventContext->slot();
854
855 error() << "Event " << eventContext->evt() << " on slot " << slotIdx << " failed" << endmsg;
856
857 dumpSchedulerState( msgLevel( MSG::VERBOSE ) ? -1 : slotIdx );
858
859 // dump temporal and topological precedence analysis (if enabled in the PrecedenceSvc)
860 m_precSvc->dumpPrecedenceRules( m_eventSlots[slotIdx] );
861
862 // Push into the finished events queue the failed context
863 m_eventSlots[slotIdx].complete = true;
864 m_finishedEvents.push( m_eventSlots[slotIdx].eventContext.release() );
865}
866
867//---------------------------------------------------------------------------
868
874
875 // To have just one big message
876 std::ostringstream outputMS;
877
878 outputMS << "Dumping scheduler state\n"
879 << "=========================================================================================\n"
880 << "++++++++++++++++++++++++++++++++++++ SCHEDULER STATE ++++++++++++++++++++++++++++++++++++\n"
881 << "=========================================================================================\n\n";
882
883 //===========================================================================
884
885 outputMS << "------------------ Last schedule: Task/Event/Slot/Thread/State Mapping "
886 << "------------------\n\n";
887
888 // Figure if TimelineSvc is available (used below to detect threads IDs)
889 auto timelineSvc = serviceLocator()->service<ITimelineSvc>( "TimelineSvc", false );
890 if ( !timelineSvc.isValid() || !timelineSvc->isEnabled() ) {
891 outputMS << "WARNING Enable TimelineSvc in record mode (RecordTimeline = True) to trace the mapping\n";
892 } else {
893
894 // Figure optimal printout layout
895 size_t indt( 0 );
896 for ( auto& slot : m_eventSlots ) {
897
898 const auto& schedAlgs = slot.algsStates.algsInState( AState::SCHEDULED );
899 for ( uint algIndex : schedAlgs ) {
900 if ( index2algname( algIndex ).length() > indt ) indt = index2algname( algIndex ).length();
901 }
902 }
903
904 // Figure the last running schedule across all slots
905 for ( auto& slot : m_eventSlots ) {
906
907 const auto& schedAlgs = slot.algsStates.algsInState( AState::SCHEDULED );
908 for ( uint algIndex : schedAlgs ) {
909
910 const std::string& algoName{ index2algname( algIndex ) };
911
912 outputMS << " task: " << std::setw( indt ) << algoName << " evt/slot: " << slot.eventContext->evt() << "/"
913 << slot.eventContext->slot();
914
915 // Try to get POSIX threads IDs the currently running tasks are scheduled to
916 if ( timelineSvc.isValid() ) {
917 TimelineEvent te{};
918 te.algorithm = algoName;
919 te.slot = slot.eventContext->slot();
920 te.event = slot.eventContext->evt();
921
922 if ( timelineSvc->getTimelineEvent( te ) )
923 outputMS << " thread.id: 0x" << std::hex << te.thread << std::dec;
924 else
925 outputMS << " thread.id: [unknown]"; // this means a task has just
926 // been signed off as SCHEDULED,
927 // but has not been assigned to a thread yet
928 // (i.e., not running yet)
929 }
930 outputMS << " state: [" << m_algExecStateSvc->algExecState( algoName, *( slot.eventContext ) ) << "]\n";
931 }
932 }
933 }
934
935 //===========================================================================
936
937 outputMS << "\n---------------------------- Task/CF/FSM Mapping "
938 << ( 0 > iSlot ? "[all slots] --" : "[target slot] " ) << "--------------------------\n\n";
939
940 int slotCount = -1;
941 bool wasAlgError = ( iSlot >= 0 ) ? m_eventSlots[iSlot].algsStates.containsAny( { AState::ERROR } ) ||
942 subSlotAlgsInStates( m_eventSlots[iSlot], { AState::ERROR } )
943 : false;
944
945 for ( auto& slot : m_eventSlots ) {
946 ++slotCount;
947 if ( slot.complete ) continue;
948
949 outputMS << "[ slot: "
950 << ( slot.eventContext->valid() ? std::to_string( slot.eventContext->slot() ) : "[ctx invalid]" )
951 << ", event: "
952 << ( slot.eventContext->valid() ? std::to_string( slot.eventContext->evt() ) : "[ctx invalid]" );
953
954 if ( slot.eventContext->eventID().isValid() ) { outputMS << ", eventID: " << slot.eventContext->eventID(); }
955 outputMS << " ]:\n\n";
956
957 if ( 0 > iSlot || iSlot == slotCount ) {
958
959 // If an alg has thrown an error then it's not a failure of the CF/DF graph
960 if ( wasAlgError ) {
961 outputMS << "ERROR alg(s):";
962 int errorCount = 0;
963 const auto& errorAlgs = slot.algsStates.algsInState( AState::ERROR );
964 for ( uint algIndex : errorAlgs ) {
965 outputMS << " " << index2algname( algIndex );
966 ++errorCount;
967 }
968 if ( errorCount == 0 ) outputMS << " in subslot(s)";
969 outputMS << "\n\n";
970 } else {
971 // Snapshot of the Control Flow and FSM states
972 outputMS << m_precSvc->printState( slot ) << "\n";
973 }
974
975 // Mention sub slots (this is expensive if the number of sub-slots is high)
976 if ( m_verboseSubSlots && !slot.allSubSlots.empty() ) {
977 outputMS << "\nNumber of sub-slots: " << slot.allSubSlots.size() << "\n\n";
978 auto slotID = slot.eventContext->valid() ? std::to_string( slot.eventContext->slot() ) : "[ctx invalid]";
979 for ( auto& ss : slot.allSubSlots ) {
980 outputMS << "[ slot: " << slotID << ", sub-slot: "
981 << ( ss.eventContext->valid() ? std::to_string( ss.eventContext->subSlot() ) : "[ctx invalid]" )
982 << ", entry: " << ss.entryPoint << ", event: "
983 << ( ss.eventContext->valid() ? std::to_string( ss.eventContext->evt() ) : "[ctx invalid]" )
984 << " ]:\n\n";
985 if ( wasAlgError ) {
986 outputMS << "ERROR alg(s):";
987 const auto& errorAlgs = ss.algsStates.algsInState( AState::ERROR );
988 for ( uint algIndex : errorAlgs ) { outputMS << " " << index2algname( algIndex ); }
989 outputMS << "\n\n";
990 } else {
991 // Snapshot of the Control Flow and FSM states in sub slot
992 outputMS << m_precSvc->printState( ss ) << "\n";
993 }
994 }
995 }
996 }
997 }
998
999 //===========================================================================
1000
1001 if ( 0 <= iSlot && !wasAlgError ) {
1002 outputMS << "\n------------------------------ Algorithm Execution States -----------------------------\n\n";
1003 m_algExecStateSvc->dump( outputMS, *( m_eventSlots[iSlot].eventContext ) );
1004 }
1005
1006 outputMS << "\n=========================================================================================\n"
1007 << "++++++++++++++++++++++++++++++++++++++ END OF DUMP ++++++++++++++++++++++++++++++++++++++\n"
1008 << "=========================================================================================\n\n";
1009
1010 info() << outputMS.str() << endmsg;
1011}
1012
1013//---------------------------------------------------------------------------
1014
1016
1017 // Check if a free Algorithm instance is available
1018 StatusCode getAlgSC( m_algResourcePool->acquireAlgorithm( ts.algName, ts.algPtr ) );
1019
1020 // If an instance is available, proceed to scheduling
1021 StatusCode sc;
1022 if ( getAlgSC.isSuccess() ) {
1023
1024 // Decide how to schedule the task and schedule it
1025 if ( -100 != m_threadPoolSize ) {
1026
1027 // Cache values before moving the TaskSpec further
1028 unsigned int algIndex{ ts.algIndex };
1029 std::string_view algName( ts.algName );
1030 unsigned int algRank{ ts.algRank };
1031 bool asynchronous{ ts.asynchronous };
1032 int slotIndex{ ts.slotIndex };
1033 EventContext* contextPtr{ ts.contextPtr };
1034
1035 if ( asynchronous ) {
1036 // Add to asynchronous scheduled queue
1037 m_scheduledAsynchronousQueue.push( std::move( ts ) );
1038
1039 // Schedule task
1040 m_fiberManager->schedule( AlgTask( this, serviceLocator(), m_algExecStateSvc, asynchronous ) );
1041 }
1042
1043 if ( !asynchronous ) {
1044 // Add the algorithm to the scheduled queue
1045 m_scheduledQueue.push( std::move( ts ) );
1046
1047 // Prepare a TBB task that will execute the Algorithm according to the above queued specs
1048 m_arena->enqueue( AlgTask( this, serviceLocator(), m_algExecStateSvc, asynchronous ) );
1050 }
1051 sc = revise( algIndex, contextPtr, AState::SCHEDULED );
1052
1053 ON_DEBUG debug() << "Scheduled " << algName << " [slot:" << slotIndex << ", event:" << contextPtr->evt()
1054 << ", rank:" << algRank << ", asynchronous:" << ( asynchronous ? "yes" : "no" )
1055 << "]. Scheduled algorithms: " << m_algosInFlight << endmsg;
1056
1057 } else { // Avoid scheduling via TBB if the pool size is -100. Instead, run here in the scheduler's control thread
1058 // Beojan: I don't think this bit works. ts hasn't been pushed into any queue so AlgTask won't retrieve it
1060 sc = revise( ts.algIndex, ts.contextPtr, AState::SCHEDULED );
1061 AlgTask( this, serviceLocator(), m_algExecStateSvc, ts.asynchronous )();
1063 }
1064 } else { // if no Algorithm instance available, retry later
1065
1066 sc = revise( ts.algIndex, ts.contextPtr, AState::RESOURCELESS );
1067 // Add the algorithm to the retry queue
1068 m_retryQueue.push( std::move( ts ) );
1069 }
1070
1072
1073 return sc;
1074}
1075
1076//---------------------------------------------------------------------------
1077
1082
1083 Gaudi::Hive::setCurrentContext( ts.contextPtr );
1084
1086
1087 const AlgExecStateRef algstate = m_algExecStateSvc->algExecState( ts.algPtr, *( ts.contextPtr ) );
1088 AState state = algstate.execStatus().isSuccess()
1089 ? ( algstate.filterPassed() ? AState::EVTACCEPTED : AState::EVTREJECTED )
1090 : AState::ERROR;
1091
1092 // Update algorithm state and revise the downstream states
1093 auto sc = revise( ts.algIndex, ts.contextPtr, state, true );
1094
1095 ON_DEBUG debug() << "Executed " << ts.algName << " [slot:" << ts.slotIndex << ", event:" << ts.contextPtr->evt()
1096 << ", rank:" << ts.algRank << ", asynchronous:" << ( ts.asynchronous ? "yes" : "no" )
1097 << "]. Scheduled algorithms: " << m_algosInFlight << endmsg;
1098
1099 // Prompt a call to updateStates
1100 m_needsUpdate.store( true );
1101 return sc;
1102}
1103
1104//---------------------------------------------------------------------------
1105
1106// Method to inform the scheduler about event views
1107
1108StatusCode AvalancheSchedulerSvc::scheduleEventView( const EventContext* sourceContext, const std::string& nodeName,
1109 std::unique_ptr<EventContext> viewContext ) {
1110 // Prevent view nesting
1111 if ( sourceContext->usesSubSlot() ) {
1112 fatal() << "Attempted to nest EventViews at node " << nodeName << ": this is not supported" << endmsg;
1113 return StatusCode::FAILURE;
1114 }
1115
1116 ON_VERBOSE verbose() << "Queuing a view for [" << viewContext.get() << "]" << endmsg;
1117
1118 // It's not possible to create an std::functional from a move-capturing lambda
1119 // So, we have to release the unique pointer
1120 auto action = [this, slotIndex = sourceContext->slot(), viewContextPtr = viewContext.release(),
1121 &nodeName]() -> StatusCode {
1122 // Attach the sub-slot to the top-level slot
1123 EventSlot& topSlot = this->m_eventSlots[slotIndex];
1124
1125 if ( viewContextPtr ) {
1126 // Re-create the unique pointer
1127 auto viewContext = std::unique_ptr<EventContext>( viewContextPtr );
1128 topSlot.addSubSlot( std::move( viewContext ), nodeName );
1129 return StatusCode::SUCCESS;
1130 } else {
1131 // Disable the view node if there are no views
1132 topSlot.disableSubSlots( nodeName );
1133 return StatusCode::SUCCESS;
1134 }
1135 };
1136
1137 m_actionsQueue.push( std::move( action ) );
1138
1139 return StatusCode::SUCCESS;
1140}
1141
1142//---------------------------------------------------------------------------
1143
1144// Sample occupancy at fixed interval (ms)
1145// Negative value to deactivate, 0 to snapshot every change
1146// Each sample, apply the callback function to the result
1147
1148void AvalancheSchedulerSvc::recordOccupancy( int samplePeriod, std::function<void( OccupancySnapshot )> callback ) {
1149
1150 auto action = [this, samplePeriod, callback = std::move( callback )]() -> StatusCode {
1151 if ( samplePeriod < 0 ) {
1152 this->m_snapshotInterval = std::chrono::duration<int64_t, std::milli>::min();
1153 } else {
1154 this->m_snapshotInterval = std::chrono::duration<int64_t, std::milli>( samplePeriod );
1155 m_snapshotCallback = std::move( callback );
1156 }
1157 return StatusCode::SUCCESS;
1158 };
1159
1160 m_actionsQueue.push( std::move( action ) );
1161}
1162
1163StatusCode AvalancheSchedulerSvc::dumpDataDepsGraphFile( const std::map<std::string, DataObjIDColl>& inDeps,
1164 const std::map<std::string, DataObjIDColl>& outDeps ) const {
1165 // Both maps should have the same algorithm entries
1166 assert( inDeps.size() == outDeps.size() );
1167
1169 info() << "Dumping data dependencies graph to file: " << g.fileName() << endmsg;
1170
1171 // define algs and objects
1172 std::set<std::size_t> definedObjects;
1173
1174 // Regex for selection of algs and objects
1175 std::regex algNameRegex( m_dataDepsGraphAlgoPattern.value() );
1176 std::regex objNameRegex( m_dataDepsGraphObjectPattern.value() );
1177
1178 // inDeps and outDeps should have the same entries
1179 std::size_t algoIndex = 0ul;
1180 for ( const auto& [algName, ideps] : inDeps ) {
1181 if ( not std::regex_search( algName, algNameRegex ) ) continue;
1182 std::string algIndex = "Alg_" + std::to_string( algoIndex );
1183 g.addNode( algIndex, algName );
1184
1185 // inputs
1186 for ( const auto& dep : ideps ) {
1187 if ( not std::regex_search( dep.fullKey(), objNameRegex ) ) continue;
1188
1189 const auto [itr, inserted] = definedObjects.insert( dep.hash() );
1190 std::string objIndex = "obj_" + std::to_string( dep.hash() );
1191 if ( inserted ) g.addNode( objIndex, dep.key() );
1192
1193 g.addEdge( objIndex, algIndex );
1194 } // loop on ideps
1195
1196 const auto& odeps = outDeps.at( algName );
1197 for ( const auto& dep : odeps ) {
1198 if ( not std::regex_search( dep.fullKey(), objNameRegex ) ) continue;
1199
1200 const auto [itr, inserted] = definedObjects.insert( dep.hash() );
1201 std::string objIndex = "obj_" + std::to_string( dep.hash() );
1202 if ( inserted ) g.addNode( objIndex, dep.key() );
1203
1204 g.addEdge( algIndex, objIndex );
1205 } // loop on odeps
1206
1207 ++algoIndex;
1208 } // loop on inDeps
1209
1210 return StatusCode::SUCCESS;
1211}
#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.
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