The Gaudi Framework  v30r0 (c919700c)
PluginService.cpp
Go to the documentation of this file.
1 /*****************************************************************************\
2 * (c) Copyright 2013 CERN *
3 * *
4 * This software is distributed under the terms of the GNU General Public *
5 * Licence version 3 (GPL Version 3), copied verbatim in the file "LICENCE". *
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 
13 
14 #include <Gaudi/PluginService.h>
15 
16 #include <dirent.h>
17 #include <dlfcn.h>
18 
19 #include <cstdlib>
20 #include <fstream>
21 #include <iostream>
22 #include <memory>
23 #include <regex>
24 
25 #include <cxxabi.h>
26 #include <sys/stat.h>
27 
28 #define REG_SCOPE_LOCK std::lock_guard<std::recursive_mutex> _guard( m_mutex );
29 
30 namespace
31 {
32  std::mutex registrySingletonMutex;
33 }
34 #define SINGLETON_LOCK std::lock_guard<std::mutex> _guard(::registrySingletonMutex );
35 
36 #include <algorithm>
37 
38 namespace
39 {
40  // string trimming functions taken from
41  // http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring
42 
43  constexpr struct is_space_t {
44  bool operator()( int i ) const { return std::isspace( i ); }
45  } is_space{};
46 
47  // trim from start
48  static inline std::string& ltrim( std::string& s )
49  {
50  s.erase( s.begin(), std::find_if_not( s.begin(), s.end(), is_space ) );
51  return s;
52  }
53 
54  // trim from end
55  static inline std::string& rtrim( std::string& s )
56  {
57  s.erase( std::find_if_not( s.rbegin(), s.rend(), is_space ).base(), s.end() );
58  return s;
59  }
60  // trim from both ends
61  static inline std::string& trim( std::string& s ) { return ltrim( rtrim( s ) ); }
62 }
63 
64 namespace
65 {
69  inline void factoryInfoSetHelper( std::string& dest, const std::string value, const std::string& desc,
70  const std::string& id )
71  {
72  if ( dest.empty() ) {
73  dest = value;
74  } else if ( dest != value ) {
75  Gaudi::PluginService::Details::logger().warning( "new factory loaded for '" + id + "' with different " + desc +
76  ": " + dest + " != " + value );
77  }
78  }
79 
80  struct OldStyleCnv {
82  void operator()( const char c )
83  {
84  switch ( c ) {
85  case '<':
86  case '>':
87  case ',':
88  case '(':
89  case ')':
90  case ':':
91  case '.':
92  name.push_back( '_' );
93  break;
94  case '&':
95  name.push_back( 'r' );
96  break;
97  case '*':
98  name.push_back( 'p' );
99  break;
100  case ' ':
101  break;
102  default:
103  name.push_back( c );
104  break;
105  }
106  }
107  };
109  std::string old_style_name( const std::string& name )
110  {
111  return std::for_each( name.begin(), name.end(), OldStyleCnv() ).name;
112  }
113 }
114 
115 namespace Gaudi
116 {
117  namespace PluginService
118  {
119 
120  Exception::Exception( std::string msg ) : m_msg( std::move( msg ) ) {}
122  const char* Exception::what() const throw() { return m_msg.c_str(); }
123 
124  namespace Details
125  {
126  void* getCreator( const std::string& id, const std::string& type )
127  {
128  return Registry::instance().get( id, type );
129  }
130 
132  {
133  int status;
135  abi::__cxa_demangle( id.c_str(), nullptr, nullptr, &status ), free );
136  if ( !realname ) return id;
137 #if _GLIBCXX_USE_CXX11_ABI
138  return std::regex_replace(
139  realname.get(),
140  std::regex{"std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >( (?=>))?"},
141  "std::string" );
142 #else
143  return std::string{realname.get()};
144 #endif
145  }
146  std::string demangle( const std::type_info& id ) { return demangle( id.name() ); }
147 
148  Registry& Registry::instance()
149  {
151  static Registry r;
152  return r;
153  }
154 
155  Registry::Registry() : m_initialized( false ) {}
156 
158  {
160  if ( m_initialized ) return;
161  m_initialized = true;
162 #if defined( _WIN32 )
163  const char* envVar = "PATH";
164  const char sep = ';';
165 #elif defined( __APPLE__ )
166  const char* envVar = "DYLD_LIBRARY_PATH";
167  const char sep = ':';
168 #else
169  const char* envVar = "LD_LIBRARY_PATH";
170  const char sep = ':';
171 #endif
172  char* search_path = ::getenv( envVar );
173  if ( search_path ) {
174  logger().debug( std::string( "searching factories in " ) + envVar );
175  std::string path( search_path );
176  std::string::size_type pos = 0;
177  std::string::size_type newpos = 0;
178  while ( pos != std::string::npos ) {
179  std::string dirName;
180  // get the next entry in the path
181  newpos = path.find( sep, pos );
182  if ( newpos != std::string::npos ) {
183  dirName = path.substr( pos, newpos - pos );
184  pos = newpos + 1;
185  } else {
186  dirName = path.substr( pos );
187  pos = newpos;
188  }
189  logger().debug( std::string( " looking into " ) + dirName );
190  // look for files called "*.components" in the directory
191  DIR* dir = opendir( dirName.c_str() );
192  if ( dir ) {
193  struct dirent* entry;
194  while ( ( entry = readdir( dir ) ) ) {
195  std::string name( entry->d_name );
196  // check if the file name ends with ".components"
197  std::string::size_type extpos = name.find( ".components" );
198  if ( ( extpos != std::string::npos ) && ( ( extpos + 11 ) == name.size() ) ) {
199  std::string fullPath = ( dirName + '/' + name );
200  { // check if it is a regular file
201  struct stat buf;
202  stat( fullPath.c_str(), &buf );
203  if ( !S_ISREG( buf.st_mode ) ) continue;
204  }
205  // read the file
206  logger().debug( std::string( " reading " ) + name );
207  std::ifstream factories{fullPath};
209  int factoriesCount = 0;
210  int lineCount = 0;
211  while ( !factories.eof() ) {
212  ++lineCount;
213  std::getline( factories, line );
214  trim( line );
215  // skip empty lines and lines starting with '#'
216  if ( line.empty() || line[0] == '#' ) continue;
217  // look for the separator
218  auto pos = line.find( ':' );
219  if ( pos == std::string::npos ) {
220  logger().warning( "failed to parse line " + fullPath + ':' + std::to_string( lineCount ) );
221  continue;
222  }
223  const std::string lib( line, 0, pos );
224  const std::string fact( line, pos + 1 );
225  m_factories.emplace( fact, FactoryInfo( lib ) );
226 #ifdef GAUDI_REFLEX_COMPONENT_ALIASES
227  // add an alias for the factory using the Reflex convention
228  std::string old_name = old_style_name( fact );
229  if ( fact != old_name ) {
230  FactoryInfo old_info( lib );
231  old_info.properties["ReflexName"] = "true";
232  m_factories.emplace( old_name, old_info );
233  }
234 #endif
235  ++factoriesCount;
236  }
237  if ( logger().level() <= Logger::Debug ) {
238  logger().debug( " found " + std::to_string( factoriesCount ) + " factories" );
239  }
240  }
241  }
242  closedir( dir );
243  }
244  }
245  }
246  }
247 
248  Registry::FactoryInfo& Registry::add( const std::string& id, void* factory, const std::string& type,
249  const std::string& rtype, const std::string& className,
250  const Properties& props )
251  {
253  FactoryMap& facts = factories();
254  auto entry = facts.find( id );
255  if ( entry == facts.end() ) {
256  // this factory was not known yet
257  entry = facts.emplace( id, FactoryInfo( "unknown", factory, type, rtype, className, props ) ).first;
258  } else {
259  // do not replace an existing factory with a new one
260  if ( !entry->second.ptr ) entry->second.ptr = factory;
261  factoryInfoSetHelper( entry->second.type, type, "type", id );
262  factoryInfoSetHelper( entry->second.rtype, rtype, "return type", id );
263  factoryInfoSetHelper( entry->second.className, className, "class", id );
264  }
265 #ifdef GAUDI_REFLEX_COMPONENT_ALIASES
266  // add an alias for the factory using the Reflex convention
267  std::string old_name = old_style_name( id );
268  if ( id != old_name ) add( old_name, factory, type, rtype, className, props ).properties["ReflexName"] = "true";
269 #endif
270  return entry->second;
271  }
272 
273  void* Registry::get( const std::string& id, const std::string& type ) const
274  {
276  const FactoryMap& facts = factories();
277  auto f = facts.find( id );
278  if ( f != facts.end() ) {
279 #ifdef GAUDI_REFLEX_COMPONENT_ALIASES
280  const Properties& props = f->second.properties;
281  if ( props.find( "ReflexName" ) != props.end() )
282  logger().warning( "requesting factory via old name '" + id + "'"
283  "use '" +
284  f->second.className + "' instead" );
285 #endif
286  if ( !f->second.ptr ) {
287  if ( !dlopen( f->second.library.c_str(), RTLD_LAZY | RTLD_GLOBAL ) ) {
288  logger().warning( "cannot load " + f->second.library + " for factory " + id );
289  char* dlmsg = dlerror();
290  if ( dlmsg ) logger().warning( dlmsg );
291  return nullptr;
292  }
293  f = facts.find( id ); // ensure that the iterator is valid
294  }
295  if ( f->second.type == type ) return f->second.ptr;
296  logger().warning( "found factory " + id + ", but of wrong type: " + demangle( f->second.type ) +
297  " instead of " + demangle( type ) );
298  }
299  return nullptr; // factory not found
300  }
301 
303  {
305  static const FactoryInfo unknown( "unknown" );
306  const FactoryMap& facts = factories();
307  auto f = facts.find( id );
308  return ( f != facts.end() ) ? f->second : unknown;
309  }
310 
312  {
314  FactoryMap& facts = factories();
315  auto f = facts.find( id );
316  if ( f != facts.end() ) f->second.properties[k] = v;
317  return *this;
318  }
319 
321  {
324  for ( const auto& f : factories() ) {
325  if ( f.second.ptr ) l.insert( f.first );
326  }
327  return l;
328  }
329 
330  void Logger::report( Level lvl, const std::string& msg )
331  {
332  static const char* levels[] = {"DEBUG : ", "INFO : ", "WARNING: ", "ERROR : "};
333  if ( lvl >= level() ) {
334  std::cerr << levels[lvl] << msg << std::endl;
335  }
336  }
337 
338  static std::unique_ptr<Logger> s_logger( new Logger );
339  Logger& logger() { return *s_logger; }
340  void setLogger( Logger* logger ) { s_logger.reset( logger ); }
341 
342  } // namespace Details
343 
344  void SetDebug( int debugLevel )
345  {
346  using namespace Details;
347  Logger& l = logger();
348  if ( debugLevel > 1 )
349  l.setLevel( Logger::Debug );
350  else if ( debugLevel > 0 )
351  l.setLevel( Logger::Info );
352  else
353  l.setLevel( Logger::Warning );
354  }
355 
356  int Debug()
357  {
358  using namespace Details;
359  switch ( logger().level() ) {
360  case Logger::Debug:
361  return 2;
362  case Logger::Info:
363  return 1;
364  default:
365  return 0;
366  }
367  }
368  }
369 } // namespace Gaudi::PluginService
T empty(T...args)
const FactoryInfo & getInfo(const std::string &id) const
Retrieve the FactoryInfo object for an id.
T rend(T...args)
Registry & addProperty(const std::string &id, const std::string &k, const std::string &v)
Add a property to an already existing FactoryInfo object (via its id.)
#define REG_SCOPE_LOCK
T getline(T...args)
T to_string(T...args)
T endl(T...args)
STL namespace.
void initialize()
Initialize the registry loading the list of factories from the .component files in the library search...
T end(T...args)
#define SINGLETON_LOCK
GAUDIPS_API Logger & logger()
Return the current logger instance.
Simple logging class, just to provide a default implementation.
STL class.
T push_back(T...args)
GAUDIPS_API void SetDebug(int debugLevel)
Backward compatibility with Reflex.
void * get(const std::string &id, const std::string &type) const
Retrieve the factory for the given id.
T regex_replace(T...args)
std::string demangle(const std::string &id)
GAUDIPS_API std::string demangle(const std::type_info &id)
Return a canonical name for type_info object (implementation borrowed from GaudiKernel/System).
T erase(T...args)
const FactoryMap & factories() const
Return the known factories (loading the list if not yet done).
T reset(T...args)
virtual void report(Level lvl, const std::string &msg)
void warning(const std::string &msg)
dictionary l
Definition: gaudirun.py:440
T find_if_not(T...args)
T size(T...args)
STL class.
GAUDIPS_API void * getCreator(const std::string &id, const std::string &type)
Function used to load a specific factory function.
STL class.
virtual Out operator()(const vector_of_const_< In > &inputs) const =0
T begin(T...args)
T c_str(T...args)
T emplace(T...args)
string s
Definition: gaudirun.py:253
In-memory database of the loaded factories.
T substr(T...args)
FactoryInfo & add(const I &id, typename F::FuncType ptr)
Add a factory to the database.
GAUDIPS_API int Debug()
Backward compatibility with Reflex.
std::set< KeyType > loadedFactoryNames() const
Return a list of all the known and loaded factories.
GAUDIPS_API void setLogger(Logger *logger)
Set the logger instance to use.
const char * what() const override
T for_each(T...args)
T isspace(T...args)
FactoryMap m_factories
Internal storage for factories.
Helper functions to set/get the application return code.
Definition: __init__.py:1
STL class.
bool m_initialized
Flag recording if the registry has been initialized or not.
T rbegin(T...args)