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