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