22 #include <unordered_set> 25 #include "boost/thread.hpp" 26 #include "boost/tokenizer.hpp" 27 #include "boost/algorithm/string.hpp" 29 #include "tbb/task_scheduler_init.h" 49 if ( !sc.
isSuccess() ) warning() <<
"Base class could not be initialized" <<
endmsg;
52 m_threadPoolSvc = serviceLocator()->service(
"ThreadPoolSvc" );
53 if ( !m_threadPoolSvc.isValid() ) {
54 fatal() <<
"Error retrieving ThreadPoolSvc" <<
endmsg;
59 info() <<
"Activating scheduler in a separate thread" <<
endmsg;
62 while ( m_isActive != ACTIVE ) {
64 fatal() <<
"Terminating initialization" <<
endmsg;
67 info() <<
"Waiting for AvalancheSchedulerSvc to activate" <<
endmsg;
73 m_algResourcePool = serviceLocator()->service(
"AlgResourcePool" );
74 if ( !m_algResourcePool.isValid() ) {
75 fatal() <<
"Error retrieving AlgoResourcePool" <<
endmsg;
79 m_algExecStateSvc = serviceLocator()->service(
"AlgExecStateSvc");
80 if (!m_algExecStateSvc.isValid()) {
81 fatal() <<
"Error retrieving AlgExecStateSvc" <<
endmsg;
86 m_whiteboard = serviceLocator()->service( m_whiteboardSvcName );
87 if ( !m_whiteboard.isValid() ) {
88 fatal() <<
"Error retrieving EventDataSvc interface IHiveWhiteBoard." <<
endmsg;
93 if ( m_useIOBoundAlgScheduler ) {
94 m_IOBoundAlgScheduler = serviceLocator()->service( m_IOBoundAlgSchedulerSvcName );
95 if ( !m_IOBoundAlgScheduler.isValid() )
96 fatal() <<
"Error retrieving IOBoundSchedulerAlgSvc interface IAccelerator." <<
endmsg;
101 size_t numberOfWBSlots = m_whiteboard->getNumberOfStores();
102 if ( m_maxEventsInFlight != 0 ) {
103 warning() <<
"Property MaxEventsInFlight was set. This works but it's deprecated. " 104 <<
"Please migrate your code options files." <<
endmsg;
106 if ( m_maxEventsInFlight != (
int)numberOfWBSlots ) {
107 warning() <<
"In addition, the number of events in flight (" << m_maxEventsInFlight
108 <<
") differs from the slots in the whiteboard (" << numberOfWBSlots
109 <<
"). Setting the number of events in flight to " << numberOfWBSlots <<
endmsg;
114 m_maxEventsInFlight = numberOfWBSlots;
117 m_freeSlots = m_maxEventsInFlight;
122 if ( m_algosDependencies.size() != 0 ) {
123 warning() <<
" ##### Property AlgosDependencies is deprecated and ignored." 124 <<
" FIX your job options #####" <<
endmsg;
129 const unsigned int algsNumber = algos.
size();
130 info() <<
"Found " << algsNumber <<
" algorithms" <<
endmsg;
143 fatal() <<
"Could not convert IAlgorithm into Algorithm: this will result in a crash." <<
endmsg;
146 auto r = globalOutp.
insert(
id);
148 warning() <<
"multiple algorithms declare " <<
id <<
" as output! could be a single instance in multiple paths though, or control flow may guarantee only one runs...!" <<
endmsg;
152 info() <<
"outputs:\n" ;
153 for (
const auto& i : globalOutp ) {
154 info() << i <<
'\n' ;
160 info() <<
"Data Dependencies for Algorithms:";
165 if (
nullptr == algoPtr )
166 fatal() <<
"Could not convert IAlgorithm into Algorithm: this will result in a crash." <<
endmsg;
168 info() <<
"\n " << algoPtr->
name();
174 info() <<
"\n o INPUT " << id;
175 if (
id.key().find(
":")!=std::string::npos) {
176 info() <<
" contains alternatives which require resolution... " <<
endmsg;
177 auto tokens = boost::tokenizer<boost::char_separator<char>>{
id.key(),boost::char_separator<char>{
":"}};
180 return globalOutp.find(
DataObjID{t} ) != globalOutp.end();
182 if (itok!=tokens.end()) {
183 info() <<
"found matching output for " << *itok <<
" -- updating scheduler info" <<
endmsg;
186 error() <<
"failed to find alternate in global output list" <<
endmsg;
189 algoDependencies.
insert(
id );
193 info() <<
"\n o OUTPUT " << id;
194 if (
id.key().find(
":")!=std::string::npos) {
195 info() <<
" alternatives are NOT allowed for outputs..." <<
endmsg;
206 m_algname_vect.reserve( algsNumber );
207 unsigned int index = 0;
210 m_algname_index_map[
name] = index;
211 m_algname_vect.emplace_back( name );
218 for (
auto o : globalInp ) {
219 if ( globalOutp.find( o ) == globalOutp.end() ) {
224 if ( unmetDep.
size() > 0 ) {
225 fatal() <<
"The following unmet INPUT data dependencies were found: ";
226 for (
auto& o : unmetDep ) {
227 fatal() <<
"\n o " << o <<
" required by Algorithm: ";
228 for (
size_t i = 0; i < m_algosDependencies.
size(); ++i ) {
229 if ( m_algosDependencies[i].find( o ) != m_algosDependencies[i].
end() ) {
230 fatal() <<
"\n * " << m_algname_vect[i];
237 info() <<
"No unmet INPUT data dependencies were found" <<
endmsg;
243 sc = m_efManager.initialize( algPool->
getPRGraph(), m_algname_index_map, m_eventSlots, m_optimizationMode );
244 unsigned int controlFlowNodeNumber = m_efManager.getPrecedenceRulesGraph()->getControlFlowNodeCounter();
248 if ( !messageSvc.
isValid() ) error() <<
"Error retrieving MessageSvc interface IMessageSvc." <<
endmsg;
250 m_eventSlots.assign( m_maxEventsInFlight,
251 EventSlot( m_algosDependencies, algsNumber, controlFlowNodeNumber, messageSvc ) );
252 std::for_each( m_eventSlots.begin(), m_eventSlots.end(), [](
EventSlot& slot ) { slot.complete =
true; } );
255 info() <<
"Concurrency level information:" <<
endmsg;
256 info() <<
" o Number of events in flight: " << m_maxEventsInFlight <<
endmsg;
257 info() <<
" o Number of algorithms in flight: " << m_maxAlgosInFlight <<
endmsg;
258 info() <<
" o TBB thread pool size: " << m_threadPoolSize <<
endmsg;
261 if ( m_simulateExecution ) {
263 m_efManager.simulateExecutionFlow( vis );
281 info() <<
"Joining Scheduler thread" <<
endmsg;
286 error() <<
"problems in scheduler thread" <<
endmsg;
308 debug() <<
"AvalancheSchedulerSvc::activate()" <<
endmsg;
311 error() <<
"problems initializing ThreadPoolSvc" <<
endmsg;
323 info() <<
"Start checking the actionsQueue" <<
endmsg;
328 verbose() <<
"Action did not succeed (which is not bad per se)." <<
endmsg;
333 info() <<
"Terminating thread-pool resources" <<
endmsg;
335 error() <<
"Problems terminating thread pool" <<
endmsg;
393 if ( !eventContext ) {
408 const unsigned int thisSlotNum = eventContext->
slot();
411 fatal() <<
"The slot " << thisSlotNum <<
" is supposed to be a finished event but it's not" <<
endmsg;
415 info() <<
"Executing event " << eventContext->
evt() <<
" on slot " << thisSlotNum <<
endmsg;
416 thisSlot.
reset( eventContext );
427 verbose() <<
"Pushing the action to update the scheduler for slot " << eventContext->
slot() <<
endmsg;
438 for (
auto context : eventContexts ) {
456 unsigned int slotNum = 0;
458 if ( not thisSlot.algsStates.allAlgsExecuted() and not thisSlot.complete ) {
482 debug() <<
"Popped slot " << eventContext->
slot() <<
"(event " 495 debug() <<
"Try Pop successful slot " << eventContext->
slot() <<
"(event " << eventContext->
evt() <<
")" 514 fatal() <<
"*** Event " << eventContext->
evt() <<
" on slot " 515 << eventContext->
slot() <<
" failed! ***" <<
endmsg;
520 info() <<
"Dumping Alg Exec State for slot " << eventContext->
slot()
568 eventSlotsPtrs.
reserve( eventsSlotsSize );
570 if ( !slotIt->complete ) eventSlotsPtrs.
push_back( &( *slotIt ) );
578 for (
EventSlot* thisSlotPtr : eventSlotsPtrs ) {
586 if ( !algo_name.
empty() )
594 auto comp_nodes = [
this](
const uint& i,
const uint& j ) {
600 for (
auto it = thisAlgsStates.
begin( AlgsExecutionStates::State::DATAREADY );
601 it != thisAlgsStates.
end( AlgsExecutionStates::State::DATAREADY ); ++it )
629 while ( !buffer.
empty() ) {
630 bool IOBound =
false;
640 if (partial_sc.isFailure())
641 verbose() <<
"Could not apply transition from " 649 for (
auto it = thisAlgsStates.
begin( AlgsExecutionStates::State::DATAREADY );
650 it != thisAlgsStates.
end( AlgsExecutionStates::State::DATAREADY ); ++it ) {
653 bool IOBound =
false;
664 verbose() <<
"Could not apply transition from " 666 <<
" for algorithm " <<
index2algname(algIndex) <<
" on processing slot " << iSlot <<
endmsg;
673 s << algo_name <<
", " << thisAlgsStates.
sizeOfSubset(State::CONTROLREADY) <<
", " 674 << thisAlgsStates.
sizeOfSubset(State::DATAREADY) <<
", " 675 << thisAlgsStates.
sizeOfSubset(State::SCHEDULED) <<
", " 679 :
std::to_string(tbb::task_scheduler_init::default_num_threads());
681 myfile.
open(
"IntraEventConcurrencyDynamics_" + threads +
"T.csv",
std::ios::app );
692 thisSlot.complete =
true;
698 debug() <<
"Event " << thisSlot.eventContext->evt() <<
" finished (slot " 699 << thisSlot.eventContext->slot() <<
")." <<
endmsg;
708 thisSlot.eventContext =
nullptr;
738 info() <<
"About to declare a stall" <<
endmsg;
760 outputMessageStream <<
"============================== Execution Task State =============================" 764 outputMessageStream << std::endl
765 <<
"============================== Scheduler State =================================" 771 if ( thisSlot.complete )
continue;
773 outputMessageStream <<
"----------- slot: " << thisSlot.eventContext->slot()
774 <<
" event: " << thisSlot.eventContext->evt() <<
" -----------" <<
std::endl;
776 if ( 0 > iSlot or iSlot == slotCount ) {
777 outputMessageStream <<
"Algorithms states:" <<
std::endl;
779 const DataObjIDColl& wbSlotContent( thisSlot.dataFlowMgr.content() );
780 for (
unsigned int algoIdx = 0; algoIdx < thisSlot.algsStates.size(); ++algoIdx ) {
781 outputMessageStream <<
" o " <<
index2algname( algoIdx ) <<
" [" 783 DataObjIDColl deps( thisSlot.dataFlowMgr.dataDependencies( algoIdx ) );
784 const int depsSize = deps.
size();
785 if ( depsSize == 0 ) outputMessageStream <<
" none";
788 for (
auto d : deps ) {
789 outputMessageStream << d <<
" ";
790 if ( wbSlotContent.find( d ) == wbSlotContent.end() ) {
796 if ( !missing.
empty() ) {
797 outputMessageStream <<
". The following are missing: ";
798 for (
auto d : missing ) {
799 outputMessageStream << d <<
" ";
807 outputMessageStream <<
"\nWhiteboard contents: " <<
std::endl;
808 for (
auto& product : wbSlotContent ) outputMessageStream <<
" o " << product <<
std::endl;
811 outputMessageStream <<
"\nControl Flow:" <<
std::endl;
815 outputMessageStream << cFlowStateStringStream.
str() <<
std::endl;
819 outputMessageStream <<
"=================================== END ======================================" <<
std::endl;
821 info() <<
"Dumping Scheduler State " << std::endl << outputMessageStream.
str() <<
endmsg;
834 if ( sc.isSuccess() ) {
837 fatal() <<
"Event context for algorithm " << algName <<
" is a nullptr (slot " << si <<
")" <<
endmsg;
843 eventContext->
slot(),
851 tbb::task* triggerAlgoStateUpdate =
new(tbb::task::allocate_root())
855 triggerAlgoStateUpdate->set_ref_count(1);
857 tbb::task* algoTask =
new(triggerAlgoStateUpdate->allocate_child())
860 tbb::task::enqueue( *algoTask);
865 promote2ExecutedClosure();
869 debug() <<
"Algorithm " << algName <<
" was submitted on event " << eventContext->
evt() <<
" in slot " << si
876 if (updateSc.isSuccess())
900 if ( sc.isSuccess() ) {
903 fatal() <<
"[Asynchronous] Event context for algorithm " << algName <<
" is a nullptr (slot " << si <<
")" 913 debug() <<
"[Asynchronous] Algorithm " << algName <<
" was submitted on event " 914 << eventContext->
evt() <<
" in slot " << si
919 if (updateSc.isSuccess())
922 <<
" to SCHEDULED on slot " << si <<
endmsg;
926 debug() <<
"[Asynchronous] Could not acquire instance for algorithm " <<
index2algname( iAlgo ) <<
" on slot " 940 if ( !castedAlgo )
fatal() <<
"The casting did not succeed!" <<
endmsg;
951 error() <<
"[Event " << eventContext->
evt() <<
", Slot " << eventContext->
slot() <<
"] " 952 <<
"Instance of algorithm " << algo->name() <<
" could not be properly put back." <<
endmsg;
961 debug() <<
"Algorithm " << algo->name() <<
" executed in slot " << si <<
". Algorithms scheduled are " 973 state = State::EVTACCEPTED;
975 state = State::EVTREJECTED;
996 if ( !castedAlgo )
fatal() <<
"[Asynchronous] The casting did not succeed!" <<
endmsg;
1006 error() <<
"[Asynchronous] [Event " << eventContext->
evt() <<
", Slot " << eventContext->
slot() <<
"] " 1007 <<
"Instance of algorithm " << algo->name() <<
" could not be properly put back." <<
endmsg;
1016 debug() <<
"[Asynchronous] Algorithm " << algo->name() <<
" executed in slot " << si
1025 debug() <<
"[Asynchronous] Trying to handle execution result of " 1029 state = State::EVTACCEPTED;
1031 state = State::EVTREJECTED;
1065 error() <<
"could not find Alg " << a->
name() <<
" in Scheduler!" <<
endmsg;
virtual StatusCode initPool(const int &poolSize)=0
Initializes the thread pool.
bool algsPresent(State state) const
Wrapper around I/O-bound Gaudi-algorithms.
StatusCode tryPopFinishedEvent(EventContext *&eventContext) override
Try to fetch an event from the scheduler.
StatusCode initialize() override
virtual StatusCode acquireAlgorithm(const std::string &name, IAlgorithm *&algo, bool blocking=false)=0
Acquire a certain algorithm using its name.
const std::chrono::system_clock::time_point getInitTime() const
unsigned int m_IOBoundAlgosInFlight
Number of algoritms presently in flight.
void printEventState(std::stringstream &ss, AlgsExecutionStates &states, const std::vector< int > &node_decisions, const unsigned int &recursionLevel) const
Print the state of the control flow for a given event.
const std::string & name() const override
The identifying name of the algorithm object.
virtual concurrency::PrecedenceRulesGraph * getPRGraph() const
StatusCode finalize() override
Gaudi::Property< bool > m_dumpIntraEventDynamics
MsgStream & info() const
shortcut for the method msgStream(MSG::INFO)
void dumpSchedulerState(int iSlot)
Dump the state of the scheduler.
StatusCode promoteToScheduled(unsigned int iAlgo, int si)
Algorithm promotion.
AlgsExecutionStates algsStates
Vector of algorithms states.
virtual void dump(std::ostringstream &ost, const EventContext &ctx) const =0
const DataObjIDColl & outputDataObjs() const override
bool isSuccess() const
Test for a status code of SUCCESS.
EventContext * eventContext
Cache for the eventContext.
StatusCode isStalled(int si)
Check if the scheduling is in a stall.
Header file for class GaudiAlgorithm.
MsgStream & verbose() const
shortcut for the method msgStream(MSG::VERBOSE)
virtual bool filterPassed() const =0
Did this algorithm pass or fail its filter criterion for the last event?
void touchReadyAlgorithms(IGraphVisitor &visitor) const
Promote all algorithms, ready to be executed, to DataReady state.
T duration_cast(T...args)
void activate()
Activate scheduler.
Gaudi::Property< std::string > m_optimizationMode
AlgorithmNode * getAlgorithmNode(const std::string &algoName) const
Get the AlgorithmNode from by algorithm name using graph index.
size_t sizeOfSubset(State state) const
A visitor, performing full top-down traversals of a graph.
StatusCode promoteToAsyncScheduled(unsigned int iAlgo, int si)
The AlgResourcePool is a concrete implementation of the IAlgResourcePool interface.
This class represents an entry point to all the event specific data.
bool isFailure() const
Test for a status code of FAILURE.
unsigned int algname2index(const std::string &algoname)
Convert a name to an integer.
bool isIOBound() const
Check if algorithm is I/O-bound.
void addAlg(Algorithm *, EventContext *, pthread_t)
std::atomic< ActivationState > m_isActive
Flag to track if the scheduler is active or not.
std::unordered_map< std::string, unsigned int > m_algname_index_map
Map to bookkeep the information necessary to the name2index conversion.
tbb::task * execute() override
Gaudi::Property< bool > m_useIOBoundAlgScheduler
std::atomic_int m_freeSlots
Atomic to account for asyncronous updates by the scheduler wrt the rest.
virtual StatusCode terminatePool()=0
Finalize the thread pool.
StatusCode pushNewEvents(std::vector< EventContext * > &eventContexts) override
unsigned int m_algosInFlight
Number of algoritms presently in flight.
static std::list< SchedulerState > m_sState
void updateDecision(const std::string &algo_name, const int &slotNum, AlgsExecutionStates &states, std::vector< int > &node_decisions) const
MsgStream & error() const
shortcut for the method msgStream(MSG::ERROR)
bool rootDecisionResolved(const std::vector< int > &node_decisions) const
Check whether root decision was resolved.
const float & getRank() const
Get Algorithm rank.
SmartIF< IAlgResourcePool > m_algResourcePool
Cache for the algorithm resource pool.
The AlgsExecutionStates encodes the state machine for the execution of algorithms within a single eve...
MsgStream & warning() const
shortcut for the method msgStream(MSG::WARNING)
StatusCode popFinishedEvent(EventContext *&eventContext) override
Blocks until an event is availble.
This class is used for returning status codes from appropriate routines.
const DataObjIDColl & inputDataObjs() const override
tbb::concurrent_bounded_queue< EventContext * > m_finishedEvents
Queue of finished events.
std::vector< std::string > m_algname_vect
Vector to bookkeep the information necessary to the index2name conversion.
virtual void setEventStatus(const EventStatus::Status &sc, const EventContext &ctx)=0
StatusCode finalize() override
Finalise.
static std::mutex m_ssMut
#define DECLARE_SERVICE_FACTORY(x)
concurrency::ExecutionFlowManager m_efManager
Member to take care of the control flow.
bool complete
Flags completion of the event.
Gaudi::Property< int > m_threadPoolSize
SmartIF< IThreadPoolSvc > m_threadPoolSvc
SmartIF< IAccelerator > m_IOBoundAlgScheduler
A shortcut to IO-bound algorithm scheduler.
The IAlgorithm is the interface implemented by the Algorithm base class.
GAUDI_API void setCurrentContext(const EventContext *ctx)
bool m_updateNeeded
Keep track of update actions scheduled.
Gaudi::Property< int > m_maxEventsInFlight
Base class from which all concrete algorithm classes should be derived.
StatusCode pushNewEvent(EventContext *eventContext) override
Make an event available to the scheduler.
Gaudi::Property< unsigned int > m_maxAlgosInFlight
void reset(EventContext *theeventContext)
Reset all resources in order to reuse the slot.
MsgStream & debug() const
shortcut for the method msgStream(MSG::DEBUG)
bool isValid() const
Allow for check if smart pointer is valid.
StatusCode eventFailed(EventContext *eventContext)
Method to check if an event failed and take appropriate actions.
Iterator begin(State kind)
virtual const EventStatus::Status & eventStatus(const EventContext &ctx) const =0
const std::string & index2algname(unsigned int index)
Convert an integer to a name.
Class representing the event slot.
StatusCode promoteToExecuted(unsigned int iAlgo, int si, IAlgorithm *algo, EventContext *)
The call to this method is triggered only from within the AlgoExecutionTask.
unsigned int freeSlots() override
Get free slots number.
std::vector< EventSlot > m_eventSlots
Vector of events slots.
StatusCode promoteToAsyncExecuted(unsigned int iAlgo, int si, IAlgorithm *algo, EventContext *)
The call to this method is triggered only from within the IOBoundAlgTask.
StatusCode deactivate()
Deactivate scheduler.
void dumpState() override
virtual StatusCode push(IAlgTask &task)=0
MsgStream & fatal() const
shortcut for the method msgStream(MSG::FATAL)
PrecedenceRulesGraph * getPrecedenceRulesGraph() const
Get the flow graph instance.
StatusCode updateStates(int si=-1, const std::string &algo_name=std::string())
Loop on algorithm in the slots and promote them to successive states (-1 means all slots...
MSG::Level msgLevel() const
get the output level from the embedded MsgStream
State
Execution states of the algorithms.
virtual StatusCode releaseAlgorithm(const std::string &name, IAlgorithm *&algo)=0
Release a certain algorithm.
SmartIF< ISvcLocator > & serviceLocator() const override
Retrieve pointer to service locator.
SmartIF< IAlgExecStateSvc > m_algExecStateSvc
Algorithm execution state manager.
Gaudi::Property< unsigned int > m_maxIOBoundAlgosInFlight
MsgStream & endmsg(MsgStream &s)
MsgStream Modifier: endmsg. Calls the output method of the MsgStream.
tbb::concurrent_bounded_queue< action > m_actionsQueue
Queue where closures are stored and picked for execution.
static GAUDI_API void setNumConcEvents(const std::size_t &nE)
static std::map< State, std::string > stateNames
std::thread m_thread
The thread in which the activate function runs.
StatusCode m_drain()
Drain the actions present in the queue.
StatusCode updateState(unsigned int iAlgo, State newState)