21 #include <unordered_set> 24 #include "boost/algorithm/string.hpp" 25 #include "boost/thread.hpp" 26 #include "boost/tokenizer.hpp" 28 #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 ForwardSchedulerSvc 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;
94 size_t numberOfWBSlots = m_whiteboard->getNumberOfStores();
95 if ( m_maxEventsInFlight != 0 ) {
96 warning() <<
"Property MaxEventsInFlight was set. This works but it's deprecated. " 97 <<
"Please migrate your code options files." <<
endmsg;
99 if ( m_maxEventsInFlight != (
int)numberOfWBSlots ) {
100 warning() <<
"In addition, the number of events in flight (" << m_maxEventsInFlight
101 <<
") differs from the slots in the whiteboard (" << numberOfWBSlots
102 <<
"). Setting the number of events in flight to " << numberOfWBSlots <<
endmsg;
110 m_maxEventsInFlight = numberOfWBSlots;
113 m_freeSlots = m_maxEventsInFlight;
115 if ( m_algosDependencies.size() != 0 ) {
116 warning() <<
" ##### Property AlgosDependencies is deprecated and ignored." 117 <<
" FIX your job options #####" <<
endmsg;
122 const unsigned int algsNumber = algos.
size();
123 info() <<
"Found " << algsNumber <<
" algorithms" <<
endmsg;
136 fatal() <<
"Could not convert IAlgorithm into Algorithm: this will result in a crash." <<
endmsg;
139 auto r = globalOutp.
insert(
id );
141 warning() <<
"multiple algorithms declare " <<
id <<
" as output! could be a single instance in multiple paths " 142 "though, or control flow may guarantee only one runs...!" 149 ostdd <<
"Data Dependencies for Algorithms:";
154 if (
nullptr == algoPtr ) {
155 fatal() <<
"Could not convert IAlgorithm into Algorithm for " << ialgoPtr->
name()
156 <<
": this will result in a crash." <<
endmsg;
160 ostdd <<
"\n " << algoPtr->
name();
165 ostdd <<
"\n o INPUT " << id;
166 if (
id.key().find(
":" ) != std::string::npos ) {
167 ostdd <<
" contains alternatives which require resolution...\n";
168 auto tokens = boost::tokenizer<boost::char_separator<char>>{
id.key(), boost::char_separator<char>{
":"}};
172 if ( itok != tokens.end() ) {
173 ostdd <<
"found matching output for " << *itok <<
" -- updating scheduler info\n";
174 id.updateKey( *itok );
176 error() <<
"failed to find alternate in global output list" 177 <<
" for id: " <<
id <<
" in Alg " << algoPtr->
name() <<
endmsg;
178 m_showDataDeps =
true;
181 algoDependencies.
insert(
id );
185 ostdd <<
"\n o OUTPUT " << id;
186 if (
id.key().find(
":" ) != std::string::npos ) {
187 error() <<
" in Alg " << algoPtr->
name() <<
" alternatives are NOT allowed for outputs! id: " <<
id <<
endmsg;
188 m_showDataDeps =
true;
197 if ( m_showDataDeps ) {
202 m_algname_vect.reserve( algsNumber );
203 unsigned int index = 0;
207 m_algname_index_map[
name] = index;
208 m_algname_vect.emplace_back( name );
209 if ( algo->name() == m_useDataLoader ) {
210 dataLoaderAlg = algo;
218 for (
auto o : globalInp ) {
219 if ( globalOutp.
find( o ) == globalOutp.
end() ) {
224 if ( unmetDep.
size() > 0 ) {
227 for (
auto& o : unmetDep ) {
228 ost <<
"\n o " << o <<
" required by Algorithm: ";
229 for (
size_t i = 0; i < m_algosDependencies.
size(); ++i ) {
230 if ( m_algosDependencies[i].find( o ) != m_algosDependencies[i].
end() ) {
231 ost <<
"\n * " << m_algname_vect[i];
236 if ( m_useDataLoader !=
"" ) {
238 if ( dataLoaderAlg ==
nullptr ) {
239 fatal() <<
"No DataLoader Algorithm \"" << m_useDataLoader.value()
240 <<
"\" found, and unmet INPUT dependencies " 246 info() <<
"Will attribute the following unmet INPUT dependencies to \"" << dataLoaderAlg->
type() <<
"/" 247 << dataLoaderAlg->name() <<
"\" Algorithm" << ost.
str() <<
endmsg;
252 fatal() <<
"Unable to dcast DataLoader \"" << m_useDataLoader.value() <<
"\" IAlg to Algorithm" <<
endmsg;
256 for (
auto&
id : unmetDep ) {
257 debug() <<
"adding OUTPUT dep \"" <<
id <<
"\" to " << dataLoaderAlg->
type() <<
"/" << dataLoaderAlg->name()
263 fatal() <<
"Auto DataLoading not requested, " 264 <<
"and the following unmet INPUT dependencies were found:" << ost.
str() <<
endmsg;
269 info() <<
"No unmet INPUT data dependencies were found" <<
endmsg;
275 unsigned int controlFlowNodeNumber = m_efManager.getCFGraph()->getControlFlowNodeCounter();
279 if ( !messageSvc.
isValid() ) error() <<
"Error retrieving MessageSvc interface IMessageSvc." <<
endmsg;
281 m_eventSlots.assign( m_maxEventsInFlight,
282 EventSlot( m_algosDependencies, algsNumber, controlFlowNodeNumber, messageSvc ) );
283 std::for_each( m_eventSlots.begin(), m_eventSlots.end(), [](
EventSlot& slot ) { slot.complete =
true; } );
286 info() <<
"Concurrency level information:" <<
endmsg;
287 info() <<
" o Number of events in flight: " << m_maxEventsInFlight <<
endmsg;
288 info() <<
" o Number of algorithms in flight: " << m_maxAlgosInFlight <<
endmsg;
289 info() <<
" o TBB thread pool size: " << m_threadPoolSize <<
endmsg;
293 if ( m_showControlFlow ) {
295 info() << m_efg->dumpControlFlow() <<
endmsg;
298 if ( m_showDataFlow ) {
299 warning() <<
"A 1-level data flow dump requested, but this feature is not supported" 300 <<
" by the ForwardScheduler any more. Use the AvalancheScheduler" 301 <<
" to dump as 1-level data flow, so the complete data flow graph." <<
endmsg;
320 info() <<
"Joining Scheduler thread" <<
endmsg;
325 error() <<
"problems in scheduler thread" <<
endmsg;
348 error() <<
"problems initializing ThreadPoolSvc" <<
endmsg;
360 info() <<
"Start checking the actionsQueue" <<
endmsg;
365 verbose() <<
"Action did not succeed (which is not bad per se)." <<
endmsg;
370 info() <<
"Terminating thread-pool resources" <<
endmsg;
372 error() <<
"Problems terminating thread pool" <<
endmsg;
431 if ( !eventContext ) {
446 const unsigned int thisSlotNum = eventContext->
slot();
449 fatal() <<
"The slot " << thisSlotNum <<
" is supposed to be a finished event but it's not" <<
endmsg;
453 debug() <<
"Executing event " << eventContext->
evt() <<
" on slot " << thisSlotNum <<
endmsg;
454 thisSlot.
reset( eventContext );
461 verbose() <<
"Pushing the action to update the scheduler for slot " << eventContext->
slot() <<
endmsg;
473 for (
auto context : eventContexts ) {
489 unsigned int slotNum = 0;
491 if ( not thisSlot.algsStates.allAlgsExecuted() and not thisSlot.complete ) {
516 debug() <<
"Popped slot " << eventContext->
slot() <<
"(event " << eventContext->
evt() <<
")" <<
endmsg;
529 debug() <<
"Try Pop successful slot " << eventContext->
slot() <<
"(event " << eventContext->
evt() <<
")" 549 fatal() <<
"*** Event " << eventContext->
evt() <<
" on slot " << eventContext->
slot() <<
" failed! ***" <<
endmsg;
554 info() <<
"Dumping Alg Exec State for slot " << eventContext->
slot() <<
":\n" << ost.
str() <<
endmsg;
617 eventSlotsPtrs.
reserve( eventsSlotsSize );
619 if ( !slotIt->complete ) eventSlotsPtrs.
push_back( &( *slotIt ) );
627 for (
EventSlot* thisSlotPtr : eventSlotsPtrs ) {
660 for (
auto it = thisAlgsStates.
begin( AlgsExecutionStates::State::CONTROLREADY );
661 it != thisAlgsStates.
end( AlgsExecutionStates::State::CONTROLREADY ); ++it ) {
667 verbose() <<
"Could not apply transition from " 673 for (
auto it = thisAlgsStates.
begin( AlgsExecutionStates::State::DATAREADY );
674 it != thisAlgsStates.
end( AlgsExecutionStates::State::DATAREADY ); ++it ) {
681 verbose() <<
"Could not apply transition from " 692 thisSlot.complete =
true;
698 debug() <<
"Event " << thisSlot.eventContext->evt() <<
" finished (slot " << thisSlot.eventContext->slot()
708 thisSlot.eventContext =
nullptr;
739 info() <<
"About to declare a stall" <<
endmsg;
762 outputMessageStream <<
"============================== Execution Task State =============================" 766 outputMessageStream << std::endl
767 <<
"============================== Scheduler State =================================" 773 if ( thisSlot.complete )
continue;
775 outputMessageStream <<
"----------- slot: " << thisSlot.eventContext->slot()
776 <<
" event: " << thisSlot.eventContext->evt() <<
" -----------" <<
std::endl;
778 if ( 0 > iSlot or iSlot == slotCount ) {
779 outputMessageStream <<
"Algorithms states:" <<
std::endl;
781 const DataObjIDColl& wbSlotContent( thisSlot.dataFlowMgr.content() );
782 for (
unsigned int algoIdx = 0; algoIdx < thisSlot.algsStates.size(); ++algoIdx ) {
783 outputMessageStream <<
" o " <<
index2algname( algoIdx ) <<
" [" 785 DataObjIDColl deps( thisSlot.dataFlowMgr.dataDependencies( algoIdx ) );
786 const int depsSize = deps.
size();
787 if ( depsSize == 0 ) outputMessageStream <<
" none";
790 for (
auto d : deps ) {
791 outputMessageStream << d <<
" ";
792 if ( wbSlotContent.find( d ) == wbSlotContent.end() ) {
798 if ( !missing.
empty() ) {
799 outputMessageStream <<
". The following are missing: ";
800 for (
auto d : missing ) {
801 outputMessageStream << d <<
" ";
809 outputMessageStream <<
"\nWhiteboard contents: " <<
std::endl;
810 for (
auto& product : wbSlotContent ) outputMessageStream <<
" o " << product <<
std::endl;
813 outputMessageStream <<
"\nControl Flow:" <<
std::endl;
817 outputMessageStream << cFlowStateStringStream.
str() <<
std::endl;
821 outputMessageStream <<
"=================================== END ======================================" <<
std::endl;
823 info() <<
"Dumping Scheduler State " << std::endl << outputMessageStream.
str() <<
endmsg;
869 if ( sc.isSuccess() ) {
872 fatal() <<
"Event context for algorithm " << algName <<
" is a nullptr (slot " << si <<
")" <<
endmsg;
876 auto promote2ExecutedClosure =
883 tbb::task* triggerAlgoStateUpdate =
887 triggerAlgoStateUpdate->set_ref_count( 1 );
889 tbb::task* algoTask =
new ( triggerAlgoStateUpdate->allocate_child() )
892 tbb::task::enqueue( *algoTask );
897 promote2ExecutedClosure();
901 debug() <<
"Algorithm " << algName <<
" was submitted on event " << eventContext->
evt() <<
" in slot " << si
908 if ( updateSc.isSuccess() )
927 if ( !castedAlgo )
fatal() <<
"The casting did not succeed!" <<
endmsg;
937 error() <<
"[Event " << eventContext->
evt() <<
", Slot " << eventContext->
slot() <<
"] " 938 <<
"Instance of algorithm " << algo->name() <<
" could not be properly put back." <<
endmsg;
953 for (
const auto& new_product : new_products )
958 debug() <<
"Algorithm " << algo->name() <<
" executed in slot " << si <<
". Algorithms scheduled are " 973 state = State::EVTACCEPTED;
975 state = State::EVTREJECTED;
1009 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
StatusCode initialize() override
virtual StatusCode acquireAlgorithm(const std::string &name, IAlgorithm *&algo, bool blocking=false)=0
Acquire a certain algorithm using its name.
StatusCode eventFailed(EventContext *eventContext)
Method to check if an event failed and take appropriate actions.
void updateDataObjectsCatalog(const DataObjIDColl &newProducts)
Update the catalog of available products in the slot.
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
MsgStream & info() const
shortcut for the method msgStream(MSG::INFO)
concurrency::recursive_CF::ExecutionFlowManager m_efManager
Member to take care of the control flow.
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.
StatusCode isStalled(int si)
Check if the scheduling is in a stall.
EventContext * eventContext
Cache for the eventContext.
Header file for class GaudiAlgorithm.
StatusCode updateStates(int si=-1)
Loop on algorithm in the slots and promote them to successive states (-1 means all slots...
StatusCode finalize() override
Finalise.
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?
SmartIF< IThreadPoolSvc > m_threadPoolSvc
The SchedulerSvc implements the IScheduler interface.
StatusCode pushNewEvent(EventContext *eventContext) override
Make an event available to the scheduler.
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.
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
virtual const std::string & type() const =0
The type of the algorithm.
tbb::task * execute() override
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)
MsgStream & error() const
shortcut for the method msgStream(MSG::ERROR)
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.
const DataObjIDColl & inputDataObjs() const override
unsigned int algname2index(const std::string &algoname)
Convert a name to an integer.
StatusCode promoteToExecuted(unsigned int iAlgo, int si, IAlgorithm *algo, EventContext *)
virtual void setEventStatus(const EventStatus::Status &sc, const EventContext &ctx)=0
unsigned int freeSlots() override
Get free slots number.
StatusCode pushNewEvents(std::vector< EventContext * > &eventContexts) override
#define DECLARE_SERVICE_FACTORY(x)
bool complete
Flags completion of the event.
Gaudi::Property< int > m_maxEventsInFlight
concurrency::recursive_CF::ControlFlowGraph * getCFGraph() const
The IAlgorithm is the interface implemented by the Algorithm base class.
GAUDI_API void setCurrentContext(const EventContext *ctx)
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.
void addDependency(const DataObjID &id, const Gaudi::DataHandle::Mode &mode) override
StatusCode tryPopFinishedEvent(EventContext *&eventContext) override
Try to fetch an event from the scheduler.
Base class from which all concrete algorithm classes should be derived.
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.
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< 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.
virtual const EventStatus::Status & eventStatus(const EventContext &ctx) const =0
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.
static std::mutex m_ssMut
const std::string & index2algname(unsigned int index)
Convert an integer to a name.
void updateEventState(AlgsExecutionStates &algo_states, std::vector< int > &node_decisions) const
Update states and decisions of algorithms.
bool rootDecisionResolved(const std::vector< int > &node_decisions) const
Check whether root decision was resolved.
std::atomic< ActivationState > m_isActive
Flag to track if the scheduler is active or not.
StatusCode initialize() override
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
void dumpState() override
SmartIF< ISvcLocator > & serviceLocator() const override
Retrieve pointer to service locator.
MsgStream & endmsg(MsgStream &s)
MsgStream Modifier: endmsg. Calls the output method of the MsgStream.
StatusCode promoteToDataReady(unsigned int iAlgo, int si)
static GAUDI_API void setNumConcEvents(const std::size_t &nE)
static std::map< State, std::string > stateNames
StatusCode updateState(unsigned int iAlgo, State newState)