The Gaudi Framework  v32r2 (46d42edc)
PluginServiceV2.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_V2
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 #ifdef _GNU_SOURCE
30 # include <cstring>
31 # include <dlfcn.h>
32 #endif
33 
34 #ifdef USE_BOOST_FILESYSTEM
35 # include <boost/filesystem.hpp>
36 namespace fs = boost::filesystem;
37 #else
38 # include <filesystem>
39 namespace fs = std::filesystem;
40 #endif // USE_BOOST_FILESYSTEM
41 
42 #if __cplusplus >= 201703
43 # include <string_view>
44 #else
45 # include <experimental/string_view>
46 namespace std {
47  using experimental::string_view;
48 }
49 #endif
50 
51 #define REG_SCOPE_LOCK std::lock_guard<std::recursive_mutex> _guard( m_mutex );
52 
53 namespace {
54  std::mutex registrySingletonMutex;
55 }
56 #define SINGLETON_LOCK std::lock_guard<std::mutex> _guard( ::registrySingletonMutex );
57 
58 #include <algorithm>
59 
60 namespace {
61  struct OldStyleCnv {
63  void operator()( const char c ) {
64  switch ( c ) {
65  case '<':
66  case '>':
67  case ',':
68  case '(':
69  case ')':
70  case ':':
71  case '.':
72  name.push_back( '_' );
73  break;
74  case '&':
75  name.push_back( 'r' );
76  break;
77  case '*':
78  name.push_back( 'p' );
79  break;
80  case ' ':
81  break;
82  default:
83  name.push_back( c );
84  break;
85  }
86  }
87  };
89  std::string old_style_name( const std::string& name ) {
90  return std::for_each( name.begin(), name.end(), OldStyleCnv() ).name;
91  }
92 } // namespace
93 
94 namespace Gaudi {
95  namespace PluginService {
96  GAUDI_PLUGIN_SERVICE_V2_INLINE namespace v2 {
97  namespace Details {
99  int status;
101  abi::__cxa_demangle( id.c_str(), nullptr, nullptr, &status ), free );
102  if ( !realname ) return id;
103 #if _GLIBCXX_USE_CXX11_ABI
104  return std::regex_replace(
105  realname.get(),
106  std::regex{"std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >( (?=>))?"},
107  "std::string" );
108 #else
109  return std::string{realname.get()};
110 #endif
111  }
112  std::string demangle( const std::type_info& id ) { return demangle( id.name() ); }
113 
114  Registry& Registry::instance() {
116  static Registry r;
117  return r;
118  }
119 
120  void reportBadAnyCast( const std::type_info& factory_type, const std::string& id ) {
121  if ( logger().level() <= Logger::Debug ) {
123  const auto& info = Registry::instance().getInfo( id );
124  msg << "bad any_cast: requested factory " << id << " of type " << demangle( factory_type ) << ", got ";
125  if ( info.is_set() )
126  msg << demangle( info.factory.type() ) << " from " << info.library;
127  else
128  msg << "nothing";
129  logger().debug( msg.str() );
130  }
131  }
132 
133  Registry::Properties::mapped_type Registry::FactoryInfo::getprop( const Properties::key_type& name ) const {
134  auto p = properties.find( name );
135  return ( p != end( properties ) ) ? p->second : Properties::mapped_type{};
136  }
137 
138  Registry::Registry() {}
139 
140  void Registry::initialize() {
142 #if defined( _WIN32 )
143  const char* envVar = "PATH";
144  const char sep = ';';
145 #else
146  const char* envVar = "LD_LIBRARY_PATH";
147  const char sep = ':';
148 #endif
149 
150  std::regex line_format{"^(?:[[:space:]]*(?:(v[0-9]+)::)?([^:]+):(.*[^[:space:]]))?[[:space:]]*(?:#.*)?$"};
151  std::smatch m;
152 
153  std::string_view search_path = std::getenv( envVar );
154  if ( !search_path.empty() ) {
155  logger().debug( std::string( "searching factories in " ) + envVar );
156 
157  std::string_view::size_type start_pos = 0, end_pos = 0;
158  while ( start_pos != std::string_view::npos ) {
159  // correctly handle begin of string or path separator
160  if ( start_pos ) ++start_pos;
161 
162  end_pos = search_path.find( sep, start_pos );
163  fs::path dirName =
164 #ifdef USE_BOOST_FILESYSTEM
165  std::string{search_path.substr( start_pos, end_pos - start_pos )};
166 #else
167  search_path.substr( start_pos, end_pos - start_pos );
168 #endif
169  start_pos = end_pos;
170 
171  logger().debug( " looking into " + dirName.string() );
172  // look for files called "*.components" in the directory
173  if ( is_directory( dirName ) ) {
174  for ( auto& p : fs::directory_iterator( dirName ) ) {
175  if ( p.path().extension() == ".components" && is_regular_file( p.path() ) ) {
176  // read the file
177  const auto& fullPath = p.path().string();
178  logger().debug( " reading " + p.path().filename().string() );
179  std::ifstream factories{fullPath};
181  int factoriesCount = 0;
182  int lineCount = 0;
183  while ( !factories.eof() ) {
184  ++lineCount;
186  if ( regex_match( line, m, line_format ) ) {
187  if ( m[1] == "v2" ) { // ignore non "v2" and "empty" lines
188  const std::string lib{m[2]};
189  const std::string fact{m[3]};
190  m_factories.emplace( fact, FactoryInfo{lib, {}, {{"ClassName", fact}}} );
191 #ifdef GAUDI_REFLEX_COMPONENT_ALIASES
192  // add an alias for the factory using the Reflex convention
193  std::string old_name = old_style_name( fact );
194  if ( fact != old_name ) {
195  m_factories.emplace( old_name,
196  FactoryInfo{lib, {}, {{"ReflexName", "true"}, {"ClassName", fact}}} );
197  }
198 #endif
199  ++factoriesCount;
200  }
201  } else {
202  logger().warning( "failed to parse line " + fullPath + ':' + std::to_string( lineCount ) );
203  }
204  }
205  if ( logger().level() <= Logger::Debug ) {
206  logger().debug( " found " + std::to_string( factoriesCount ) + " factories" );
207  }
208  }
209  }
210  }
211  }
212  }
213  }
214 
215  const Registry::FactoryMap& Registry::factories() const {
216  std::call_once( m_initialized, &Registry::initialize, const_cast<Registry*>( this ) );
217  return m_factories;
218  }
219 
220  Registry::FactoryMap& Registry::factories() {
221  std::call_once( m_initialized, &Registry::initialize, this );
222  return m_factories;
223  }
224 
225  Registry::FactoryInfo& Registry::add( const KeyType& id, FactoryInfo info ) {
227  FactoryMap& facts = factories();
228 
229 #ifdef GAUDI_REFLEX_COMPONENT_ALIASES
230  // add an alias for the factory using the Reflex convention
231  const auto old_name = old_style_name( id );
232  if ( id != old_name ) {
233  auto new_info = info;
234 
235  new_info.properties["ReflexName"] = "true";
236 
237  add( old_name, new_info );
238  }
239 #endif
240 
241  auto entry = facts.find( id );
242  if ( entry == facts.end() ) {
243  // this factory was not known yet
244  entry = facts.emplace( id, std::move( info ) ).first;
245  } else {
246  // do not replace an existing factory with a new one
247  if ( !entry->second.is_set() ) entry->second = std::move( info );
248  }
249  return entry->second;
250  }
251 
252  const Registry::FactoryInfo& Registry::getInfo( const KeyType& id, const bool load ) const {
254  static const FactoryInfo unknown = {"unknown"};
255  const FactoryMap& facts = factories();
256  auto f = facts.find( id );
257 
258  if ( f != facts.end() ) {
259  if ( load && !f->second.is_set() ) {
260  const std::string library = f->second.library;
261  if ( !dlopen( library.c_str(), RTLD_LAZY | RTLD_GLOBAL ) ) {
262  logger().warning( "cannot load " + library + " for factory " + id );
263  char* dlmsg = dlerror();
264  if ( dlmsg ) logger().warning( dlmsg );
265  return unknown;
266  }
267  f = facts.find( id ); // ensure that the iterator is valid
268  }
269  return f->second;
270  } else {
271  return unknown;
272  }
273  }
274 
275  Registry& Registry::addProperty( const KeyType& id, const KeyType& k, const std::string& v ) {
277  FactoryMap& facts = factories();
278  auto f = facts.find( id );
279 
280  if ( f != facts.end() ) f->second.properties[k] = v;
281  return *this;
282  }
283 
284  std::set<Registry::KeyType> Registry::loadedFactoryNames() const {
287  for ( const auto& f : factories() ) {
288  if ( f.second.is_set() ) l.insert( f.first );
289  }
290  return l;
291  }
292 
293  void Logger::report( Level lvl, const std::string& msg ) {
294  static const char* levels[] = {"DEBUG : ", "INFO : ", "WARNING: ", "ERROR : "};
295  if ( lvl >= level() ) { std::cerr << levels[lvl] << msg << std::endl; }
296  }
297 
298  static auto s_logger = std::make_unique<Logger>();
299  Logger& logger() { return *s_logger; }
300  void setLogger( Logger* logger ) { s_logger.reset( logger ); }
301 
302  // This chunk of code was taken from GaudiKernel (genconf) DsoUtils.h
303  std::string getDSONameFor( void* fptr ) {
304 #ifdef _GNU_SOURCE
305  Dl_info info;
306  if ( dladdr( fptr, &info ) == 0 ) return "";
307 
308  auto pos = std::strrchr( info.dli_fname, '/' );
309  if ( pos )
310  ++pos;
311  else
312  return info.dli_fname;
313  return pos;
314 #else
315  return "";
316 #endif
317  }
318  } // namespace Details
319 
320  void SetDebug( int debugLevel ) {
321  using namespace Details;
322  Logger& l = logger();
323  if ( debugLevel > 1 )
324  l.setLevel( Logger::Debug );
325  else if ( debugLevel > 0 )
326  l.setLevel( Logger::Info );
327  else
328  l.setLevel( Logger::Warning );
329  }
330 
331  int Debug() {
332  using namespace Details;
333  switch ( logger().level() ) {
334  case Logger::Debug:
335  return 2;
336  case Logger::Info:
337  return 1;
338  default:
339  return 0;
340  }
341  }
342  }
343  } // namespace PluginService
344 } // namespace Gaudi
T regex_match(T... args)
#define GAUDI_PLUGIN_SERVICE_V2_INLINE
T getline(T... args)
T to_string(T... args)
T endl(T... args)
STL namespace.
void SetDebug(int debugLevel)
T call_once(T... args)
std::string getDSONameFor(void *fptr)
void reportBadAnyCast(const std::type_info &factory_type, const std::string &id)
STL class.
T getenv(T... args)
T regex_replace(T... args)
constexpr double m
Definition: SystemOfUnits.h:92
#define REG_SCOPE_LOCK
def end
Definition: IOTest.py:113
T strrchr(T... args)
T move(T... args)
dictionary l
Definition: gaudirun.py:523
STL class.
STL class.
T c_str(T... args)
T substr(T... args)
std::string demangle(const std::string &id)
#define SINGLETON_LOCK
T for_each(T... args)
Header file for std:chrono::duration-based Counters.
Definition: __init__.py:1
STL class.