Loading [MathJax]/jax/output/HTML-CSS/config.js
The Gaudi Framework  master (d98a2936)
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-2025 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>
22 #include <GaudiKernel/Bootstrap.h>
23 #include <GaudiKernel/DataHandle.h>
26 #include <GaudiKernel/HashMap.h>
27 #include <GaudiKernel/IAlgTool.h>
28 #include <GaudiKernel/IAlgorithm.h>
29 #include <GaudiKernel/IAppMgrUI.h>
30 #include <GaudiKernel/IProperty.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 <set>
58 #include <sstream>
59 #include <type_traits>
60 #include <vector>
61 
62 namespace po = boost::program_options;
63 namespace fs = boost::filesystem;
64 
65 #define LOG_ERROR BOOST_LOG_TRIVIAL( error )
66 #define LOG_WARNING BOOST_LOG_TRIVIAL( warning )
67 #define LOG_INFO BOOST_LOG_TRIVIAL( info )
68 
69 using namespace std;
71 
72 class IConverter;
73 
74 // useful typedefs
75 typedef std::vector<std::string> Strings_t;
76 typedef std::vector<fs::path> LibPathNames_t;
77 
78 namespace {
79 
80  std::string quote( std::string_view sv ) {
81  std::ostringstream s;
82  s << std::quoted( sv, '\'' );
83  return s.str();
84  }
85 
86  const std::string py_tab = " ";
87 
90  const boost::regex pythonIdentifier( "^[a-zA-Z_][a-zA-Z0-9_]*$" );
91 
92  //-----------------------------------------------------------------------------
93  enum class component_t {
94  Module,
95  DefaultName,
96  Algorithm,
97  AlgTool,
98  Auditor,
99  Service,
100  ApplicationMgr,
101  IInterface,
102  Converter,
103  DataObject,
104  Unknown
105  };
106 
107  enum class conf_t {
108  CONF, // legacy configurables
109  CONF2 // GaudiConfig2 configurables
110  };
111 
112  const std::map<std::string, component_t> allowedFactories{
113  { typeid( Gaudi::Algorithm::Factory::FactoryType ).name(), component_t::Algorithm },
114  { typeid( Service::Factory::FactoryType ).name(), component_t::Service },
115  { typeid( AlgTool::Factory::FactoryType ).name(), component_t::AlgTool },
116  // factories for new Auditors
117  { typeid( Gaudi::Auditor::Factory::FactoryType ).name(), component_t::Auditor },
118  };
119 
120  const std::string& toString( component_t type ) {
121  static const std::array<std::string, 11> names = { "Module", "DefaultName", "Algorithm", "AlgTool",
122  "Auditor", "Service", "ApplicationMgr", "IInterface",
123  "Converter", "DataObject", "Unknown" };
124  return names.at( static_cast<std::underlying_type_t<component_t>>( type ) );
125  }
126  std::ostream& operator<<( std::ostream& os, component_t type ) { return os << toString( type ); }
127 
128  std::set<std::string> ignored_interfaces{
129  { "IInterface", "IProperty", "INamedInterface", "IAlgorithm", "IAlgTool", "IService", "IAuditor" } };
130 
131  //-----------------------------------------------------------------------------
133  std::string pythonizeName( const std::string& name ) {
134  static const string in( "<>&*,: ()." );
135  static const string out( "__rp__s___" );
136  auto r = boost::algorithm::replace_all_copy( name, ", ", "," );
137  for ( auto& c : r ) {
138  auto rep = in.find( c );
139  if ( rep != string::npos ) c = out[rep];
140  }
141  return r;
142  }
143  //-----------------------------------------------------------------------------
144  template <typename T>
145  std::type_index typeIndex() {
146  return std::type_index{ typeid( T ) };
147  }
148  //-----------------------------------------------------------------------------
149  inline std::string libNativeName( const std::string& libName ) {
150 #if defined( __linux ) || defined( __APPLE__ )
151  return "lib" + libName + ".so";
152 #else
153  // variant of the GIGO design pattern
154  return libName;
155 #endif
156  }
157 } // namespace
158 
161  string m_pkgName;
162 
166 
168  stringstream m_pyBuf;
169 
172  bool m_importGaudiHandles = false;
173  bool m_importDataHandles = false;
174 
176  std::set<conf_t> m_confTypes;
177 
182  stringstream m_dbBuf;
183 
185  stringstream m_db2Buf;
186 
192  std::map<component_t, std::string> m_configurable;
193 
194 public:
195  configGenerator( const string& pkgName, const string& outputDirName )
196  : m_pkgName( pkgName ), m_outputDirName( outputDirName ) {}
197 
202  int genConfig( const Strings_t& modules, const string& userModule );
203 
205  void setConfigurableTypes( const std::set<conf_t>& types ) { m_confTypes = types; }
206 
208  void setConfigurableModule( const std::string& moduleName ) { m_configurable[component_t::Module] = moduleName; }
209 
211  void setConfigurableDefaultName( const std::string& defaultName ) {
212  m_configurable[component_t::DefaultName] = defaultName;
213  }
214 
216  void setConfigurableAlgorithm( const std::string& cfgAlgorithm ) {
217  m_configurable[component_t::Algorithm] = cfgAlgorithm;
218  }
219 
221  void setConfigurableAlgTool( const std::string& cfgAlgTool ) { m_configurable[component_t::AlgTool] = cfgAlgTool; }
222 
224  void setConfigurableAuditor( const std::string& cfgAuditor ) { m_configurable[component_t::Auditor] = cfgAuditor; }
225 
227  void setConfigurableService( const std::string& cfgService ) {
228  m_configurable[component_t::Service] = cfgService;
229  m_configurable[component_t::ApplicationMgr] = cfgService;
230  }
231 
232 private:
233  bool genComponent( const std::string& libName, const std::string& componentName, component_t componentType,
234  const vector<PropertyBase*>& properties,
235  const Gaudi::PluginService::Details::Registry::FactoryInfo& info );
236 
237  bool genComponent2( const std::string& componentName, component_t componentType,
238  const vector<PropertyBase*>& properties, const std::vector<std::string>& interfaces,
239  const Gaudi::PluginService::Details::Registry::FactoryInfo& info );
240 
241  void genImport( std::ostream& s, std::string_view frmt, std::string indent );
242  void genHeader( std::ostream& pyOut, std::ostream& dbOut );
243  void genBody( std::ostream& pyOut, std::ostream& dbOut ) {
244  pyOut << m_pyBuf.str() << flush;
245  dbOut << m_dbBuf.str() << flush;
246  }
247  void genTrailer( std::ostream& pyOut, std::ostream& dbOut );
248 
250  void pythonizeValue( const PropertyBase* prop, string& pvalue, string& ptype );
251 };
252 
253 int createAppMgr();
254 
255 void init_logging( boost::log::trivial::severity_level level ) {
256  namespace logging = boost::log;
257  namespace keywords = boost::log::keywords;
258  namespace expr = boost::log::expressions;
259 
260  logging::add_console_log( std::cout, keywords::format =
261  ( expr::stream << "[" << std::setw( 7 ) << std::left
262  << logging::trivial::severity << "] " << expr::smessage ) );
263 
264  logging::core::get()->set_filter( logging::trivial::severity >= level );
265 }
266 
267 //--- Command main program-----------------------------------------------------
268 int main( int argc, char** argv )
269 //-----------------------------------------------------------------------------
270 {
271  init_logging( ( System::isEnvSet( "VERBOSE" ) && !System::getEnv( "VERBOSE" ).empty() )
272  ? boost::log::trivial::info
273  : boost::log::trivial::warning );
274 
275  fs::path pwd = fs::initial_path();
276  fs::path out;
277  Strings_t libs;
278  std::string pkgName;
279  std::string userModule;
280 
281  // declare a group of options that will be allowed only on command line
282  po::options_description generic( "Generic options" );
283  generic.add_options()( "help,h", "produce this help message" )(
284  "package-name,p", po::value<string>(), "name of the package for which we create the configurables file" )(
285  "input-libraries,i", po::value<string>(), "libraries to extract the component configurables from" )(
286  "input-cfg,c", po::value<string>(),
287  "path to the cfg file holding the description of the Configurable base "
288  "classes, the python module holding the Configurable definitions, etc..." )(
289  "output-dir,o", po::value<string>()->default_value( "../genConfDir" ),
290  "output directory for genconf files." )( "debug-level,d", po::value<int>()->default_value( 0 ), "debug level" )(
291  "load-library,l", po::value<Strings_t>()->composing(), "preloading library" )(
292  "user-module,m", po::value<string>(), "user-defined module to be imported by the genConf-generated one" )(
293  "no-init", "do not generate the (empty) __init__.py" )(
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  if ( EXIT_SUCCESS == sc && !vm.contains( "no-init" ) ) {
438  // create an empty __init__.py file in the output dir
439  std::fstream initPy( ( out / fs::path( "__init__.py" ) ).string(), std::ios_base::out | std::ios_base::trunc );
440  initPy << "## Hook for " << pkgName << " genConf module\n" << flush;
441  }
442 
443  {
444  std::ostringstream msg;
445  msg << ":::::: libraries : [ ";
446  std::copy( libs.begin(), libs.end(), std::ostream_iterator<std::string>( msg, " " ) );
447  msg << "] :::::: [DONE]";
448  LOG_INFO << msg.str();
449  }
450  return sc;
451 }
452 
453 //-----------------------------------------------------------------------------
454 int configGenerator::genConfig( const Strings_t& libs, const string& userModule )
455 //-----------------------------------------------------------------------------
456 {
457  const auto endLib = libs.end();
458 
459  static const std::string gaudiSvc = "GaudiCoreSvc";
460  const bool isGaudiSvc =
461  std::find_if( libs.begin(), endLib, []( const auto& s ) {
462  return s.find( gaudiSvc ) != std::string::npos; // libs can be <name> or path/to/lib<name>.so
463  } ) != endLib;
464 
465  //--- Instantiate ApplicationMgr --------------------------------------------
466  if ( !isGaudiSvc && createAppMgr() ) {
467  cout << "ERROR: ApplicationMgr can not be created. Check environment" << endl;
468  return EXIT_FAILURE;
469  }
470 
471  //--- Iterate over component factories --------------------------------------
472  using Gaudi::PluginService::Details::Registry;
473  const Registry& registry = Registry::instance();
474 
475  auto bkgNames = registry.loadedFactoryNames();
476 
477  ISvcLocator* svcLoc = Gaudi::svcLocator();
478  IInterface* dummySvc = new Service( "DummySvc", svcLoc );
479  dummySvc->addRef();
480 
481  bool allGood = true;
482 
483  // iterate over all the requested libraries
484  for ( const auto& iLib : libs ) {
485  std::string lib = fs::path( iLib ).stem().string();
486  if ( lib.compare( 0, 3, "lib" ) == 0 ) {
487  lib = lib.substr( 3 ); // For *NIX remove "lib"
488  }
489  LOG_INFO << ":::: processing library: " << iLib << "...";
490 
491  // reset state
492  m_importGaudiHandles = false;
493  m_importDataHandles = false;
494  m_pyBuf.str( "" );
495  m_dbBuf.str( "" );
496  m_db2Buf.str( "" );
497 
498  //--- Load component library ----------------------------------------------
499  System::ImageHandle handle;
500  unsigned long err = System::loadDynamicLib( iLib, &handle );
501  if ( err != 1 ) {
503  allGood = false;
504  continue;
505  }
506 
507  const auto& factories = registry.factories();
508  for ( const auto& factoryName : registry.loadedFactoryNames() ) {
509  if ( bkgNames.find( factoryName ) != bkgNames.end() ) {
511  LOG_INFO << "\t==> skipping [" << factoryName << "]...";
512  }
513  continue;
514  }
515  auto entry = factories.find( factoryName );
516  if ( entry == end( factories ) ) {
517  LOG_ERROR << "inconsistency in component factories list: I cannot find anymore " << factoryName;
518  continue;
519  }
520  const auto& info = entry->second;
521  if ( !info.is_set() ) continue;
522 
523  // do not generate configurables for the Reflex-compatible aliases
524  if ( !info.getprop( "ReflexName" ).empty() ) continue;
525 
526  // Atlas contributed code (patch #1247)
527  // Skip the generation of configurables if the component does not come
528  // from the same library we are processing (i.e. we found a symbol that
529  // is coming from a library loaded by the linker).
530  if ( libNativeName( lib ) != info.library ) {
531  LOG_WARNING << "library [" << lib << "] exposes factory [" << factoryName << "] which is declared in ["
532  << info.library << "] !!";
533  continue;
534  }
535 
536  component_t type = component_t::Unknown;
537  {
538  const auto ft = allowedFactories.find( info.factory.type().name() );
539  if ( ft != allowedFactories.end() ) {
540  type = ft->second;
541  } else if ( factoryName == "ApplicationMgr" ) {
542  type = component_t::ApplicationMgr;
543  } else
544  continue;
545  }
546 
547  // handle possible problems with templated components
548  std::string name = boost::trim_copy( factoryName );
549 
550  const auto className = info.getprop( "ClassName" );
551  LOG_INFO << " - component: " << className << " (" << ( className != name ? ( name + ": " ) : std::string() )
552  << type << ")";
553 
554  string cname = "DefaultName";
555  SmartIF<IProperty> prop;
556  try {
557  switch ( type ) {
558  case component_t::Algorithm:
559  prop = SmartIF<IAlgorithm>( Gaudi::Algorithm::Factory::create( factoryName, cname, svcLoc ).release() );
560  break;
561  case component_t::Service:
562  prop = SmartIF<IService>( Service::Factory::create( factoryName, cname, svcLoc ).release() );
563  break;
564  case component_t::AlgTool:
565  prop =
566  SmartIF<IAlgTool>( AlgTool::Factory::create( factoryName, cname, toString( type ), dummySvc ).release() );
567  // FIXME: AlgTool base class increase artificially by 1 the refcount.
568  prop->release();
569  break;
570  case component_t::Auditor:
571  prop = SmartIF<Gaudi::IAuditor>( Gaudi::Auditor::Factory::create( factoryName, cname, svcLoc ).release() );
572  break;
573  case component_t::ApplicationMgr:
574  prop = SmartIF<ISvcLocator>( svcLoc );
575  break;
576  default:
577  continue; // unknown
578  }
579  } catch ( exception& e ) {
580  LOG_ERROR << "Error instantiating " << name << " from " << iLib;
581  LOG_ERROR << "Got exception: " << e.what();
582  allGood = false;
583  continue;
584  } catch ( ... ) {
585  LOG_ERROR << "Error instantiating " << name << " from " << iLib;
586  allGood = false;
587  continue;
588  }
589  if ( prop ) {
590  if ( m_confTypes.contains( conf_t::CONF ) && !genComponent( lib, name, type, prop->getProperties(), info ) ) {
591  allGood = false;
592  }
593  if ( m_confTypes.contains( conf_t::CONF2 ) &&
594  !genComponent2( name, type, prop->getProperties(), prop->getInterfaceNames(), info ) ) {
595  allGood = false;
596  }
597  prop.reset();
598  } else {
599  LOG_ERROR << "could not cast IInterface* object to an IProperty* !";
600  LOG_ERROR << "NO Configurable will be generated for [" << name << "] !";
601  allGood = false;
602  }
603  } //> end loop over factories
604 
608  if ( m_confTypes.contains( conf_t::CONF ) ) {
609  const std::string pyName = ( fs::path( m_outputDirName ) / fs::path( lib + "Conf.py" ) ).string();
610  const std::string dbName = ( fs::path( m_outputDirName ) / fs::path( lib + ".confdb" ) ).string();
611 
612  std::fstream py( pyName, std::ios_base::out | std::ios_base::trunc );
613  std::fstream db( dbName, std::ios_base::out | std::ios_base::trunc );
614 
615  genHeader( py, db );
616  if ( !userModule.empty() ) py << "from " << userModule << " import *" << endl;
617  genBody( py, db );
618  genTrailer( py, db );
619  }
620  if ( m_confTypes.contains( conf_t::CONF2 ) ) {
621  const std::string db2Name = ( fs::path( m_outputDirName ) / fs::path( lib + ".confdb2_part" ) ).string();
622  std::fstream db2( db2Name, std::ios_base::out | std::ios_base::trunc );
623  db2 << "{\n" << m_db2Buf.str() << "}\n";
624  }
625 
626  } //> end loop over libraries
627 
628  dummySvc->release();
629  dummySvc = 0;
630 
631  return allGood ? EXIT_SUCCESS : EXIT_FAILURE;
632 }
633 
634 void configGenerator::genImport( std::ostream& s, std::string_view frmt, std::string indent = "" ) {
635 
636  std::string::size_type pos = 0, nxtpos = 0;
637  std::string mod;
638 
639  while ( std::string::npos != pos ) {
640  // find end of module name
641  nxtpos = m_configurable[component_t::Module].find_first_of( ',', pos );
642 
643  // Prepare import string
644  mod = m_configurable[component_t::Module].substr( pos, nxtpos - pos );
645  std::ostringstream import;
646  import << fmt::format( fmt::runtime( frmt ), mod );
647 
648  // append a normal import or a try/except enclosed one depending
649  // on availability of a fall-back module (next in the list)
650  if ( std::string::npos == nxtpos ) {
651  // last possible module
652  s << indent << import.str() << "\n" << flush;
653  pos = std::string::npos;
654  } else {
655  // we have a fallback for this
656  s << indent << "try:\n" << indent << py_tab << import.str() << "\n" << indent << "except ImportError:\n" << flush;
657  pos = nxtpos + 1;
658  }
659  // increase indentation level for next iteration
660  indent += py_tab;
661  }
662 }
663 
664 //-----------------------------------------------------------------------------
665 void configGenerator::genHeader( std::ostream& py, std::ostream& db )
666 //-----------------------------------------------------------------------------
667 {
668  // python file part
669  std::string now = Gaudi::Time::current().format( true );
670  py << "#" << now //<< "\n"
671  << "\"\"\"Automatically generated. DO NOT EDIT please\"\"\"\n";
672 
673  if ( m_importGaudiHandles ) { py << "from GaudiKernel.GaudiHandles import *\n"; }
674 
675  if ( m_importDataHandles ) { py << "from GaudiKernel.DataHandle import DataHandle\n"; }
676 
677  genImport( py, "from {}.Configurable import *" );
678 
679  // db file part
680  db << "## -*- ascii -*- \n"
681  << "# db file automatically generated by genconf on: " << now << "\n"
682  << flush;
683 }
684 //-----------------------------------------------------------------------------
685 void configGenerator::genTrailer( std::ostream& /*py*/, std::ostream& db )
686 //-----------------------------------------------------------------------------
687 {
688  // db file part
689  db << "## " << m_pkgName << "\n" << std::flush;
690 }
691 
692 //-----------------------------------------------------------------------------
693 bool configGenerator::genComponent( const std::string& libName, const std::string& componentName,
694  component_t componentType, const vector<PropertyBase*>& properties,
695  const Gaudi::PluginService::Details::Registry::FactoryInfo& info )
696 //-----------------------------------------------------------------------------
697 {
698  auto cname = pythonizeName( componentName );
699  const auto decl_loc = info.getprop( "declaration_location" );
700 
701  std::vector<std::pair<std::string, std::string>> propDoc;
702  propDoc.reserve( properties.size() );
703 
704  m_pyBuf << "\nclass " << cname << "( " << m_configurable[componentType] << " ) :\n";
705  m_pyBuf << " __slots__ = { \n";
706  for ( const auto& prop : properties ) {
707  const string& pname = prop->name();
708  // Validate property name (it must be a valid Python identifier)
709  if ( !boost::regex_match( pname, pythonIdentifier ) ) {
710  LOG_ERROR << "invalid property name \"" << pname << "\" in component " << cname << " (invalid Python identifier)"
711  << std::endl;
712  // try to make the buffer at least more or less valid python code.
713  m_pyBuf << " #ERROR-invalid identifier '" << pname << "'\n"
714  << " }\n";
715  return false;
716  }
717 
718  string pvalue, ptype;
719  pythonizeValue( prop, pvalue, ptype );
720  m_pyBuf << " '" << pname << "' : " << pvalue << ",\n";
721 
722  if ( prop->documentation() != "none" ) {
723  propDoc.emplace_back( pname, prop->documentation() + " [" + prop->ownerTypeName() + "]" );
724  }
725  }
726  m_pyBuf << " }\n";
727  m_pyBuf << " _propertyDocDct = { \n";
728  for ( const auto& prop : propDoc ) {
729  m_pyBuf << std::setw( 5 ) << "'" << prop.first << "' : "
730  << "\"\"\" " << prop.second << " \"\"\",\n";
731  }
732  m_pyBuf << " }\n";
733 
734  if ( !decl_loc.empty() ) { m_pyBuf << " __declaration_location__ = '" << decl_loc << "'\n"; }
735  m_pyBuf << " def __init__(self, name = " << m_configurable[component_t::DefaultName] << ", **kwargs):\n"
736  << " super(" << cname << ", self).__init__(name)\n"
737  << " for n,v in kwargs.items():\n"
738  << " setattr(self, n, v)\n"
739  << " def getDlls( self ):\n"
740  << " return '" << libName << "'\n"
741  << " def getType( self ):\n"
742  << " return '" << componentName << "'\n"
743  << " pass # class " << cname << "\n"
744  << flush;
745 
746  // name of the auto-generated module
747  const string pyName = ( fs::path( m_outputDirName ) / fs::path( libName + "Conf.py" ) ).string();
748  const string modName = fs::path( pyName ).filename().stem().string();
749 
750  // now the db part
751  m_dbBuf << m_pkgName << "." << modName << " " << libName << " " << cname << "\n" << flush;
752 
753  return true;
754 }
755 
756 //-----------------------------------------------------------------------------
757 bool configGenerator::genComponent2( const std::string& componentName, component_t componentType,
758  const vector<PropertyBase*>& properties, const vector<std::string>& interfaces,
759  const Gaudi::PluginService::Details::Registry::FactoryInfo& info )
760 //-----------------------------------------------------------------------------
761 {
762  m_db2Buf << " '" << componentName << "': {\n";
763  m_db2Buf << " '__component_type__': '";
764  switch ( componentType ) {
765  case component_t::Algorithm:
766  m_db2Buf << "Algorithm";
767  break;
768  case component_t::AlgTool:
769  m_db2Buf << "AlgTool";
770  break;
771  case component_t::ApplicationMgr: // FALLTROUGH
772  case component_t::Service:
773  m_db2Buf << "Service";
774  break;
775  case component_t::Auditor:
776  m_db2Buf << "Auditor";
777  break;
778  default:
779  m_db2Buf << "Unknown";
780  }
781 
782  const auto decl_loc = info.getprop( "declaration_location" );
783  if ( !decl_loc.empty() ) { m_db2Buf << "',\n '__declaration_location__': '" << decl_loc; }
784 
785  m_db2Buf << "',\n '__interfaces__': (";
786  for ( const auto& intf : std::set<std::string>{ begin( interfaces ), end( interfaces ) } ) {
787  if ( ignored_interfaces.find( intf ) == end( ignored_interfaces ) ) { m_db2Buf << '\'' << intf << "', "; }
788  }
789  m_db2Buf << "),\n 'properties': {\n";
790 
791  bool success = true;
792  for ( const auto& prop : properties ) {
793  const string& pname = prop->name();
794  // Validate property name (it must be a valid Python identifier)
795  if ( !boost::regex_match( pname, pythonIdentifier ) ) {
796  LOG_ERROR << "invalid property name \"" << pname << "\" in component " << componentName
797  << " (invalid Python identifier)" << std::endl;
798  m_db2Buf << " #ERROR-invalid identifier '" << pname << "'\n";
799  success = false;
800  break;
801  }
802 
803  string pvalue, ptype;
804  pythonizeValue( prop, pvalue, ptype );
805 
806  m_db2Buf << " '" << pname << "': ('" << ptype << "', " << pvalue << ", '''" << prop->documentation()
807  << " [" << prop->ownerTypeName() << "]'''";
808  auto sem = prop->semantics();
809  if ( !sem.empty() ) { m_db2Buf << ", '" << sem << '\''; }
810  m_db2Buf << "),\n";
811  }
812 
813  m_db2Buf << " },\n },\n";
814 
815  return success;
816 }
817 
818 //-----------------------------------------------------------------------------
819 void configGenerator::pythonizeValue( const PropertyBase* p, string& pvalue, string& ptype )
820 //-----------------------------------------------------------------------------
821 {
822  const std::string cvalue = p->toString();
823  const std::type_index ti = std::type_index( *p->type_info() );
824  ptype = System::typeinfoName( *p->type_info() );
825 
826  if ( ti == typeIndex<bool>() ) {
827  pvalue = ( cvalue == "0" || cvalue == "False" || cvalue == "false" ) ? "False" : "True";
828  } else if ( ti == typeIndex<char>() || ti == typeIndex<signed char>() || ti == typeIndex<unsigned char>() ||
829  ti == typeIndex<short>() || ti == typeIndex<unsigned short>() || ti == typeIndex<int>() ||
830  ti == typeIndex<unsigned int>() || ti == typeIndex<long>() || ti == typeIndex<unsigned long>() ||
831  ti == typeIndex<long long>() || ti == typeIndex<unsigned long long>() ) {
832  pvalue = cvalue;
833  } else if ( ti == typeIndex<float>() || ti == typeIndex<double>() ) {
834  // forces python to handle this as a float: put a dot in there...
835  pvalue = boost::to_lower_copy( cvalue );
836  if ( std::string::npos != pvalue.find( "nan" ) ) {
837  pvalue = "float('nan')";
838  } else if ( std::string::npos == pvalue.find( "." ) && std::string::npos == pvalue.find( "e" ) ) {
839  pvalue = cvalue + ".0";
840  }
841  } else if ( ti == typeIndex<string>() ) {
842  pvalue = quote( cvalue );
843  } else if ( ti == typeIndex<GaudiHandleBase>() ) {
844  const GaudiHandleProperty& hdl = dynamic_cast<const GaudiHandleProperty&>( *p );
845  const GaudiHandleBase& base = hdl.value();
846 
847  pvalue = base.pythonRepr();
848  ptype = base.pythonPropertyClassName();
849  m_importGaudiHandles = true;
850  } else if ( ti == typeIndex<GaudiHandleArrayBase>() ) {
851  const GaudiHandleArrayProperty& hdl = dynamic_cast<const GaudiHandleArrayProperty&>( *p );
852  const GaudiHandleArrayBase& base = hdl.value();
853 
854  pvalue = base.pythonRepr();
855  ptype = base.pythonPropertyClassName();
856  m_importGaudiHandles = true;
857  } else if ( auto hdl = dynamic_cast<const DataHandleProperty*>( p ); hdl ) {
858  // dynamic_cast to support also classes derived from DataHandleProperty
859  const Gaudi::DataHandle& base = hdl->value();
860 
861  pvalue = base.pythonRepr();
862  m_importDataHandles = true;
863  } else {
864  std::ostringstream v_str;
865  v_str.setf( std::ios::showpoint ); // to correctly display floats
866  p->toStream( v_str );
867  pvalue = v_str.str();
868  }
869 }
870 
871 //-----------------------------------------------------------------------------
873 //-----------------------------------------------------------------------------
874 {
876  SmartIF<IAppMgrUI> appUI( iface );
877  auto propMgr = appUI.as<IProperty>();
878  if ( !propMgr || !appUI ) return EXIT_FAILURE;
879 
880  propMgr->setProperty( "JobOptionsType", "NONE" ).ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ ); // No job
881  // options
882  propMgr->setProperty( "AppName", "" ).ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ ); // No initial printout
883  // message
884  propMgr->setProperty( "OutputLevel", 7 ).ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ ); // No other printout
885  // messages
886  appUI->configure().ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
887  auto msgSvc = SmartIF<IMessageSvc>{ iface }.as<IProperty>();
888  msgSvc->setPropertyRepr( "setWarning", "['DefaultName', 'PropertyHolder']" )
889  .ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
890  msgSvc->setProperty( "Format", "%T %0W%M" ).ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
891  return EXIT_SUCCESS;
892 }
Gaudi::Details::PropertyBase
PropertyBase base class allowing PropertyBase* collections to be "homogeneous".
Definition: PropertyBase.h:34
configGenerator::genTrailer
void genTrailer(std::ostream &pyOut, std::ostream &dbOut)
Definition: genconf.cpp:685
Gaudi::createApplicationMgr
GAUDI_API IAppMgrUI * createApplicationMgr(const std::string &dllname, const std::string &factname)
GaudiPython.Bindings.DataObject
DataObject
Definition: Bindings.py:82
GaudiHandle.h
System::loadDynamicLib
GAUDI_API unsigned long loadDynamicLib(const std::string &name, ImageHandle *handle)
Load dynamic link library.
Definition: System.cpp:115
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:221
configGenerator::setConfigurableAuditor
void setConfigurableAuditor(const std::string &cfgAuditor)
customize the configurable base class for AlgTool component
Definition: genconf.cpp:224
Gaudi.Configuration.log
log
Definition: Configuration.py:28
cpluginsvc.registry
def registry()
Definition: cpluginsvc.py:83
configGenerator::setConfigurableDefaultName
void setConfigurableDefaultName(const std::string &defaultName)
customize the default name for configurable instances
Definition: genconf.cpp:211
GaudiHandleArrayProperty::value
const GaudiHandleArrayBase & value() const
Definition: Property.h:627
configGenerator
Definition: genconf.cpp:159
AtlasMCRecoFullPrecedenceDump.path
path
Definition: AtlasMCRecoFullPrecedenceDump.py:49
GaudiPartProp.decorators.std
std
Definition: decorators.py:32
Gaudi::Details::PropertyBase::type_info
const std::type_info * type_info() const
property type-info
Definition: PropertyBase.h:44
System.h
plotBacklogPyRoot.argc
argc
Definition: plotBacklogPyRoot.py:173
configGenerator::genComponent
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:693
DataHandleProperty.h
configGenerator::genConfig
int genConfig(const Strings_t &modules, const string &userModule)
main entry point of this class:
Definition: genconf.cpp:454
gaudirun.s
string s
Definition: gaudirun.py:346
System::getEnv
GAUDI_API std::string getEnv(const char *var)
get a particular environment variable (returning "UNKNOWN" if not set)
Definition: System.cpp:329
SmartIF::reset
void reset(TYPE *ptr=nullptr)
Set the internal pointer to the passed one disposing of the old one.
Definition: SmartIF.h:88
ISvcLocator
Definition: ISvcLocator.h:42
DataHandleProperty
DataHandleProperty.h GaudiKernel/DataHandleProperty.h.
Definition: DataHandleProperty.h:34
Algorithm
Alias for backward compatibility.
Definition: Algorithm.h:58
GaudiPartProp.decorators.get
get
decorate the vector of properties
Definition: decorators.py:283
IConverter
Definition: IConverter.h:65
configGenerator::m_confTypes
std::set< conf_t > m_confTypes
Types of configurables to generate.
Definition: genconf.cpp:176
GaudiMP.FdsRegistry.msg
msg
Definition: FdsRegistry.py:19
Gaudi::DataHandle
Definition: DataHandle.h:37
createAppMgr
int createAppMgr()
Definition: genconf.cpp:872
configGenerator::setConfigurableModule
void setConfigurableModule(const std::string &moduleName)
customize the Module name where configurable base classes are defined
Definition: genconf.cpp:208
System::ImageHandle
void * ImageHandle
Definition of an image handle.
Definition: ModuleInfo.h:25
conf.release
string release
Definition: conf.py:27
gaudirun.c
c
Definition: gaudirun.py:525
ProduceConsume.types
types
Definition: ProduceConsume.py:59
System::typeinfoName
GAUDI_API const std::string typeinfoName(const std::type_info &)
Get platform independent information about the class type.
Definition: System.cpp:260
IInterface::addRef
virtual unsigned long addRef() const =0
Increment the reference count of Interface instance.
Gaudi::Details::PropertyBase::toStream
virtual void toStream(std::ostream &out) const =0
value -> stream
IAppMgrUI.h
HashMap.h
configGenerator::m_dbBuf
stringstream m_dbBuf
buffer of generated configurables informations for the "Db" file The "Db" file is holding information...
Definition: genconf.cpp:182
AvalancheSchedulerErrorTest.msgSvc
msgSvc
Definition: AvalancheSchedulerErrorTest.py:80
GaudiHandleBase
Definition: GaudiHandle.h:102
configGenerator::m_pyBuf
stringstream m_pyBuf
buffer of auto-generated configurables
Definition: genconf.cpp:168
prepareBenchmark.config
config
Definition: prepareBenchmark.py:43
IProperty
Definition: IProperty.h:32
Gaudi.CommonGaudiConfigurables.mod
mod
Definition: CommonGaudiConfigurables.py:39
Gaudi::svcLocator
GAUDI_API ISvcLocator * svcLocator()
main
int main(int argc, char **argv)
Definition: genconf.cpp:268
SmartIF.h
PluginService.h
Gaudi::Utils::begin
AttribStringParser::Iterator begin(const AttribStringParser &parser)
Definition: AttribStringParser.h:135
Gaudi::Time::format
std::string format(bool local, std::string spec="%c") const
Format the time using strftime.
Definition: Time.cpp:157
Converter
Definition: Converter.h:33
configGenerator::genComponent2
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:757
Gaudi::Parsers::operator<<
std::ostream & operator<<(std::ostream &o, const Catalog &c)
printout operator
Definition: Catalog.h:49
LibPathNames_t
std::vector< fs::path > LibPathNames_t
Definition: genconf.cpp:76
IAlgTool.h
IAuditor.h
LOG_ERROR
#define LOG_ERROR
Definition: genconf.cpp:65
configGenerator::configGenerator
configGenerator(const string &pkgName, const string &outputDirName)
Definition: genconf.cpp:195
cpluginsvc.factories
def factories()
Definition: cpluginsvc.py:93
Algorithm.h
SmartIF< IProperty >
format
GAUDI_API std::string format(const char *,...)
MsgStream format utility "a la sprintf(...)".
Definition: MsgStream.cpp:93
GaudiHandleProperty::value
const GaudiHandleBase & value() const
Definition: Property.h:590
System::isEnvSet
GAUDI_API bool isEnvSet(const char *var)
Check if an environment variable is set or not.
Definition: System.cpp:349
configGenerator::m_pkgName
string m_pkgName
name of the package we are processing
Definition: genconf.cpp:161
gaudirun.level
level
Definition: gaudirun.py:364
configGenerator::genImport
void genImport(std::ostream &s, std::string_view frmt, std::string indent)
Definition: genconf.cpp:634
configGenerator::m_configurable
std::map< component_t, std::string > m_configurable
Configurable customization.
Definition: genconf.cpp:192
System::moduleName
GAUDI_API const std::string & moduleName()
Get the name of the (executable/DLL) file without file-type.
Definition: ModuleInfo.cpp:28
GaudiHandleArrayBase
Base class of array's of various gaudihandles.
Definition: GaudiHandle.h:334
GaudiHandleProperty
Definition: Property.h:569
Gaudi::PluginService::v1::SetDebug
GAUDIPS_API void SetDebug(int debugLevel)
Backward compatibility with Reflex.
Definition: PluginServiceV1.cpp:314
gaudiComponentHelp.properties
properties
Definition: gaudiComponentHelp.py:68
StatusCode::ignore
const StatusCode & ignore() const
Allow discarding a StatusCode without warning.
Definition: StatusCode.h:139
Service.h
SmartIF::as
SmartIF< IFace > as() const
return a new SmartIF instance to another interface
Definition: SmartIF.h:110
LOG_WARNING
#define LOG_WARNING
Definition: genconf.cpp:66
Gaudi::Utils::toString
std::string toString(const TYPE &obj)
the generic implementation of the type conversion to the string
Definition: ToStream.h:326
gaudirun.type
type
Definition: gaudirun.py:160
init_logging
void init_logging(boost::log::trivial::severity_level level)
Definition: genconf.cpp:255
Gaudi::PluginService::v1::Details::logger
GAUDIPS_API Logger & logger()
Return the current logger instance.
Definition: PluginServiceV1.cpp:309
ConditionsStallTest.name
name
Definition: ConditionsStallTest.py:77
configGenerator::genHeader
void genHeader(std::ostream &pyOut, std::ostream &dbOut)
Definition: genconf.cpp:665
LOG_INFO
#define LOG_INFO
Definition: genconf.cpp:67
AlgTool
Definition: AlgTool.h:55
configGenerator::setConfigurableTypes
void setConfigurableTypes(const std::set< conf_t > &types)
customize configurable types to generate
Definition: genconf.cpp:205
Gaudi::Details::PropertyBase::toString
virtual std::string toString() const =0
value -> string
Time.h
Gaudi::Time::current
static Time current()
Returns the current time.
Definition: Time.cpp:43
IInterface
Definition: IInterface.h:225
configGenerator::m_outputDirName
string m_outputDirName
absolute path to the directory where genconf will store auto-generated files (Configurables and Confi...
Definition: genconf.cpp:165
Bootstrap.h
DataHandle.h
configGenerator::setConfigurableService
void setConfigurableService(const std::string &cfgService)
customize the configurable base class for Service component
Definition: genconf.cpp:227
compareOutputFiles.pname
pname
Definition: compareOutputFiles.py:482
AlgTool.h
Strings_t
std::vector< std::string > Strings_t
Definition: genconf.cpp:72
IProperty.h
configGenerator::m_db2Buf
stringstream m_db2Buf
buffer of generated GaudiConfig2 configurables
Definition: genconf.cpp:185
check_ParticleID.base
base
Definition: check_ParticleID.py:24
IOTest.end
end
Definition: IOTest.py:125
configGenerator::setConfigurableAlgorithm
void setConfigurableAlgorithm(const std::string &cfgAlgorithm)
customize the configurable base class for Algorithm component
Definition: genconf.cpp:216
gaudirun.options
options
Definition: gaudirun.py:313
IAlgorithm.h
ISvcLocator.h
configGenerator::pythonizeValue
void pythonizeValue(const PropertyBase *prop, string &pvalue, string &ptype)
handle the "marshalling" of Properties
Definition: genconf.cpp:819
System::getLastErrorString
GAUDI_API const std::string getLastErrorString()
Get last system error as string.
Definition: System.cpp:234
configGenerator::genBody
void genBody(std::ostream &pyOut, std::ostream &dbOut)
Definition: genconf.cpp:243
GaudiHandleArrayProperty
Definition: Property.h:606
IInterface::release
virtual unsigned long release() const =0
Release Interface instance.
gaudirun.argv
list argv
Definition: gaudirun.py:327
Gaudi::Functional::details::out
OptOut && out
Definition: details.h:179
Auditor.h
IProperty::setProperty
StatusCode setProperty(const Gaudi::Details::PropertyBase &p)
Set the property from a property.
Definition: IProperty.h:38