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