The Gaudi Framework  master (50869dff)
Loading...
Searching...
No Matches
genconf.cpp
Go to the documentation of this file.
1/***********************************************************************************\
2* (c) Copyright 1998-2026 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#ifdef __ICC
12// disable icc warning #279: controlling expression is constant
13// ... a lot of noise produced by the boost/filesystem/operations.hpp
14# pragma warning( disable : 279 )
15#endif
16
17#include <Gaudi/Algorithm.h>
18#include <Gaudi/Auditor.h>
19#include <Gaudi/IAuditor.h>
20#include <Gaudi/PluginService.h>
21#include <GaudiKernel/AlgTool.h>
26#include <GaudiKernel/HashMap.h>
32#include <GaudiKernel/Service.h>
33#include <GaudiKernel/SmartIF.h>
34#include <GaudiKernel/System.h>
35#include <GaudiKernel/Time.h>
36#include <algorithm>
37#include <boost/algorithm/string/case_conv.hpp>
38#include <boost/algorithm/string/classification.hpp>
39#include <boost/algorithm/string/replace.hpp>
40#include <boost/algorithm/string/split.hpp>
41#include <boost/algorithm/string/trim.hpp>
42#include <boost/filesystem/exception.hpp>
43#include <boost/filesystem/operations.hpp>
44#include <boost/log/core.hpp>
45#include <boost/log/expressions.hpp>
46#include <boost/log/trivial.hpp>
47#include <boost/log/utility/setup/common_attributes.hpp>
48#include <boost/log/utility/setup/console.hpp>
49#include <boost/program_options.hpp>
50#include <boost/regex.hpp>
51#include <boost/tokenizer.hpp>
52
53#include <exception>
54#include <fmt/format.h>
55#include <fstream>
56#include <iostream>
57#include <nlohmann/json.hpp>
58#include <set>
59#include <sstream>
60#include <type_traits>
61#include <vector>
62
63namespace po = boost::program_options;
64namespace fs = boost::filesystem;
65
66#define LOG_ERROR BOOST_LOG_TRIVIAL( error )
67#define LOG_WARNING BOOST_LOG_TRIVIAL( warning )
68#define LOG_INFO BOOST_LOG_TRIVIAL( info )
69
70using namespace std;
72
73class IConverter;
74
75// useful typedefs
76typedef std::vector<std::string> Strings_t;
77typedef std::vector<fs::path> LibPathNames_t;
78
79namespace {
80
81 std::string quote( std::string_view sv ) {
82 std::ostringstream s;
83 s << std::quoted( sv, '\'' );
84 return s.str();
85 }
86
87 const std::string py_tab = " ";
88
91 const boost::regex pythonIdentifier( "^[a-zA-Z_][a-zA-Z0-9_]*$" );
92
93 //-----------------------------------------------------------------------------
94 enum class component_t {
95 Module,
96 DefaultName,
98 AlgTool,
99 Auditor,
100 Service,
103 Converter,
105 Unknown
106 };
107
108 enum class conf_t {
109 CONF, // legacy configurables
110 CONF2 // GaudiConfig2 configurables
111 };
112
113 const std::map<std::string, component_t> allowedFactories{
114 { typeid( Gaudi::Algorithm::Factory::FactoryType ).name(), component_t::Algorithm },
115 { typeid( Service::Factory::FactoryType ).name(), component_t::Service },
116 { typeid( AlgTool::Factory::FactoryType ).name(), component_t::AlgTool },
117 // factories for new Auditors
118 { typeid( Gaudi::Auditor::Factory::FactoryType ).name(), component_t::Auditor },
119 };
120
121 const std::string& toString( component_t type ) {
122 static const std::array<std::string, 11> names = { "Module", "DefaultName", "Algorithm", "AlgTool",
123 "Auditor", "Service", "ApplicationMgr", "IInterface",
124 "Converter", "DataObject", "Unknown" };
125 return names.at( static_cast<std::underlying_type_t<component_t>>( type ) );
126 }
127 std::ostream& operator<<( std::ostream& os, component_t type ) { return os << toString( type ); }
128
129 std::set<std::string> ignored_interfaces{
130 { "IInterface", "IProperty", "INamedInterface", "IAlgorithm", "IAlgTool", "IService", "IAuditor" } };
131
132 //-----------------------------------------------------------------------------
134 std::string pythonizeName( const std::string& name ) {
135 static const string in( "<>&*,: ()." );
136 static const string out( "__rp__s___" );
137 auto r = boost::algorithm::replace_all_copy( name, ", ", "," );
138 for ( auto& c : r ) {
139 auto rep = in.find( c );
140 if ( rep != string::npos ) c = out[rep];
141 }
142 return r;
143 }
144 //-----------------------------------------------------------------------------
145 template <typename T>
146 std::type_index typeIndex() {
147 return std::type_index{ typeid( T ) };
148 }
149 //-----------------------------------------------------------------------------
150 inline std::string libNativeName( const std::string& libName ) {
151#if defined( __linux ) || defined( __APPLE__ )
152 return "lib" + libName + ".so";
153#else
154 // variant of the GIGO design pattern
155 return libName;
156#endif
157 }
158} // namespace
159
162 string m_pkgName;
163
167
169 stringstream m_pyBuf;
170
175
177 std::set<conf_t> m_confTypes;
178
183 stringstream m_dbBuf;
184
186 stringstream m_db2Buf;
187
193 std::map<component_t, std::string> m_configurable;
194
195public:
196 configGenerator( const string& pkgName, const string& outputDirName )
197 : m_pkgName( pkgName ), m_outputDirName( outputDirName ) {}
198
203 int genConfig( const Strings_t& modules, const string& userModule );
204
206 void setConfigurableTypes( const std::set<conf_t>& types ) { m_confTypes = types; }
207
209 void setConfigurableModule( const std::string& moduleName ) { m_configurable[component_t::Module] = moduleName; }
210
212 void setConfigurableDefaultName( const std::string& defaultName ) {
213 m_configurable[component_t::DefaultName] = defaultName;
214 }
215
217 void setConfigurableAlgorithm( const std::string& cfgAlgorithm ) {
218 m_configurable[component_t::Algorithm] = cfgAlgorithm;
219 }
220
222 void setConfigurableAlgTool( const std::string& cfgAlgTool ) { m_configurable[component_t::AlgTool] = cfgAlgTool; }
223
225 void setConfigurableAuditor( const std::string& cfgAuditor ) { m_configurable[component_t::Auditor] = cfgAuditor; }
226
228 void setConfigurableService( const std::string& cfgService ) {
229 m_configurable[component_t::Service] = cfgService;
230 m_configurable[component_t::ApplicationMgr] = cfgService;
231 }
232
233private:
234 bool genComponent( const std::string& libName, const std::string& componentName, component_t componentType,
235 const vector<PropertyBase*>& properties,
236 const Gaudi::PluginService::Details::Registry::FactoryInfo& info );
237
238 bool genComponent2( const std::string& componentName, component_t componentType,
239 const vector<PropertyBase*>& properties, const std::vector<std::string>& interfaces,
240 const Gaudi::PluginService::Details::Registry::FactoryInfo& info );
241
242 void genImport( std::ostream& s, std::string_view frmt, std::string indent );
243 void genHeader( std::ostream& pyOut, std::ostream& dbOut );
244 void genBody( std::ostream& pyOut, std::ostream& dbOut ) {
245 pyOut << m_pyBuf.str() << flush;
246 dbOut << m_dbBuf.str() << flush;
247 }
248 void genTrailer( std::ostream& pyOut, std::ostream& dbOut );
249
251 void pythonizeValue( const PropertyBase* prop, string& pvalue, string& ptype );
252};
253
254int createAppMgr();
255
256void init_logging( boost::log::trivial::severity_level level ) {
257 namespace logging = boost::log;
258 namespace keywords = boost::log::keywords;
259 namespace expr = boost::log::expressions;
260
261 logging::add_console_log( std::cout, keywords::format =
262 ( expr::stream << "[" << std::setw( 7 ) << std::left
263 << logging::trivial::severity << "] " << expr::smessage ) );
264
265 logging::core::get()->set_filter( logging::trivial::severity >= level );
266}
267
268//--- Command main program-----------------------------------------------------
269int main( int argc, char** argv )
270//-----------------------------------------------------------------------------
271{
272 init_logging( ( System::isEnvSet( "VERBOSE" ) && !System::getEnv( "VERBOSE" ).empty() )
273 ? boost::log::trivial::info
274 : boost::log::trivial::warning );
275
276 fs::path pwd = fs::initial_path();
277 fs::path out;
278 Strings_t libs;
279 std::string pkgName;
280 std::string userModule;
281
282 // declare a group of options that will be allowed only on command line
283 po::options_description generic( "Generic options" );
284 generic.add_options()( "help,h", "produce this help message" )(
285 "package-name,p", po::value<string>(), "name of the package for which we create the configurables file" )(
286 "input-libraries,i", po::value<string>(), "libraries to extract the component configurables from" )(
287 "input-cfg,c", po::value<string>(),
288 "path to the cfg file holding the description of the Configurable base "
289 "classes, the python module holding the Configurable definitions, etc..." )(
290 "output-dir,o", po::value<string>()->default_value( "../genConfDir" ),
291 "output directory for genconf files." )( "debug-level,d", po::value<int>()->default_value( 0 ), "debug level" )(
292 "load-library,l", po::value<Strings_t>()->composing(), "preloading library" )(
293 "user-module,m", po::value<string>(), "user-defined module to be imported by the genConf-generated one" )(
294 "type", po::value<string>()->default_value( "conf,conf2" ), "comma-separate types of configurables to generate" );
295
296 // declare a group of options that will be allowed both on command line
297 // _and_ in configuration file
298 po::options_description config( "Configuration" );
299 config.add_options()( "configurable-module", po::value<string>()->default_value( "AthenaCommon" ),
300 "Name of the module holding the configurable classes" )(
301 "configurable-default-name", po::value<string>()->default_value( "Configurable.DefaultName" ),
302 "Default name for the configurable instance" )( "configurable-algorithm",
303 po::value<string>()->default_value( "ConfigurableAlgorithm" ),
304 "Name of the configurable base class for Algorithm components" )(
305 "configurable-algtool", po::value<string>()->default_value( "ConfigurableAlgTool" ),
306 "Name of the configurable base class for AlgTool components" )(
307 "configurable-auditor", po::value<string>()->default_value( "ConfigurableAuditor" ),
308 "Name of the configurable base class for Auditor components" )(
309 "configurable-service", po::value<string>()->default_value( "ConfigurableService" ),
310 "Name of the configurable base class for Service components" );
311
312 po::options_description cmdline_options;
313 cmdline_options.add( generic ).add( config );
314
315 po::options_description config_file_options;
316 config_file_options.add( config );
317
318 po::options_description visible( "Allowed options" );
319 visible.add( generic ).add( config );
320
321 po::variables_map vm;
322
323 try {
324 po::store( po::command_line_parser( argc, argv ).options( cmdline_options ).run(), vm );
325
326 po::notify( vm );
327
328 // try to read configuration from the optionally given configuration file
329 if ( vm.contains( "input-cfg" ) ) {
330 string cfgFileName = vm["input-cfg"].as<string>();
331 cfgFileName = fs::system_complete( fs::path( cfgFileName ) ).string();
332 std::ifstream ifs( cfgFileName );
333 po::store( parse_config_file( ifs, config_file_options ), vm );
334 }
335
336 po::notify( vm );
337 } catch ( po::error& err ) {
338 LOG_ERROR << "error detected while parsing command options: " << err.what();
339 return EXIT_FAILURE;
340 }
341
342 //--- Process command options -----------------------------------------------
343 if ( vm.contains( "help" ) ) {
344 cout << visible << endl;
345 return EXIT_FAILURE;
346 }
347
348 if ( vm.contains( "package-name" ) ) {
349 pkgName = vm["package-name"].as<string>();
350 } else {
351 LOG_ERROR << "'package-name' required";
352 cout << visible << endl;
353 return EXIT_FAILURE;
354 }
355
356 if ( vm.contains( "user-module" ) ) {
357 userModule = vm["user-module"].as<string>();
358 LOG_INFO << "INFO: will import user module " << userModule;
359 }
360
361 if ( vm.contains( "input-libraries" ) ) {
362 // re-shape the input arguments:
363 // - removes spurious spaces,
364 // - split into tokens.
365 std::string tmp = vm["input-libraries"].as<std::string>();
366 boost::trim( tmp );
367 boost::split( libs, tmp, boost::is_any_of( " " ), boost::token_compress_on );
368 } else {
369 LOG_ERROR << "input component library(ies) required";
370 cout << visible << endl;
371 return EXIT_FAILURE;
372 }
373
374 if ( vm.contains( "output-dir" ) ) { out = fs::system_complete( fs::path( vm["output-dir"].as<string>() ) ); }
375
376 if ( vm.contains( "debug-level" ) ) { Gaudi::PluginService::SetDebug( vm["debug-level"].as<int>() ); }
377
378 if ( vm.contains( "load-library" ) ) {
379 for ( const auto& lLib : vm["load-library"].as<Strings_t>() ) {
380 // load done through Gaudi helper class
381 System::ImageHandle tmp; // we ignore the library handle
382 unsigned long err = System::loadDynamicLib( lLib, &tmp );
383 if ( err != 1 ) LOG_WARNING << "failed to load: " << lLib;
384 }
385 }
386
387 std::set<conf_t> confTypes;
388 if ( vm.contains( "type" ) ) {
389 for ( const std::string& type : boost::tokenizer{ vm["type"].as<std::string>(), boost::char_separator{ "," } } ) {
390 if ( type == "conf" ) {
391 confTypes.insert( conf_t::CONF );
392 } else if ( type == "conf2" ) {
393 confTypes.insert( conf_t::CONF2 );
394 } else {
395 LOG_ERROR << "unknown configurable type: " << type;
396 cout << visible << endl;
397 return EXIT_FAILURE;
398 }
399 }
400 }
401
402 if ( !fs::exists( out ) ) {
403 try {
404 fs::create_directory( out );
405 } catch ( fs::filesystem_error& err ) {
406 LOG_ERROR << "error creating directory: " << err.what();
407 return EXIT_FAILURE;
408 }
409 }
410
411 {
412 std::ostringstream msg;
413 msg << ":::::: libraries : [ ";
414 std::copy( libs.begin(), libs.end(), std::ostream_iterator<std::string>( msg, " " ) );
415 msg << "] ::::::";
416 LOG_INFO << msg.str();
417 }
418
419 configGenerator py( pkgName, out.string() );
420 py.setConfigurableModule( vm["configurable-module"].as<string>() );
421 py.setConfigurableTypes( confTypes );
422 py.setConfigurableDefaultName( vm["configurable-default-name"].as<string>() );
423 py.setConfigurableAlgorithm( vm["configurable-algorithm"].as<string>() );
424 py.setConfigurableAlgTool( vm["configurable-algtool"].as<string>() );
425 py.setConfigurableAuditor( vm["configurable-auditor"].as<string>() );
426 py.setConfigurableService( vm["configurable-service"].as<string>() );
427
428 int sc = EXIT_FAILURE;
429 try {
430 sc = py.genConfig( libs, userModule );
431 } catch ( exception& e ) {
432 cout << "ERROR: Could not generate Configurable(s) !\n"
433 << "ERROR: Got exception: " << e.what() << endl;
434 return EXIT_FAILURE;
435 }
436
437 {
438 std::ostringstream msg;
439 msg << ":::::: libraries : [ ";
440 std::copy( libs.begin(), libs.end(), std::ostream_iterator<std::string>( msg, " " ) );
441 msg << "] :::::: [DONE]";
442 LOG_INFO << msg.str();
443 }
444 return sc;
445}
446
447//-----------------------------------------------------------------------------
448int configGenerator::genConfig( const Strings_t& libs, const string& userModule )
449//-----------------------------------------------------------------------------
450{
451 const auto endLib = libs.end();
452
453 static const std::string gaudiSvc = "GaudiCoreSvc";
454 const bool isGaudiSvc =
455 std::find_if( libs.begin(), endLib, []( const auto& s ) {
456 return s.find( gaudiSvc ) != std::string::npos; // libs can be <name> or path/to/lib<name>.so
457 } ) != endLib;
458
459 //--- Instantiate ApplicationMgr --------------------------------------------
460 if ( !isGaudiSvc && createAppMgr() ) {
461 cout << "ERROR: ApplicationMgr can not be created. Check environment" << endl;
462 return EXIT_FAILURE;
463 }
464
465 //--- Iterate over component factories --------------------------------------
466 using Gaudi::PluginService::Details::Registry;
467 const Registry& registry = Registry::instance();
468
469 auto bkgNames = registry.loadedFactoryNames();
470
471 ISvcLocator* svcLoc = Gaudi::svcLocator();
472 IInterface* dummySvc = new Service( "DummySvc", svcLoc );
473 dummySvc->addRef();
474
475 bool allGood = true;
476
477 // iterate over all the requested libraries
478 for ( const auto& iLib : libs ) {
479 std::string lib = fs::path( iLib ).stem().string();
480 if ( lib.compare( 0, 3, "lib" ) == 0 ) {
481 lib = lib.substr( 3 ); // For *NIX remove "lib"
482 }
483 LOG_INFO << ":::: processing library: " << iLib << "...";
484
485 // reset state
486 m_importGaudiHandles = false;
487 m_importDataHandles = false;
488 m_pyBuf.str( "" );
489 m_dbBuf.str( "" );
490 m_db2Buf.str( "" );
491
492 //--- Load component library ----------------------------------------------
493 if ( !registry.loadPluginLibrary( iLib ) ) {
495 allGood = false;
496 continue;
497 }
498
499 const auto& factories = registry.factories();
500 for ( const auto& factoryName : registry.loadedFactoryNames() ) {
501 if ( bkgNames.find( factoryName ) != bkgNames.end() ) {
502 if ( Gaudi::PluginService::Details::logger().level() <= 1 ) {
503 LOG_INFO << "\t==> skipping [" << factoryName << "]...";
504 }
505 continue;
506 }
507 auto entry = factories.find( factoryName );
508 if ( entry == end( factories ) ) {
509 LOG_ERROR << "inconsistency in component factories list: I cannot find anymore " << factoryName;
510 continue;
511 }
512 const auto& info = entry->second;
513 if ( !info.is_set() ) continue;
514
515 // do not generate configurables for the Reflex-compatible aliases
516 if ( !info.getprop( "ReflexName" ).empty() ) continue;
517
518 // Atlas contributed code (patch #1247)
519 // Skip the generation of configurables if the component does not come
520 // from the same library we are processing (i.e. we found a symbol that
521 // is coming from a library loaded by the linker).
522 if ( libNativeName( lib ) != info.library ) {
523 LOG_WARNING << "library [" << lib << "] exposes factory [" << factoryName << "] which is declared in ["
524 << info.library << "] !!";
525 continue;
526 }
527
528 component_t type = component_t::Unknown;
529 {
530 const auto ft = allowedFactories.find( info.factory.type().name() );
531 if ( ft != allowedFactories.end() ) {
532 type = ft->second;
533 } else if ( factoryName == "ApplicationMgr" ) {
534 type = component_t::ApplicationMgr;
535 } else
536 continue;
537 }
538
539 // handle possible problems with templated components
540 std::string name = boost::trim_copy( factoryName );
541
542 const auto className = info.getprop( "ClassName" );
543 LOG_INFO << " - component: " << className << " (" << ( className != name ? ( name + ": " ) : std::string() )
544 << type << ")";
545
546 string cname = "DefaultName";
548 try {
549 switch ( type ) {
550 case component_t::Algorithm:
551 prop = SmartIF<IAlgorithm>( Gaudi::Algorithm::Factory::create( factoryName, cname, svcLoc ).release() );
552 break;
553 case component_t::Service:
554 prop = SmartIF<IService>( Service::Factory::create( factoryName, cname, svcLoc ).release() );
555 break;
556 case component_t::AlgTool:
557 prop =
558 SmartIF<IAlgTool>( AlgTool::Factory::create( factoryName, cname, toString( type ), dummySvc ).release() );
559 // FIXME: AlgTool base class increase artificially by 1 the refcount.
560 prop->release();
561 break;
562 case component_t::Auditor:
563 prop = SmartIF<Gaudi::IAuditor>( Gaudi::Auditor::Factory::create( factoryName, cname, svcLoc ).release() );
564 break;
565 case component_t::ApplicationMgr:
566 prop = SmartIF<ISvcLocator>( svcLoc );
567 break;
568 default:
569 continue; // unknown
570 }
571 } catch ( exception& e ) {
572 LOG_ERROR << "Error instantiating " << name << " from " << iLib;
573 LOG_ERROR << "Got exception: " << e.what();
574 allGood = false;
575 continue;
576 } catch ( ... ) {
577 LOG_ERROR << "Error instantiating " << name << " from " << iLib;
578 allGood = false;
579 continue;
580 }
581 if ( prop ) {
582 if ( m_confTypes.contains( conf_t::CONF ) && !genComponent( lib, name, type, prop->getProperties(), info ) ) {
583 allGood = false;
584 }
585 if ( m_confTypes.contains( conf_t::CONF2 ) &&
586 !genComponent2( name, type, prop->getProperties(), prop->getInterfaceNames(), info ) ) {
587 allGood = false;
588 }
589 prop.reset();
590 } else {
591 LOG_ERROR << "could not cast IInterface* object to an IProperty* !";
592 LOG_ERROR << "NO Configurable will be generated for [" << name << "] !";
593 allGood = false;
594 }
595 } //> end loop over factories
596
600 if ( m_confTypes.contains( conf_t::CONF ) ) {
601 const std::string pyName = ( fs::path( m_outputDirName ) / fs::path( lib + "Conf.py" ) ).string();
602 const std::string dbName = ( fs::path( m_outputDirName ) / fs::path( lib + ".confdb" ) ).string();
603
604 std::fstream py( pyName, std::ios_base::out | std::ios_base::trunc );
605 std::fstream db( dbName, std::ios_base::out | std::ios_base::trunc );
606
607 genHeader( py, db );
608 if ( !userModule.empty() ) py << "from " << userModule << " import *" << endl;
609 genBody( py, db );
610 genTrailer( py, db );
611 }
612 if ( m_confTypes.contains( conf_t::CONF2 ) ) {
613 const std::string db2Name = ( fs::path( m_outputDirName ) / fs::path( lib + ".confdb2_part" ) ).string();
614 std::fstream db2( db2Name, std::ios_base::out | std::ios_base::trunc );
615 db2 << "{\n" << m_db2Buf.str() << "}\n";
616 }
617
618 } //> end loop over libraries
619
620 dummySvc->release();
621 dummySvc = 0;
622
623 return allGood ? EXIT_SUCCESS : EXIT_FAILURE;
624}
625
626void configGenerator::genImport( std::ostream& s, std::string_view frmt, std::string indent = "" ) {
627
628 std::string::size_type pos = 0, nxtpos = 0;
629 std::string mod;
630
631 while ( std::string::npos != pos ) {
632 // find end of module name
633 nxtpos = m_configurable[component_t::Module].find_first_of( ',', pos );
634
635 // Prepare import string
636 mod = m_configurable[component_t::Module].substr( pos, nxtpos - pos );
637 std::ostringstream import_cmd;
638 import_cmd << fmt::format( fmt::runtime( frmt ), mod );
639
640 // append a normal import_cmd or a try/except enclosed one depending
641 // on availability of a fall-back module (next in the list)
642 if ( std::string::npos == nxtpos ) {
643 // last possible module
644 s << indent << import_cmd.str() << "\n" << flush;
645 pos = std::string::npos;
646 } else {
647 // we have a fallback for this
648 s << indent << "try:\n"
649 << indent << py_tab << import_cmd.str() << "\n"
650 << indent << "except ImportError:\n"
651 << flush;
652 pos = nxtpos + 1;
653 }
654 // increase indentation level for next iteration
655 indent += py_tab;
656 }
657}
658
659//-----------------------------------------------------------------------------
660void configGenerator::genHeader( std::ostream& py, std::ostream& db )
661//-----------------------------------------------------------------------------
662{
663 // python file part
664 std::string now = Gaudi::Time::current().format( true );
665 py << "#" << now //<< "\n"
666 << "\"\"\"Automatically generated. DO NOT EDIT please\"\"\"\n";
667
668 if ( m_importGaudiHandles ) { py << "from GaudiKernel.GaudiHandles import *\n"; }
669
670 if ( m_importDataHandles ) { py << "from GaudiKernel.DataHandle import DataHandle\n"; }
671
672 genImport( py, "from {}.Configurable import *" );
673
674 // db file part
675 db << "## -*- ascii -*- \n"
676 << "# db file automatically generated by genconf on: " << now << "\n"
677 << flush;
678}
679//-----------------------------------------------------------------------------
680void configGenerator::genTrailer( std::ostream& /*py*/, std::ostream& db )
681//-----------------------------------------------------------------------------
682{
683 // db file part
684 db << "## " << m_pkgName << "\n" << std::flush;
685}
686
687//-----------------------------------------------------------------------------
688bool configGenerator::genComponent( const std::string& libName, const std::string& componentName,
689 component_t componentType, const vector<PropertyBase*>& properties,
690 const Gaudi::PluginService::Details::Registry::FactoryInfo& info )
691//-----------------------------------------------------------------------------
692{
693 auto cname = pythonizeName( componentName );
694 const auto decl_loc = info.getprop( "declaration_location" );
695
696 std::vector<std::pair<std::string, std::string>> propDoc;
697 propDoc.reserve( properties.size() );
698
699 m_pyBuf << "\nclass " << cname << "( " << m_configurable[componentType] << " ) :\n";
700 m_pyBuf << " __slots__ = { \n";
701 for ( const auto& prop : properties ) {
702 const string& pname = prop->name();
703 // Validate property name (it must be a valid Python identifier)
704 if ( !boost::regex_match( pname, pythonIdentifier ) ) {
705 LOG_ERROR << "invalid property name \"" << pname << "\" in component " << cname << " (invalid Python identifier)"
706 << std::endl;
707 // try to make the buffer at least more or less valid python code.
708 m_pyBuf << " #ERROR-invalid identifier '" << pname << "'\n"
709 << " }\n";
710 return false;
711 }
712
713 string pvalue, ptype;
714 pythonizeValue( prop, pvalue, ptype );
715 m_pyBuf << " '" << pname << "' : " << pvalue << ",\n";
716
717 if ( prop->documentation() != "none" ) {
718 propDoc.emplace_back( pname, prop->documentation() + " [" + prop->ownerTypeName() + "]" );
719 }
720 }
721 m_pyBuf << " }\n";
722 m_pyBuf << " _propertyDocDct = { \n";
723 for ( const auto& prop : propDoc ) {
724 m_pyBuf << std::setw( 5 ) << "'" << prop.first << "' : "
725 << "\"\"\" " << prop.second << " \"\"\",\n";
726 }
727 m_pyBuf << " }\n";
728
729 if ( !decl_loc.empty() ) { m_pyBuf << " __declaration_location__ = '" << decl_loc << "'\n"; }
730 m_pyBuf << " def __init__(self, name = " << m_configurable[component_t::DefaultName] << ", **kwargs):\n"
731 << " super(" << cname << ", self).__init__(name)\n"
732 << " for n,v in kwargs.items():\n"
733 << " setattr(self, n, v)\n"
734 << " def getDlls( self ):\n"
735 << " return '" << libName << "'\n"
736 << " def getType( self ):\n"
737 << " return '" << componentName << "'\n"
738 << " pass # class " << cname << "\n"
739 << flush;
740
741 // name of the auto-generated module
742 const string pyName = ( fs::path( m_outputDirName ) / fs::path( libName + "Conf.py" ) ).string();
743 const string modName = fs::path( pyName ).filename().stem().string();
744
745 // now the db part
746 m_dbBuf << m_pkgName << "." << modName << " " << libName << " " << cname << "\n" << flush;
747
748 return true;
749}
750
751//-----------------------------------------------------------------------------
752bool configGenerator::genComponent2( const std::string& componentName, component_t componentType,
753 const vector<PropertyBase*>& properties, const vector<std::string>& interfaces,
754 const Gaudi::PluginService::Details::Registry::FactoryInfo& info )
755//-----------------------------------------------------------------------------
756{
757 m_db2Buf << " '" << componentName << "': {\n";
758 m_db2Buf << " '__component_type__': '";
759 switch ( componentType ) {
760 case component_t::Algorithm:
761 m_db2Buf << "Algorithm";
762 break;
763 case component_t::AlgTool:
764 m_db2Buf << "AlgTool";
765 break;
766 case component_t::ApplicationMgr: // FALLTROUGH
767 case component_t::Service:
768 m_db2Buf << "Service";
769 break;
770 case component_t::Auditor:
771 m_db2Buf << "Auditor";
772 break;
773 default:
774 m_db2Buf << "Unknown";
775 }
776
777 const auto decl_loc = info.getprop( "declaration_location" );
778 if ( !decl_loc.empty() ) { m_db2Buf << "',\n '__declaration_location__': '" << decl_loc; }
779
780 m_db2Buf << "',\n '__interfaces__': (";
781 for ( const auto& intf : std::set<std::string>{ begin( interfaces ), end( interfaces ) } ) {
782 if ( ignored_interfaces.find( intf ) == end( ignored_interfaces ) ) { m_db2Buf << '\'' << intf << "', "; }
783 }
784 m_db2Buf << "),\n 'properties': {\n";
785
786 bool success = true;
787 for ( const auto& prop : properties ) {
788 const string& pname = prop->name();
789 // Validate property name (it must be a valid Python identifier)
790 if ( !boost::regex_match( pname, pythonIdentifier ) ) {
791 LOG_ERROR << "invalid property name \"" << pname << "\" in component " << componentName
792 << " (invalid Python identifier)" << std::endl;
793 m_db2Buf << " #ERROR-invalid identifier '" << pname << "'\n";
794 success = false;
795 break;
796 }
797
798 string pvalue, ptype;
799 pythonizeValue( prop, pvalue, ptype );
800
801 m_db2Buf << " '" << pname << "': ('" << ptype << "', " << pvalue << ", '''" << prop->documentation()
802 << " [" << prop->ownerTypeName() << "]'''";
803 auto sem = prop->semantics();
804 if ( !sem.empty() ) { m_db2Buf << ", '" << sem << '\''; }
805 m_db2Buf << "),\n";
806 }
807
808 m_db2Buf << " },\n },\n";
809
810 return success;
811}
812
813//-----------------------------------------------------------------------------
814void configGenerator::pythonizeValue( const PropertyBase* p, string& pvalue, string& ptype )
815//-----------------------------------------------------------------------------
816{
817 const std::string cvalue = p->toString();
818 const std::type_index ti = std::type_index( *p->type_info() );
819 ptype = System::typeinfoName( *p->type_info() );
820
821 if ( ti == typeIndex<bool>() ) {
822 pvalue = ( cvalue == "0" || cvalue == "False" || cvalue == "false" ) ? "False" : "True";
823 } else if ( ti == typeIndex<char>() || ti == typeIndex<signed char>() || ti == typeIndex<unsigned char>() ||
824 ti == typeIndex<short>() || ti == typeIndex<unsigned short>() || ti == typeIndex<int>() ||
825 ti == typeIndex<unsigned int>() || ti == typeIndex<long>() || ti == typeIndex<unsigned long>() ||
826 ti == typeIndex<long long>() || ti == typeIndex<unsigned long long>() ) {
827 pvalue = cvalue;
828 } else if ( ti == typeIndex<float>() || ti == typeIndex<double>() || ti == typeIndex<long double>() ) {
829 // forces python to handle this as a float: put a dot in there...
830 pvalue = boost::to_lower_copy( cvalue );
831 if ( std::string::npos != pvalue.find( "nan" ) ) {
832 pvalue = "float('nan')";
833 } else if ( std::string::npos == pvalue.find( "." ) && std::string::npos == pvalue.find( "e" ) ) {
834 pvalue = cvalue + ".0";
835 }
836 } else if ( ti == typeIndex<string>() ) {
837 pvalue = quote( cvalue );
838 } else if ( ti == typeIndex<nlohmann::json>() ) {
839 pvalue = quote( cvalue );
840 } else if ( ti == typeIndex<GaudiHandleBase>() ) {
841 const GaudiHandleProperty& hdl = dynamic_cast<const GaudiHandleProperty&>( *p );
842 const GaudiHandleBase& base = hdl.value();
843
844 pvalue = base.pythonRepr();
845 ptype = base.pythonPropertyClassName();
847 } else if ( ti == typeIndex<GaudiHandleArrayBase>() ) {
848 const GaudiHandleArrayProperty& hdl = dynamic_cast<const GaudiHandleArrayProperty&>( *p );
849 const GaudiHandleArrayBase& base = hdl.value();
850
851 pvalue = base.pythonRepr();
852 ptype = base.pythonPropertyClassName();
854 } else if ( auto hdl = dynamic_cast<const DataHandleProperty*>( p ); hdl ) {
855 // dynamic_cast to support also classes derived from DataHandleProperty
856 const Gaudi::DataHandle& base = hdl->value();
857
858 pvalue = base.pythonRepr();
859 m_importDataHandles = true;
860 } else {
861 std::ostringstream v_str;
862 v_str.setf( std::ios::showpoint ); // to correctly display floats
863 p->toStream( v_str );
864 pvalue = v_str.str();
865 }
866}
867
868//-----------------------------------------------------------------------------
870//-----------------------------------------------------------------------------
871{
873 SmartIF<IAppMgrUI> appUI( iface );
874 auto propMgr = appUI.as<IProperty>();
875 if ( !propMgr || !appUI ) return EXIT_FAILURE;
876
877 propMgr->setProperty( "JobOptionsType", "NONE" ).ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ ); // No job
878 // options
879 propMgr->setProperty( "AppName", "" ).ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ ); // No initial printout
880 // message
881 propMgr->setProperty( "OutputLevel", 7 ).ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ ); // No other printout
882 // messages
883 appUI->configure().ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
884 auto msgSvc = SmartIF<IMessageSvc>{ iface }.as<IProperty>();
885 msgSvc->setPropertyRepr( "setWarning", "['DefaultName', 'PropertyHolder']" )
886 .ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
887 msgSvc->setProperty( "Format", "%T %0W%M" ).ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
888 return EXIT_SUCCESS;
889}
std::ostream & operator<<(std::ostream &s, AlgsExecutionStates::State x)
Streaming of State values.
int main()
Base class from which all the concrete tool classes should be derived.
Definition AlgTool.h:55
Alias for backward compatibility.
Definition Algorithm.h:58
The Application Manager class.
Converter base class.
Definition Converter.h:33
DataHandleProperty.h GaudiKernel/DataHandleProperty.h.
A DataObject is the base class of any identifiable object on any data store.
Definition DataObject.h:37
PropertyBase base class allowing PropertyBase* collections to be "homogeneous".
const std::type_info * type_info() const
property type-info
virtual std::string toString() const =0
value -> string
virtual void toStream(std::ostream &out) const =0
value -> stream
std::string format(bool local, std::string spec="%c") const
Format the time using strftime.
Definition Time.cpp:155
static Time current()
Returns the current time.
Definition Time.cpp:41
Base class of array's of various gaudihandles.
const GaudiHandleArrayBase & value() const
Definition Property.h:679
Base class to handles to be used in lieu of naked pointers to various Gaudi components.
const GaudiHandleBase & value() const
Definition Property.h:642
The data converters are responsible to translate data from one representation into another.
Definition IConverter.h:65
Definition of the basic interface.
Definition IInterface.h:225
virtual unsigned long addRef() const =0
Increment the reference count of Interface instance.
virtual unsigned long release() const =0
Release Interface instance.
The IProperty is the basic interface for all components which have properties that can be set or get.
Definition IProperty.h:32
StatusCode setProperty(const Gaudi::Details::PropertyBase &p)
Set the property from a property.
Definition IProperty.h:38
The ISvcLocator is the interface implemented by the Service Factory in the Application Manager to loc...
Definition ISvcLocator.h:42
Base class for all services.
Definition Service.h:39
Small smart pointer class with automatic reference counting for IInterface.
Definition SmartIF.h:28
SmartIF< IFace > as() const
return a new SmartIF instance to another interface
Definition SmartIF.h:110
void reset(TYPE *ptr=nullptr)
Set the internal pointer to the passed one disposing of the old one.
Definition SmartIF.h:88
void ignore() const
Allow discarding a StatusCode without warning.
Definition StatusCode.h:128
void pythonizeValue(const PropertyBase *prop, string &pvalue, string &ptype)
handle the "marshalling" of Properties
Definition genconf.cpp:814
void setConfigurableDefaultName(const std::string &defaultName)
customize the default name for configurable instances
Definition genconf.cpp:212
void setConfigurableTypes(const std::set< conf_t > &types)
customize configurable types to generate
Definition genconf.cpp:206
configGenerator(const string &pkgName, const string &outputDirName)
Definition genconf.cpp:196
string m_outputDirName
absolute path to the directory where genconf will store auto-generated files (Configurables and Confi...
Definition genconf.cpp:166
void genHeader(std::ostream &pyOut, std::ostream &dbOut)
Definition genconf.cpp:660
void setConfigurableAuditor(const std::string &cfgAuditor)
customize the configurable base class for AlgTool component
Definition genconf.cpp:225
void genImport(std::ostream &s, std::string_view frmt, std::string indent)
Definition genconf.cpp:626
std::set< conf_t > m_confTypes
Types of configurables to generate.
Definition genconf.cpp:177
stringstream m_pyBuf
buffer of auto-generated configurables
Definition genconf.cpp:169
bool m_importGaudiHandles
switch to decide if the generated configurables need to import GaudiHandles (ie: if one of the compon...
Definition genconf.cpp:173
void genTrailer(std::ostream &pyOut, std::ostream &dbOut)
Definition genconf.cpp:680
bool m_importDataHandles
Definition genconf.cpp:174
bool genComponent2(const std::string &componentName, component_t componentType, const vector< PropertyBase * > &properties, const std::vector< std::string > &interfaces, const Gaudi::PluginService::Details::Registry::FactoryInfo &info)
Definition genconf.cpp:752
stringstream m_dbBuf
buffer of generated configurables informations for the "Db" file The "Db" file is holding information...
Definition genconf.cpp:183
std::map< component_t, std::string > m_configurable
Configurable customization.
Definition genconf.cpp:193
int genConfig(const Strings_t &modules, const string &userModule)
main entry point of this class:
Definition genconf.cpp:448
void setConfigurableModule(const std::string &moduleName)
customize the Module name where configurable base classes are defined
Definition genconf.cpp:209
void genBody(std::ostream &pyOut, std::ostream &dbOut)
Definition genconf.cpp:244
stringstream m_db2Buf
buffer of generated GaudiConfig2 configurables
Definition genconf.cpp:186
void setConfigurableService(const std::string &cfgService)
customize the configurable base class for Service component
Definition genconf.cpp:228
void setConfigurableAlgorithm(const std::string &cfgAlgorithm)
customize the configurable base class for Algorithm component
Definition genconf.cpp:217
bool genComponent(const std::string &libName, const std::string &componentName, component_t componentType, const vector< PropertyBase * > &properties, const Gaudi::PluginService::Details::Registry::FactoryInfo &info)
Definition genconf.cpp:688
void setConfigurableAlgTool(const std::string &cfgAlgTool)
customize the configurable base class for AlgTool component
Definition genconf.cpp:222
string m_pkgName
name of the package we are processing
Definition genconf.cpp:162
std::vector< std::string > Strings_t
Definition genconf.cpp:76
void init_logging(boost::log::trivial::severity_level level)
Definition genconf.cpp:256
std::vector< fs::path > LibPathNames_t
Definition genconf.cpp:77
int createAppMgr()
Definition genconf.cpp:869
#define LOG_ERROR
Definition genconf.cpp:66
#define LOG_WARNING
Definition genconf.cpp:67
#define LOG_INFO
Definition genconf.cpp:68
GAUDI_API ISvcLocator * svcLocator()
GAUDI_API IAppMgrUI * createApplicationMgr()
GAUDI_API bool isEnvSet(const char *var)
Check if an environment variable is set or not.
Definition System.cpp:334
GAUDI_API unsigned long loadDynamicLib(const std::string &name, ImageHandle *handle)
Load dynamic link library.
Definition System.cpp:109
GAUDI_API const std::string getLastErrorString()
Get last system error as string.
Definition System.cpp:228
GAUDI_API const std::string typeinfoName(const std::type_info &)
Get platform independent information about the class type.
Definition System.cpp:254
void * ImageHandle
Definition of an image handle.
Definition ModuleInfo.h:25
GAUDI_API std::string getEnv(const char *var)
get a particular environment variable (returning "UNKNOWN" if not set)
Definition System.cpp:314
STL namespace.