The Gaudi Framework  v33r0 (d5ea422b)
ServiceManager.cpp
Go to the documentation of this file.
1 /***********************************************************************************\
2 * (c) Copyright 1998-2019 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 \***********************************************************************************/
11 // Include files
12 #include "ServiceManager.h"
15 #include "GaudiKernel/IService.h"
16 #include "GaudiKernel/Incident.h"
17 #include "GaudiKernel/MsgStream.h"
19 #include "GaudiKernel/Service.h"
20 #include "GaudiKernel/SmartIF.h"
21 #include "GaudiKernel/System.h"
23 #include "GaudiKernel/reverse.h"
24 
25 #include <algorithm>
26 #include <cassert>
27 #include <functional>
28 #include <iostream>
29 
30 #define ON_DEBUG if ( msgLevel( MSG::DEBUG ) )
31 #define ON_VERBOSE if ( msgLevel( MSG::VERBOSE ) )
32 
33 #define DEBMSG ON_DEBUG debug()
34 #define VERMSG ON_VERBOSE verbose()
35 
37 static SmartIF<IService> no_service;
38 
40 namespace {
41  template <typename C>
42  std::vector<IService*> activeSvc( const C& lst ) {
44  v.reserve( lst.size() );
45  for ( auto& i : lst ) {
46  if ( i.active ) v.push_back( i.service.get() );
47  }
48  return v;
49  }
50 } // namespace
51 
52 // constructor
54  : base_class( application, IService::interfaceID() ), m_appSvc( application ) {
55  // Set the service locator to myself
56  m_svcLocator = this;
57  addRef(); // increase ref count, so we live forever...
58 }
59 
60 // destructor
62  //-- inform the orphan services that I am gone....
63  for ( auto& svc : m_listsvc ) svc.service->setServiceManager( nullptr );
64 }
65 
66 //------------------------------------------------------------------------------
67 // Instantiate a service
69 //------------------------------------------------------------------------------
70 {
71  // Check if the service is already existing
72  if ( existsService( typeName.name() ) ) {
73  // return an error because a service with that name already exists
74  return no_service;
75  }
76 
77  const std::string& name = typeName.name();
78  std::string type = typeName.type();
79  if ( !typeName.haveType() ) { // the type is not explicit
80  // see we have some specific type mapping for the name
81  auto it = m_maptype.find( typeName.name() );
82  if ( it != m_maptype.end() ) {
83  type = it->second; // use the declared type
84  }
85  }
86 
88  auto ip = type.find( "__" );
89  if ( ip != std::string::npos ) type.erase( ip, type.length() );
90 
91  IService* service = Service::Factory::create( type, name, this ).release();
92  if ( !service ) {
93  fatal() << "No Service factory for " << type << " available." << endmsg;
94  return no_service;
95  }
96  // Check the compatibility of the version of the interface obtained
97  if ( !isValidInterface( service ) ) {
98  fatal() << "Incompatible interface IService version for " << type << endmsg;
99  return no_service;
100  }
101 
103  service->setServiceManager( this );
104  return m_listsvc.back().service; // DANGER: returns a reference to a SmartIF in m_listsvc, and hence does no longer
105  // allow relocations of those...
106 }
107 
108 //------------------------------------------------------------------------------
109 // add a service to the managed list
111 //------------------------------------------------------------------------------
112 {
113  ListSvc::iterator it = find( svc );
114  LockGuard_t lck( m_gLock );
115  if ( it != m_listsvc.end() ) {
116  it->priority = prio; // if the service is already known, it is equivalent to a setPriority
117  it->active = true; // and make it active
118  } else {
119  m_listsvc.emplace_back( svc, prio, true );
120  }
121  return StatusCode::SUCCESS;
122 }
123 
124 //------------------------------------------------------------------------------
125 // add the service with the give type and name to the active list
127 //------------------------------------------------------------------------------
128 {
129  auto it = find( typeName.name() ); // try to find the service by name
130  if ( it == m_listsvc.end() ) { // not found
131  // If the service does not exist, we create it
132  SmartIF<IService>& svc =
133  createService( typeName ); // WARNING: svc is now a reference to something that lives in m_listsvc
134  if ( !svc ) return StatusCode::FAILURE;
135  it = find( svc.get() ); // now it is in the list because createService added it
136  it->priority = prio;
138  if ( targetFSMState() >= Gaudi::StateMachine::INITIALIZED ) { // WARNING: this can trigger a recursion!!!
139  sc = svc->sysInitialize();
140  if ( sc.isSuccess() && targetFSMState() >= Gaudi::StateMachine::RUNNING ) { sc = svc->sysStart(); }
141  }
142  if ( sc.isFailure() ) { // if initialization failed, remove it from the list
143  error() << "Unable to initialize service \"" << typeName.name() << "\"" << endmsg;
144  LockGuard_t lck( m_gLock );
145  m_listsvc.erase( it );
146  // Note: removing it from the list + the SmartIF going out of scope should trigger the delete
147  // delete svc.get();
148  return sc;
149  }
150  // initialization successful, we can work with the service
151  // Move the just initialized service to the back of the list
152  // (we care more about order of initialization than of creation)
153  LockGuard_t lck( m_gLock );
154  m_listsvc.push_back( *it );
155  m_listsvc.erase( it );
156  it = std::prev( std::end( m_listsvc ) ); // last entry (the iterator was invalidated by erase)
157  } else {
158  // if the service is already known, it is equivalent to a setPriority
159  it->priority = prio;
160  }
161  // 'it' is defined because either we found the service or we created it
162  // Now we can activate the service
163  it->active = true; // and make it active
164  return StatusCode( StatusCode::SUCCESS, true );
165 }
166 
167 //------------------------------------------------------------------------------
168 // Returns a smart pointer to a service.
170  const std::string& name = typeName.name();
171 
172  // Acquire the RAII lock to avoid simultaneous attempts from different threads to initialize a service
173 
174  Mutex_t* imut;
175  {
176  // get the global lock, then extract/create the service specific mutex
177  // then release global lock
178 
179  LockGuard_t lk( m_gLock );
180  auto mit = m_lockMap.find( name );
181  if ( mit == m_lockMap.end() ) {
183  .first;
184  }
185  imut = &mit->second;
186  }
187 
188  {
189  // now we have the service specific lock on the above mutex
190  LockGuard_t lk2( *imut );
191 
192  auto it = find( name );
193 
194  if ( it != m_listsvc.end() ) {
195  if ( m_loopCheck && ( createIf && it->service->FSMState() == Gaudi::StateMachine::CONFIGURED ) ) {
196  error() << "Initialization loop detected when creating service \"" << name << "\"" << endmsg;
197  return no_service;
198  }
199  return it->service;
200  }
201 
202  // Service not found. The user may be interested in one of the interfaces
203  // of the application manager itself
204  if ( name == "ApplicationMgr" || name == "APPMGR" || name == "" ) { return m_appSvc; }
205 
206  // last resort: we try to create the service
207  if ( createIf && addService( typeName ).isSuccess() ) { return find( name )->service; }
208 
209  return no_service;
210  }
211 }
212 
213 //------------------------------------------------------------------------------
215 //------------------------------------------------------------------------------
216 {
219  []( ListSvc::const_reference i ) { return i.service.get(); } );
220  return m_listOfPtrs;
221 }
222 
223 //------------------------------------------------------------------------------
225 //------------------------------------------------------------------------------
226 {
227  return find( name ) != m_listsvc.end();
228 }
229 
230 //------------------------------------------------------------------------------
232 //------------------------------------------------------------------------------
233 {
234  auto it = find( svc );
235  if ( it == m_listsvc.end() ) return StatusCode( StatusCode::FAILURE, true );
236  m_listsvc.erase( it );
237  return StatusCode( StatusCode::SUCCESS, true );
238 }
239 
240 //------------------------------------------------------------------------------
242 //------------------------------------------------------------------------------
243 {
244  auto it = find( name );
245  if ( it == m_listsvc.end() ) return StatusCode::FAILURE;
246  m_listsvc.erase( it );
247  return StatusCode::SUCCESS;
248 }
249 
250 //------------------------------------------------------------------------------
252 //------------------------------------------------------------------------------
253 {
254  // once we get to C++17, replace with m_maptype.insert_or_assign...
255  auto p = m_maptype.emplace( svcname, svctype );
256  if ( !p.second ) p.first->second = svctype;
257  return StatusCode::SUCCESS;
258 }
259 
260 //------------------------------------------------------------------------------
262 //------------------------------------------------------------------------------
263 {
264  // ensure that the list is ordered by priority
265  m_listsvc.sort();
266  // we work on a copy to avoid to operate twice on the services created on demand
267  // which are already in the correct state.
268 
269  StatusCode sc( StatusCode::SUCCESS, true );
270  // call initialize() for all services
271  for ( auto& it : activeSvc( m_listsvc ) ) {
272  const std::string& name = it->name();
273  switch ( it->FSMState() ) {
275  DEBMSG << "Service " << name << " already initialized" << endmsg;
276  break;
278  DEBMSG << "Initializing service " << name << endmsg;
279  sc = it->sysInitialize();
280  if ( !sc.isSuccess() ) {
281  error() << "Unable to initialize Service: " << name << endmsg;
282  return sc;
283  }
284  break;
285  default:
286  error() << "Service " << name << " not in the correct state to be initialized (" << it->FSMState() << ")"
287  << endmsg;
288  return StatusCode::FAILURE;
289  }
290  }
291  return StatusCode::SUCCESS;
292 }
293 
294 //------------------------------------------------------------------------------
296 //------------------------------------------------------------------------------
297 {
298  // ensure that the list is ordered by priority
299  m_listsvc.sort();
300  // we work on a copy to avoid to operate twice on the services created on demand
301  // (which are already in the correct state.
302  // only act on active services
303  StatusCode sc( StatusCode::SUCCESS, true );
304  // call initialize() for all services
305  for ( auto& it : activeSvc( m_listsvc ) ) {
306  const std::string& name = it->name();
307  switch ( it->FSMState() ) {
309  DEBMSG << "Service " << name << " already started" << endmsg;
310  break;
312  DEBMSG << "Starting service " << name << endmsg;
313  sc = it->sysStart();
314  if ( !sc.isSuccess() ) {
315  error() << "Unable to start Service: " << name << endmsg;
316  return sc;
317  }
318  break;
319  default:
320  error() << "Service " << name << " not in the correct state to be started (" << it->FSMState() << ")" << endmsg;
321  return StatusCode::FAILURE;
322  }
323  }
324  return StatusCode::SUCCESS;
325 }
326 
327 //------------------------------------------------------------------------------
329 //------------------------------------------------------------------------------
330 {
331  // ensure that the list is ordered by priority
332  m_listsvc.sort();
333  // we work on a copy to avoid to operate twice on the services created on demand
334  // which are already in the correct state.
335  // only act on active services
336 
337  StatusCode sc( StatusCode::SUCCESS, true );
338  // call stop() for all services
339  for ( const auto& svc : reverse( activeSvc( m_listsvc ) ) ) {
340  const std::string& name = svc->name();
341  switch ( svc->FSMState() ) {
343  DEBMSG << "Service " << name << " already stopped" << endmsg;
344  break;
346  DEBMSG << "Stopping service " << name << endmsg;
347  sc = svc->sysStop();
348  if ( !sc.isSuccess() ) {
349  error() << "Unable to stop Service: " << name << endmsg;
350  return sc;
351  }
352  break;
353  default:
354  DEBMSG << "Service " << name << " not in the correct state to be stopped (" << svc->FSMState() << ")" << endmsg;
355  return StatusCode::FAILURE;
356  }
357  }
358  return StatusCode::SUCCESS;
359 }
360 
361 //------------------------------------------------------------------------------
363 //------------------------------------------------------------------------------
364 {
365  // ensure that the list is ordered by priority
366  m_listsvc.sort();
367  // we work on a copy to avoid to operate twice on the services created on demand
368  // which are already in the correct state.
369  // only act on active services
370  StatusCode sc( StatusCode::SUCCESS, true );
371  // Re-Initialize all services
372  for ( auto& svc : activeSvc( m_listsvc ) ) {
373  sc = svc->sysReinitialize();
374  if ( !sc.isSuccess() ) {
375  error() << "Unable to re-initialize Service: " << svc->name() << endmsg;
376  return StatusCode::FAILURE;
377  }
378  }
379  return StatusCode::SUCCESS;
380 }
381 
382 //------------------------------------------------------------------------------
384 //------------------------------------------------------------------------------
385 {
386  // ensure that the list is ordered by priority
387  m_listsvc.sort();
388  // we work on a copy to avoid to operate twice on the services created on demand
389  // which are already in the correct state.
390  // only act on active services
391  StatusCode sc( StatusCode::SUCCESS, true );
392  // Re-Start all services
393  for ( auto& svc : activeSvc( m_listsvc ) ) {
394  sc = svc->sysRestart();
395  if ( !sc.isSuccess() ) {
396  error() << "Unable to re-start Service: " << svc->name() << endmsg;
397  return StatusCode::FAILURE;
398  }
399  }
400  return StatusCode::SUCCESS;
401 }
402 
403 //------------------------------------------------------------------------------
405 //------------------------------------------------------------------------------
406 {
407  // make sure that HistogramDataSvc and THistSvc get finalized after the
408  // ToolSvc, and the FileMgr and StatusCodeSvc after that
409  int pri_tool = getPriority( "ToolSvc" );
410  if ( pri_tool != 0 ) {
411  setPriority( "THistSvc", pri_tool - 10 ).ignore();
412  setPriority( "ChronoStatSvc", pri_tool - 20 ).ignore();
413  setPriority( "AuditorSvc", pri_tool - 30 ).ignore();
414  setPriority( "NTupleSvc", pri_tool - 10 ).ignore();
415  setPriority( "HistogramDataSvc", pri_tool - 10 ).ignore();
416  // Preserve the relative ordering between HistogramDataSvc and HistogramPersistencySvc
417  setPriority( "HistogramPersistencySvc", pri_tool - 20 ).ignore();
418  setPriority( "HistorySvc", pri_tool - 30 ).ignore();
419  setPriority( "FileMgr", pri_tool - 40 ).ignore();
420  }
421 
422  // get list of PostFinalize clients
424  auto p_inc = service<IIncidentSvc>( "IncidentSvc", false );
425  if ( p_inc ) {
426  p_inc->getListeners( postFinList, IncidentType::SvcPostFinalize );
427  p_inc.reset();
428  }
429 
430  // make sure the StatusCodeSvc gets finalized really late:
431  setPriority( "StatusCodeSvc", -9999 ).ignore();
432 
433  // ensure that the list is ordered by priority
434  m_listsvc.sort();
435  // dump();
436 
437  StatusCode sc( StatusCode::SUCCESS, true );
438  {
439  // we work on a copy to avoid to operate twice on the services created on demand
440  // which are already in the correct state.
441  // only act on active services
442  // call finalize() for all services in reverse order
443  for ( const auto& svc : reverse( activeSvc( m_listsvc ) ) ) {
444  const std::string& name = svc->name();
445  // ignore the current state for the moment
446  // if( Gaudi::StateMachine::INITIALIZED == svc->state() )
447  DEBMSG << "Finalizing service " << name << endmsg;
448  if ( !svc->sysFinalize().isSuccess() ) {
449  warning() << "Finalization of service " << name << " failed" << endmsg;
450  sc = StatusCode::FAILURE;
451  }
452  }
453  }
454 
455  // call SvcPostFinalize on all clients
456  if ( !postFinList.empty() ) {
457  DEBMSG << "Will call SvcPostFinalize for " << postFinList.size() << " clients" << endmsg;
458  Incident inc( "ServiceManager", IncidentType::SvcPostFinalize );
459  for ( auto& itr : postFinList ) itr->handle( inc );
460  }
461 
462  // loop over all Active Services, removing them one by one.
463  // They should be deleted because the reference counting goes to 0.
464  DEBMSG << "Looping over all active services..." << endmsg;
465  auto it = m_listsvc.begin();
466  while ( it != m_listsvc.end() ) {
467  DEBMSG << "---- " << it->service->name() << " (refCount = " << it->service->refCount() << ")" << endmsg;
468  if ( it->service->refCount() < 1 ) {
469  warning() << "Too low reference count for " << it->service->name() << " (should not go below 1 at this point)"
470  << endmsg;
471  it->service->addRef();
472  }
473  if ( it->active ) {
474  it = m_listsvc.erase( it );
475  } else {
476  ++it;
477  }
478  }
479  return sc;
480 }
481 
482 //------------------------------------------------------------------------------
484  //------------------------------------------------------------------------------
485  auto it = find( name );
486  return ( it != m_listsvc.end() ) ? it->priority : 0;
487 }
488 
489 //------------------------------------------------------------------------------
491  //------------------------------------------------------------------------------
492  auto it = find( name );
493  if ( it == m_listsvc.end() ) return StatusCode::FAILURE;
494  it->priority = prio;
495  return StatusCode::SUCCESS;
496 }
497 
498 //------------------------------------------------------------------------------
499 // Get the value of the initialization loop check flag.
500 //------------------------------------------------------------------------------
502 //------------------------------------------------------------------------------
503 // Set the value of the initialization loop check flag.
504 //------------------------------------------------------------------------------
506 
507 //------------------------------------------------------------------------------
508 // Dump out contents of service list
509 //------------------------------------------------------------------------------
510 void ServiceManager::dump() const {
511 
512  auto& log = info();
513  log << "\n"
514  << "===================== listing all services ===================\n"
515  << " prior ref name active\n";
516 
517  for ( const auto& svc : m_listsvc ) {
518 
519  log.width( 6 );
520  log.flags( std::ios_base::right );
521  log << svc.priority << " ";
522  log.width( 5 );
523  log << svc.service->refCount() << " ";
524  log.width( 30 );
525  log.flags( std::ios_base::left );
526  log << svc.service->name() << " ";
527  log.width( 2 );
528  log << svc.active << std::endl;
529  }
530 
531  log << "=================================================================\n";
532  log << endmsg;
533 }
534 
536  resetMessaging();
537  for ( auto& svcItem : m_listsvc ) {
538  const auto svc = dynamic_cast<Service*>( svcItem.service.get() );
539  if ( svc ) svc->resetMessaging();
540  }
541 }
542 
The ServiceManager class is in charge of the creation of concrete instances of Services.
std::list< IService * > m_listOfPtrs
List of pointers to the know services used to implement getServices()
Gaudi::StateMachine::State targetFSMState() const override
When we are in the middle of a transition, get the state where the transition is leading us.
void setLoopCheckEnabled(bool en) override
Set the value of the initialization loop check flag.
SmartIF< IService > m_appSvc
Pointer to the application IService interface.
T empty(T... args)
boost::lock_guard< Mutex_t > LockGuard_t
T forward_as_tuple(T... args)
StatusCode finalize() override
Finalize (from INITIALIZED to CONFIGURED).
int getPriority(const std::string &name) const override
manage priorities of services
MsgStream & warning() const
shortcut for the method msgStream(MSG::WARNING)
MSG::Level resetMessaging()
Reinitialize internal states.
SmartIF< ISvcLocator > m_svcLocator
Service locator (needed to access the MessageSvc)
bool m_loopCheck
Check for service initialization loops.
::details::reverse_wrapper< T > reverse(T &&iterable)
Definition: reverse.h:59
bool existsService(const std::string &name) const override
implementation of ISvcLocation::existsService
ServiceManager(IInterface *application)
default creator
T endl(T... args)
constexpr static const auto SUCCESS
Definition: StatusCode.h:96
boost::recursive_mutex Mutex_t
Mutex to synchronize shared service initialization between threads.
StatusCode restart() override
Initialization (from RUNNING to RUNNING, via INITIALIZED).
T end(T... args)
bool isValidInterface(I *i)
Templated function that throws an exception if the version if the interface implemented by the object...
Definition: IInterface.h:351
MsgStream & info() const
shortcut for the method msgStream(MSG::INFO)
TYPE * get() const
Get interface pointer.
Definition: SmartIF.h:86
MapType m_maptype
Map of service name and service type.
T prev(T... args)
STL class.
virtual StatusCode sysInitialize()=0
Initialize Service.
T push_back(T... args)
MsgStream & error() const
shortcut for the method msgStream(MSG::ERROR)
StatusCode stop() override
Stop (from RUNNING to INITIALIZED).
iterator end()
Definition: Map.h:140
Helper class to parse a string of format "type/name".
bool loopCheckEnabled() const override
Get the value of the initialization loop check flag.
General service interface definition.
Definition: IService.h:28
This class is used for returning status codes from appropriate routines.
Definition: StatusCode.h:61
Definition of the basic interface.
Definition: IInterface.h:254
const std::list< IService * > & getServices() const override
Return the list of Services.
~ServiceManager() override
virtual destructor
#define DECLARE_OBJECT_FACTORY(x)
Definition: ObjectFactory.h:25
T erase(T... args)
iterator find(const key_type &key)
Definition: Map.h:157
const std::string & name() const override
Return the name of the manager (implementation of INamedInterface)
void dump() const
StatusCode start() override
Start (from INITIALIZED to RUNNING).
T clear(T... args)
bool isSuccess() const
Definition: StatusCode.h:361
T find(T... args)
T size(T... args)
const StatusCode & ignore() const
Ignore/check StatusCode.
Definition: StatusCode.h:164
void outputLevelUpdate() override
Function to call to update the outputLevel of the components (after a change in MessageSvc).
STL class.
virtual StatusCode sysStart()=0
Start Service.
T begin(T... args)
T back_inserter(T... args)
StatusCode reinitialize() override
Initialization (from INITIALIZED or RUNNING to INITIALIZED, via CONFIGURED).
Base class for all Incidents (computing events).
Definition: Incident.h:27
T emplace(T... args)
T back(T... args)
constexpr static const auto FAILURE
Definition: StatusCode.h:97
ListSvc::iterator find(const std::string &name)
StatusCode declareSvcType(const std::string &svcname, const std::string &svctype) override
implementation of ISvcManager::declareSvcType
T sort(T... args)
T transform(T... args)
#define DEBMSG
bool isFailure() const
Definition: StatusCode.h:141
StatusCode setPriority(const std::string &name, int pri) override
StatusCode removeService(IService *svc) override
implementation of ISvcManager::removeService
SmartIF< IService > & service(const Gaudi::Utils::TypeNameString &typeName, const bool createIf=true) override
Returns a smart pointer to a service.
std::string typeName(const std::type_info &typ)
Definition: Dictionary.cpp:31
ListSvc m_listsvc
List of service maintained by ServiceManager This contains SmartIF<T> for all services – and because ...
virtual void setServiceManager(ISvcManager *)=0
SmartIF< IService > & createService(const Gaudi::Utils::TypeNameString &nametype) override
implementation of ISvcManager::createService NOTE: as this returns a &, we must guarantee that once c...
MsgStream & fatal() const
shortcut for the method msgStream(MSG::FATAL)
SmartIF< IService > service
std::pair< iterator, bool > emplace(Args &&... args)
Definition: Map.h:174
MsgStream & endmsg(MsgStream &s)
MsgStream Modifier: endmsg. Calls the output method of the MsgStream.
Definition: MsgStream.h:202
std::map< std::string, Mutex_t > m_lockMap
T reserve(T... args)
StatusCode addService(IService *svc, int prio=DEFAULT_SVC_PRIORITY) override
implementation of ISvcManager::addService
T emplace_back(T... args)
StatusCode initialize() override
Initialization (from CONFIGURED to INITIALIZED).