| The Gaudi Framework v30r0 (c919700c)

- Main Page
- Related Pages
- Modules
- Namespaces
- Classes
- Files

- File List
- File Members

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 {
81 std::string name;
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 ) ) {}
121 Exception::~Exception() throw() {}
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
131 std::string demangle( const std::string& id )
132 {
133 int status;
134 auto realname = std::unique_ptr<char, decltype( free )*>(
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 {
150 SINGLETON_LOCK
151 static Registry r;
152 return r;
153 }
154
155 Registry::Registry() : m_initialized( false ) {}
156
157 void Registry::initialize()
158 {
159 REG_SCOPE_LOCK
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};
208 std::string line;
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 {
252 REG_SCOPE_LOCK
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 {
275 REG_SCOPE_LOCK
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
302 const Registry::FactoryInfo& Registry::getInfo( const std::string& id ) const
303 {
304 REG_SCOPE_LOCK
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
311 Registry& Registry::addProperty( const std::string& id, const std::string& k, const std::string& v )
312 {
313 REG_SCOPE_LOCK
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
320 std::set<Registry::KeyType> Registry::loadedFactoryNames() const
321 {
322 REG_SCOPE_LOCK
323 std::set<KeyType> l;
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
Gaudi::PluginService::Details::Logger::Info
Definition: PluginServiceDetails.h:223
std::string::empty
T empty(T...args)
gaudirun.c
c
Definition: gaudirun.py:407
GaudiPython.HistoUtils.path
path
Definition: HistoUtils.py:895
gaudiComponentHelp.name
name
Definition: gaudiComponentHelp.py:32
Gaudi::PluginService::Details::Registry::getInfo
const FactoryInfo & getInfo(const std::string &id) const
Retrieve the FactoryInfo object for an id.
Definition: PluginService.cpp:302
Gaudi::PluginService::Exception::m_msg
std::string m_msg
Definition: PluginService.h:75
std::string::rend
T rend(T...args)
Gaudi::PluginService::Details::Registry::addProperty
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.)
Definition: PluginService.cpp:311
REG_SCOPE_LOCK
#define REG_SCOPE_LOCK
Definition: PluginService.cpp:28
std::getline
T getline(T...args)
std::to_string
T to_string(T...args)
std::endl
T endl(T...args)
std
STL namespace.
Gaudi::PluginService::Details::Registry::initialize
void initialize()
Initialize the registry loading the list of factories from the .component files in the library search...
Definition: PluginService.cpp:157
std::string::end
T end(T...args)
SINGLETON_LOCK
#define SINGLETON_LOCK
Definition: PluginService.cpp:34
Gaudi::PluginService::Details::Registry::FactoryInfo
Definition: PluginServiceDetails.h:118
std::map< KeyType, std::string >
Gaudi::PluginService::Details::Registry::FactoryInfo::properties
Properties properties
Definition: PluginServiceDetails.h:135
std::mutex
Gaudi::PluginService::Details::logger
GAUDIPS_API Logger & logger()
Return the current logger instance.
Definition: PluginService.cpp:339
Gaudi::PluginService::Details::Logger
Simple logging class, just to provide a default implementation.
Definition: PluginServiceDetails.h:220
std::type_info
std::string
STL class.
std::string::push_back
T push_back(T...args)
Gaudi::PluginService::SetDebug
GAUDIPS_API void SetDebug(int debugLevel)
Backward compatibility with Reflex.
Definition: PluginService.cpp:344
Gaudi::PluginService::Details::Registry::get
void * get(const std::string &id, const std::string &type) const
Retrieve the factory for the given id.
Definition: PluginService.cpp:273
std::regex_replace
T regex_replace(T...args)
gaudirun.dest
dest
Definition: gaudirun.py:170
Gaudi::PluginService::Details::demangle
std::string demangle(const std::string &id)
Definition: PluginService.cpp:131
gaudirun.type
type
Definition: gaudirun.py:133
Gaudi::PluginService::Details::demangle
GAUDIPS_API std::string demangle(const std::type_info &id)
Return a canonical name for type_info object (implementation borrowed from GaudiKernel/System).
Definition: PluginService.cpp:146
Gaudi::PluginService::Details::Logger::Level
Level
Definition: PluginServiceDetails.h:223
std::string::erase
T erase(T...args)
Gaudi::PluginService::Details::Registry::factories
const FactoryMap & factories() const
Return the known factories (loading the list if not yet done).
Definition: PluginServiceDetails.h:178
std::unique_ptr::reset
T reset(T...args)
Gaudi::PluginService::Details::Logger::report
virtual void report(Level lvl, const std::string &msg)
Definition: PluginService.cpp:330
Gaudi::PluginService::Details::Logger::warning
void warning(const std::string &msg)
Definition: PluginServiceDetails.h:230
gaudirun.l
dictionary l
Definition: gaudirun.py:440
PluginService.h
std::find_if_not
T find_if_not(T...args)
std::string::size
T size(T...args)
std::set
STL class.
Gaudi::PluginService::Details::getCreator
GAUDIPS_API void * getCreator(const std::string &id, const std::string &type)
Function used to load a specific factory function.
Definition: PluginService.cpp:126
std::unique_ptr
STL class.
Gaudi::Functional::operator()
virtual Out operator()(const vector_of_const_< In > &inputs) const =0
Gaudi::PluginService::Details::Logger::Warning
Definition: PluginServiceDetails.h:223
std::regex
Gaudi::PluginService::Details::Logger::Debug
Definition: PluginServiceDetails.h:223
std::string::begin
T begin(T...args)
std::string::c_str
T c_str(T...args)
std::map::emplace
T emplace(T...args)
GaudiMP.FdsRegistry.msg
msg
Definition: FdsRegistry.py:8
gaudirun.s
string s
Definition: gaudirun.py:253
Gaudi::PluginService::Details::Registry
In-memory database of the loaded factories.
Definition: PluginServiceDetails.h:110
std::string::substr
T substr(T...args)
Gaudi::PluginService::Details::Registry::add
FactoryInfo & add(const I &id, typename F::FuncType ptr)
Add a factory to the database.
Definition: PluginServiceDetails.h:152
gaudirun.level
level
Definition: gaudirun.py:271
Gaudi::PluginService::Debug
GAUDIPS_API int Debug()
Backward compatibility with Reflex.
Definition: PluginService.cpp:356
Gaudi::PluginService::Details::Registry::loadedFactoryNames
std::set< KeyType > loadedFactoryNames() const
Return a list of all the known and loaded factories.
Definition: PluginService.cpp:320
Gaudi::PluginService::Details::setLogger
GAUDIPS_API void setLogger(Logger *logger)
Set the logger instance to use.
Definition: PluginService.cpp:340
Gaudi::PluginService::Exception::what
const char * what() const override
Definition: PluginService.cpp:122
std::for_each
T for_each(T...args)
std::cerr
std::isspace
T isspace(T...args)
Gaudi::PluginService::Details::Registry::m_factories
FactoryMap m_factories
Internal storage for factories.
Definition: PluginServiceDetails.h:213
Gaudi
Helper functions to set/get the application return code.
Definition: __init__.py:1
Gaudi::PluginService::Exception::~Exception
~Exception() override
Definition: PluginService.cpp:121
std::ifstream
STL class.
plotSpeedupsPyRoot.line
line
Definition: plotSpeedupsPyRoot.py:172
Gaudi::PluginService::Details::Registry::m_initialized
bool m_initialized
Flag recording if the registry has been initialized or not.
Definition: PluginServiceDetails.h:210
Gaudi::PluginService::Details::Logger::debug
void debug(const std::string &msg)
Definition: PluginServiceDetails.h:229
std::string::rbegin
T rbegin(T...args)