31 #include <unordered_set> 34 #include "boost/thread.hpp" 37 #include "tbb/task_scheduler_init.h" 57 if ( !sc.
isSuccess() ) warning() <<
"Base class could not be initialized" <<
endmsg;
60 m_threadPoolSvc = serviceLocator()->service(
"ThreadPoolSvc" );
61 if ( !m_threadPoolSvc.isValid() ) {
62 fatal() <<
"Error retrieving ThreadPoolSvc" <<
endmsg;
67 info() <<
"Activating scheduler in a separate thread" <<
endmsg;
70 while ( m_isActive != ACTIVE ) {
72 fatal() <<
"Terminating initialization" <<
endmsg;
75 info() <<
"Waiting for ForwardSchedulerSvc to activate" <<
endmsg;
81 m_algResourcePool = serviceLocator()->service(
"AlgResourcePool" );
82 if ( !m_algResourcePool.isValid() ) {
83 fatal() <<
"Error retrieving AlgoResourcePool" <<
endmsg;
87 m_algExecStateSvc = serviceLocator()->service(
"AlgExecStateSvc");
88 if (!m_algExecStateSvc.isValid()) {
89 fatal() <<
"Error retrieving AlgExecStateSvc" <<
endmsg;
94 m_whiteboard = serviceLocator()->service( m_whiteboardSvcName );
95 if ( !m_whiteboard.isValid() ) {
96 fatal() <<
"Error retrieving EventDataSvc interface IHiveWhiteBoard." <<
endmsg;
102 size_t numberOfWBSlots = m_whiteboard->getNumberOfStores();
103 if ( m_maxEventsInFlight != 0 ) {
104 warning() <<
"Property MaxEventsInFlight was set. This works but it's deprecated. " 105 <<
"Please migrate your code options files." <<
endmsg;
107 if ( m_maxEventsInFlight != (
int)numberOfWBSlots ) {
108 warning() <<
"In addition, the number of events in flight (" << m_maxEventsInFlight
109 <<
") differs from the slots in the whiteboard (" << numberOfWBSlots
110 <<
"). Setting the number of events in flight to " << numberOfWBSlots <<
endmsg;
115 if ( m_useIOBoundAlgScheduler ) {
116 m_IOBoundAlgScheduler = serviceLocator()->service( m_IOBoundAlgSchedulerSvcName );
117 if ( !m_IOBoundAlgScheduler.isValid() )
118 fatal() <<
"Error retrieving IOBoundSchedulerAlgSvc interface IAccelerator." <<
endmsg;
121 m_maxEventsInFlight = numberOfWBSlots;
124 m_freeSlots = m_maxEventsInFlight;
126 if ( m_algosDependencies.size() != 0 ) {
127 warning() <<
" ##### Property AlgosDependencies is deprecated and ignored." 128 <<
" FIX your job options #####" <<
endmsg;
133 const unsigned int algsNumber = algos.
size();
134 info() <<
"Found " << algsNumber <<
" algorithms" <<
endmsg;
143 info() <<
"Data Dependencies for Algorithms:";
148 if (
nullptr == algoPtr )
149 fatal() <<
"Could not convert IAlgorithm into Algorithm: this will result in a crash." <<
endmsg;
151 info() <<
"\n " << algoPtr->
name();
157 info() <<
"\n o INPUT " << id;
158 algoDependencies.
insert(
id );
162 info() <<
"\n o OUTPUT " << id;
173 m_algname_vect.reserve( algsNumber );
174 unsigned int index = 0;
177 m_algname_index_map[
name] = index;
178 m_algname_vect.emplace_back( name );
185 for (
auto o : globalInp ) {
186 if ( globalOutp.
find( o ) == globalOutp.
end() ) {
191 if ( unmetDep.
size() > 0 ) {
192 fatal() <<
"The following unmet INPUT data dependencies were found: ";
193 for (
auto& o : unmetDep ) {
194 fatal() <<
"\n o " << o <<
" required by Algorithm: ";
195 for (
size_t i = 0; i < m_algosDependencies.
size(); ++i ) {
196 if ( m_algosDependencies[i].find( o ) != m_algosDependencies[i].
end() ) {
197 fatal() <<
"\n * " << m_algname_vect[i];
204 info() <<
"No unmet INPUT data dependencies were found" <<
endmsg;
209 if ( m_CFNext ) m_DFNext =
true;
210 if ( !m_CFNext && !m_optimizationMode.empty() ) {
211 fatal() <<
"Execution optimization is only available with the graph-based execution flow management" <<
endmsg;
216 m_efManager.initialize( algPool->
getExecutionFlowGraph(), m_algname_index_map, m_eventSlots, m_optimizationMode );
217 unsigned int controlFlowNodeNumber = m_efManager.getExecutionFlowGraph()->getControlFlowNodeCounter();
221 if ( !messageSvc.
isValid() ) error() <<
"Error retrieving MessageSvc interface IMessageSvc." <<
endmsg;
223 m_eventSlots.assign( m_maxEventsInFlight,
224 EventSlot( m_algosDependencies, algsNumber, controlFlowNodeNumber, messageSvc ) );
225 std::for_each( m_eventSlots.begin(), m_eventSlots.end(), [](
EventSlot& slot ) { slot.complete =
true; } );
228 info() <<
"Concurrency level information:" <<
endmsg;
229 info() <<
" o Number of events in flight: " << m_maxEventsInFlight <<
endmsg;
230 info() <<
" o Number of algorithms in flight: " << m_maxAlgosInFlight <<
endmsg;
231 info() <<
" o TBB thread pool size: " << m_threadPoolSize <<
endmsg;
234 if ( m_simulateExecution ) {
236 m_efManager.simulateExecutionFlow( vis );
255 info() <<
"Joining Scheduler thread" <<
endmsg;
260 error() <<
"problems in scheduler thread" <<
endmsg;
283 debug() <<
"ForwardSchedulerSvc::activate()" <<
endmsg;
286 error() <<
"problems initializing ThreadPoolSvc" <<
endmsg;
298 info() <<
"Start checking the actionsQueue" <<
endmsg;
303 verbose() <<
"Action did not succeed (which is not bad per se)." <<
endmsg;
308 info() <<
"Terminating thread-pool resources" <<
endmsg;
310 error() <<
"Problems terminating thread pool" <<
endmsg;
369 if ( !eventContext ) {
384 const unsigned int thisSlotNum = eventContext->
slot();
387 fatal() <<
"The slot " << thisSlotNum <<
" is supposed to be a finished event but it's not" <<
endmsg;
391 info() <<
"Executing event " << eventContext->
evt() <<
" on slot " << thisSlotNum <<
endmsg;
392 thisSlot.
reset( eventContext );
404 verbose() <<
"Pushing the action to update the scheduler for slot " << eventContext->
slot() <<
endmsg;
416 for (
auto context : eventContexts ) {
433 unsigned int slotNum = 0;
435 if ( not thisSlot.algsStates.allAlgsExecuted() and not thisSlot.complete ) {
460 debug() <<
"Popped slot " << eventContext->
slot() <<
"(event " 474 debug() <<
"Try Pop successful slot " << eventContext->
slot() <<
"(event " << eventContext->
evt() <<
")" 494 fatal() <<
"*** Event " << eventContext->
evt() <<
" on slot " 495 << eventContext->
slot() <<
" failed! ***" <<
endmsg;
500 info() <<
"Dumping Alg Exec State for slot " << eventContext->
slot()
564 eventSlotsPtrs.
reserve( eventsSlotsSize );
566 if ( !slotIt->complete ) eventSlotsPtrs.
push_back( &( *slotIt ) );
574 for (
EventSlot* thisSlotPtr : eventSlotsPtrs ) {
586 if ( !algo_name.
empty() )
614 for (
auto it = thisAlgsStates.
begin( AlgsExecutionStates::State::CONTROLREADY );
615 it != thisAlgsStates.
end( AlgsExecutionStates::State::CONTROLREADY ); ++it ) {
621 verbose() <<
"Could not apply transition from " 623 <<
" for algorithm " <<
index2algname(algIndex) <<
" on processing slot " << iSlot <<
endmsg;
629 auto comp_nodes = [
this](
const uint& i,
const uint& j ) {
635 for (
auto it = thisAlgsStates.
begin( AlgsExecutionStates::State::DATAREADY );
636 it != thisAlgsStates.
end( AlgsExecutionStates::State::DATAREADY ); ++it )
664 while ( !buffer.
empty() ) {
665 bool IOBound =
false;
675 if (partial_sc.isFailure())
676 verbose() <<
"Could not apply transition from " 684 for (
auto it = thisAlgsStates.
begin( AlgsExecutionStates::State::DATAREADY );
685 it != thisAlgsStates.
end( AlgsExecutionStates::State::DATAREADY ); ++it ) {
688 bool IOBound =
false;
699 verbose() <<
"Could not apply transition from " 701 <<
" for algorithm " <<
index2algname(algIndex) <<
" on processing slot " << iSlot <<
endmsg;
708 s << algo_name <<
", " << thisAlgsStates.
sizeOfSubset(State::CONTROLREADY) <<
", " 709 << thisAlgsStates.
sizeOfSubset(State::DATAREADY) <<
", " 710 << thisAlgsStates.
sizeOfSubset(State::SCHEDULED) <<
", " 714 :
std::to_string(tbb::task_scheduler_init::default_num_threads());
716 myfile.
open(
"IntraEventConcurrencyDynamics_" + threads +
"T.csv",
std::ios::app );
727 thisSlot.complete =
true;
733 debug() <<
"Event " << thisSlot.eventContext->evt() <<
" finished (slot " 734 << thisSlot.eventContext->slot() <<
")." <<
endmsg;
743 thisSlot.eventContext =
nullptr;
774 info() <<
"About to declare a stall" <<
endmsg;
797 outputMessageStream <<
"============================== Execution Task State =============================" 801 outputMessageStream << std::endl
802 <<
"============================== Scheduler State =================================" 808 if ( thisSlot.complete )
continue;
810 outputMessageStream <<
"----------- slot: " << thisSlot.eventContext->slot()
811 <<
" event: " << thisSlot.eventContext->evt() <<
" -----------" <<
std::endl;
813 if ( 0 > iSlot or iSlot == slotCount ) {
814 outputMessageStream <<
"Algorithms states:" <<
std::endl;
816 const DataObjIDColl& wbSlotContent( thisSlot.dataFlowMgr.content() );
817 for (
unsigned int algoIdx = 0; algoIdx < thisSlot.algsStates.size(); ++algoIdx ) {
818 outputMessageStream <<
" o " <<
index2algname( algoIdx ) <<
" [" 820 DataObjIDColl deps( thisSlot.dataFlowMgr.dataDependencies( algoIdx ) );
821 const int depsSize = deps.
size();
822 if ( depsSize == 0 ) outputMessageStream <<
" none";
825 for (
auto d : deps ) {
826 outputMessageStream << d <<
" ";
827 if ( wbSlotContent.find( d ) == wbSlotContent.end() ) {
833 if ( !missing.
empty() ) {
834 outputMessageStream <<
". The following are missing: ";
835 for (
auto d : missing ) {
836 outputMessageStream << d <<
" ";
844 outputMessageStream <<
"\nWhiteboard contents: " <<
std::endl;
845 for (
auto& product : wbSlotContent ) outputMessageStream <<
" o " << product <<
std::endl;
848 outputMessageStream <<
"\nControl Flow:" <<
std::endl;
852 outputMessageStream << cFlowStateStringStream.
str() <<
std::endl;
856 outputMessageStream <<
"=================================== END ======================================" <<
std::endl;
858 info() <<
"Dumping Scheduler State " << std::endl << outputMessageStream.
str() <<
endmsg;
883 sc =
m_eventSlots[si].dataFlowMgr.canAlgorithmRun( iAlgo );
911 if ( sc.isSuccess() ) {
915 fatal() <<
"Event context for algorithm " << algName <<
" is a nullptr (slot " << si <<
")" <<
endmsg;
921 tbb::task* t =
new( tbb::task::allocate_root() )
924 tbb::task::enqueue( *t);
932 debug() <<
"Algorithm " << algName <<
" was submitted on event " << eventContext->evt() <<
" in slot " << si
939 if (updateSc.isSuccess())
964 if ( sc.isSuccess() ) {
968 fatal() <<
"[Asynchronous] Event context for algorithm " << algName <<
" is a nullptr (slot " << si <<
")" 980 debug() <<
"[Asynchronous] Algorithm " << algName <<
" was submitted on event " 981 << eventContext->evt() <<
" in slot " << si
986 if (updateSc.isSuccess())
989 <<
" to SCHEDULED on slot " << si <<
endmsg;
993 debug() <<
"[Asynchronous] Could not acquire instance for algorithm " <<
index2algname( iAlgo ) <<
" on slot " 1009 if ( !castedAlgo )
fatal() <<
"The casting did not succeed!" <<
endmsg;
1019 error() <<
"[Event " << eventContext->
evt() <<
", Slot " << eventContext->
slot() <<
"] " 1020 <<
"Instance of algorithm " << algo->name() <<
" could not be properly put back." <<
endmsg;
1036 for (
const auto& new_product : new_products )
1042 debug() <<
"Algorithm " << algo->name() <<
" executed in slot " << si <<
". Algorithms scheduled are " 1059 state = State::EVTACCEPTED;
1061 state = State::EVTREJECTED;
1084 if ( !castedAlgo )
fatal() <<
"[Asynchronous] The casting did not succeed!" <<
endmsg;
1094 error() <<
"[Asynchronous] [Event " << eventContext->
evt() <<
", Slot " << eventContext->
slot() <<
"] " 1095 <<
"Instance of algorithm " << algo->name() <<
" could not be properly put back." <<
endmsg;
1111 for (
const auto& new_product : new_products)
1113 debug() <<
"Found in WB [" << si <<
"]: " << new_product <<
endmsg;
1118 debug() <<
"[Asynchronous] Algorithm " << algo->name() <<
" executed in slot " << si
1132 debug() <<
"[Asynchronous] Trying to handle execution result of " 1136 state = State::EVTACCEPTED;
1138 state = State::EVTREJECTED;
1172 error() <<
"could not find Alg " << a->
name() <<
" in Scheduler!" <<
endmsg;
virtual StatusCode initPool(const int &poolSize)=0
Initializes the thread pool.
StatusCode deactivate()
Deactivate scheduler.
bool algsPresent(State state) const
Wrapper around I/O-bound Gaudi-algorithms.
StatusCode initialize() override
Gaudi::Property< bool > m_CFNext
virtual StatusCode acquireAlgorithm(const std::string &name, IAlgorithm *&algo, bool blocking=false)=0
Acquire a certain algorithm using its name.
StatusCode promoteToAsyncScheduled(unsigned int iAlgo, int si)
virtual void setEventStatus(const EventStatus::Status &sc)=0
StatusCode eventFailed(EventContext *eventContext)
Method to check if an event failed and take appropriate actions.
void updateEventState(AlgsExecutionStates &algo_states, std::vector< int > &node_decisions) const
Update the state of algorithms to controlready, where possible.
void updateDataObjectsCatalog(const DataObjIDColl &newProducts)
Update the catalog of available products in the slot.
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.
SmartIF< IAlgResourcePool > m_algResourcePool
Cache for the algorithm resource pool.
const std::string & name() const override
The identifying name of the algorithm object.
StatusCode finalize() override
virtual const EventStatus::Status & eventStatus() const =0
MsgStream & info() const
shortcut for the method msgStream(MSG::INFO)
bool algoDataDependenciesSatisfied(const std::string &algo_name, const int &slotNum) const
Check all data dependencies of an algorithm are satisfied.
AlgsExecutionStates algsStates
Vector of algorithms states.
bool isSuccess() const
Test for a status code of SUCCESS.
StatusCode isStalled(int si)
Check if the scheduling is in a stall.
const DataObjIDColl & inputDataObjs() const override
EventContext * eventContext
Cache for the eventContext.
Header file for class GaudiAlgorithm.
StatusCode finalize() override
Finalise.
MsgStream & verbose() const
shortcut for the method msgStream(MSG::VERBOSE)
void setContext(const EventContext *context) override
set the context
virtual bool filterPassed() const =0
Did this algorithm pass or fail its filter criterion for the last event?
unsigned int m_IOBoundAlgosInFlight
Number of algoritms presently in flight.
SmartIF< IThreadPoolSvc > m_threadPoolSvc
void touchReadyAlgorithms(IGraphVisitor &visitor) const
Promote all algorithms, ready to be executed, to DataReady state.
T duration_cast(T...args)
The SchedulerSvc implements the IScheduler interface.
StatusCode pushNewEvent(EventContext *eventContext) override
Make an event available to the scheduler.
size_t sizeOfSubset(State state) const
A visitor, performing full top-down traversals of a graph.
StatusCode promoteToAsyncExecuted(unsigned int iAlgo, int si, IAlgorithm *algo, EventContext *)
The call to this method is triggered only from within the IOBoundAlgTask.
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.
bool isIOBound() const
Check if algorithm is I/O-bound.
SmartIF< IHiveWhiteBoard > m_whiteboard
A shortcut to the whiteboard.
StatusCode m_drain()
Drain the actions present in the queue.
Gaudi::Property< unsigned int > m_maxAlgosInFlight
Gaudi::Property< std::string > m_optimizationMode
tbb::task * execute() override
virtual void dump(std::ostringstream &ost) const =0
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.
void addAlg(Algorithm *, EventContext *, pthread_t)
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.
DataFlowManager dataFlowMgr
DataFlowManager of this slot.
virtual StatusCode selectStore(size_t partitionIndex)=0
Activate an given 'slot' for all subsequent calls within the same thread id.
The AlgsExecutionStates encodes the state machine for the execution of algorithms within a single eve...
unsigned int m_algosInFlight
Number of algoritms presently in flight.
MsgStream & warning() const
shortcut for the method msgStream(MSG::WARNING)
tbb::concurrent_bounded_queue< EventContext * > m_finishedEvents
Queue of finished events.
std::thread m_thread
The thread in which the activate function runs.
virtual StatusCode getNewDataObjects(DataObjIDColl &products)=0
Get the latest new data objects registred in store.
std::vector< std::string > m_algname_vect
Vector to bookkeep the information necessary to the index2name conversion.
static std::list< SchedulerState > m_sState
std::vector< EventSlot > m_eventSlots
Vector of events slots.
StatusCode promoteToScheduled(unsigned int iAlgo, int si)
This class is used for returning status codes from appropriate routines.
Gaudi::Property< unsigned int > m_maxIOBoundAlgosInFlight
unsigned int algname2index(const std::string &algoname)
Convert a name to an integer.
StatusCode promoteToExecuted(unsigned int iAlgo, int si, IAlgorithm *algo, EventContext *)
The call to this method is triggered only from within the AlgoExecutionTask.
const DataObjIDColl & outputDataObjs() const override
unsigned int freeSlots() override
Get free slots number.
StatusCode pushNewEvents(std::vector< EventContext * > &eventContexts) override
virtual concurrency::ExecutionFlowGraph * getExecutionFlowGraph() const
#define DECLARE_SERVICE_FACTORY(x)
bool complete
Flags completion of the event.
Gaudi::Property< int > m_maxEventsInFlight
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...
The IAlgorithm is the interface implemented by the Algorithm base class.
Gaudi::Property< bool > m_DFNext
tbb::concurrent_bounded_queue< action > m_actionsQueue
Queue where closures are stored and picked for execution.
bool m_updateNeeded
Keep track of update actions scheduled.
StatusCode tryPopFinishedEvent(EventContext *&eventContext) override
Try to fetch an event from the scheduler.
SmartIF< IAccelerator > m_IOBoundAlgScheduler
A shortcut to IO-bound algorithm scheduler.
Base class from which all concrete algorithm classes should be derived.
Gaudi::Property< bool > m_useIOBoundAlgScheduler
std::unordered_map< std::string, unsigned int > m_algname_index_map
Map to bookkeep the information necessary to the name2index conversion.
void activate()
Activate scheduler.
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.
SmartIF< IAlgExecStateSvc > m_algExecStateSvc
Algorithm execution state manager.
Iterator begin(State kind)
StatusCode promoteToControlReady(unsigned int iAlgo, int si)
Algorithm promotion: Accepted by the control flow.
concurrency::ExecutionFlowManager m_efManager
Member to take care of the control flow.
StatusCode popFinishedEvent(EventContext *&eventContext) override
Blocks until an event is availble.
void dumpSchedulerState(int iSlot)
Dump the state of the scheduler.
Class representing the event slot.
Gaudi::Property< bool > m_dumpIntraEventDynamics
static std::mutex m_ssMut
const std::string & index2algname(unsigned int index)
Convert an integer to a name.
friend class IOBoundAlgTask
friend class AlgoExecutionTask
virtual StatusCode push(IAlgTask &task)=0
ExecutionFlowGraph * getExecutionFlowGraph() const
Get the flow graph instance.
std::atomic< ActivationState > m_isActive
Flag to track if the scheduler is active or not.
MsgStream & fatal() const
shortcut for the method msgStream(MSG::FATAL)
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.
Gaudi::Property< int > m_threadPoolSize
AlgorithmNode * getAlgorithmNode(const std::string &algoName) const
Get the AlgorithmNode from by algorithm name using graph index.
void dumpState() override
SmartIF< ISvcLocator > & serviceLocator() const override
Retrieve pointer to service locator.
const std::chrono::system_clock::time_point getInitTime() const
MsgStream & endmsg(MsgStream &s)
MsgStream Modifier: endmsg. Calls the output method of the MsgStream.
StatusCode promoteToDataReady(unsigned int iAlgo, int si)
static std::map< State, std::string > stateNames
StatusCode updateState(unsigned int iAlgo, State newState)