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