The Gaudi Framework  v33r2 (a6f0ec87)
genconf.cpp
Go to the documentation of this file.
1 /***********************************************************************************\
2 * (c) Copyright 1998-2019 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>
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 #include <exception>
63 #include <fmt/format.h>
64 #include <fstream>
65 #include <iostream>
66 #include <set>
67 #include <sstream>
68 #include <type_traits>
69 #include <vector>
70 
71 namespace po = boost::program_options;
72 namespace fs = boost::filesystem;
73 
74 #define LOG_ERROR BOOST_LOG_TRIVIAL( error )
75 #define LOG_WARNING BOOST_LOG_TRIVIAL( warning )
76 #define LOG_INFO BOOST_LOG_TRIVIAL( info )
77 #define LOG_DEBUG BOOST_LOG_TRIVIAL( debug )
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  const std::map<std::string, component_t> allowedFactories{
118  {typeid( Gaudi::Algorithm::Factory::FactoryType ).name(), component_t::Algorithm},
119  {typeid( Service::Factory::FactoryType ).name(), component_t::Service},
120  {typeid( AlgTool::Factory::FactoryType ).name(), component_t::AlgTool},
121  {typeid( Auditor::Factory::FactoryType ).name(), component_t::Auditor},
122  };
123 
125  static const std::array<std::string, 11> names = {"Module", "DefaultName", "Algorithm", "AlgTool",
126  "Auditor", "Service", "ApplicationMgr", "IInterface",
127  "Converter", "DataObject", "Unknown"};
128  return names.at( static_cast<std::underlying_type_t<component_t>>( type ) );
129  }
130  std::ostream& operator<<( std::ostream& os, component_t type ) { return os << toString( type ); }
131 
132  std::set<std::string> ignored_interfaces{
133  {"IInterface", "IProperty", "INamedInterface", "IAlgorithm", "IAlgTool", "IService", "IAuditor"}};
134 
135  //-----------------------------------------------------------------------------
137  std::string pythonizeName( const std::string& name ) {
138  static const string in( "<>&*,: ()." );
139  static const string out( "__rp__s___" );
140  auto r = boost::algorithm::replace_all_copy( name, ", ", "," );
141  for ( auto& c : r ) {
142  auto rep = in.find( c );
143  if ( rep != string::npos ) c = out[rep];
144  }
145  return r;
146  }
147  //-----------------------------------------------------------------------------
148  template <typename T>
149  std::type_index typeIndex() {
150  return std::type_index{typeid( T )};
151  }
152  //-----------------------------------------------------------------------------
153  inline std::string libNativeName( const std::string& libName ) {
154 #if defined( _WIN32 )
155  return libName + ".dll";
156 #elif defined( __linux ) || defined( __APPLE__ )
157  return "lib" + libName + ".so";
158 #else
159  // variant of the GIGO design pattern
160  return libName;
161 #endif
162  }
163 } // namespace
164 
167  string m_pkgName;
168 
172 
175 
178  bool m_importGaudiHandles = false;
179  bool m_importDataObjectHandles = false;
180 
186 
188 
195 
196 public:
197  configGenerator( const string& pkgName, const string& outputDirName )
198  : m_pkgName( pkgName ), m_outputDirName( outputDirName ) {}
199 
204  int genConfig( const Strings_t& modules, const string& userModule );
205 
207  void setConfigurableModule( const std::string& moduleName ) { m_configurable[component_t::Module] = moduleName; }
208 
210  void setConfigurableDefaultName( const std::string& defaultName ) {
211  m_configurable[component_t::DefaultName] = defaultName;
212  }
213 
215  void setConfigurableAlgorithm( const std::string& cfgAlgorithm ) {
216  m_configurable[component_t::Algorithm] = cfgAlgorithm;
217  }
218 
220  void setConfigurableAlgTool( const std::string& cfgAlgTool ) { m_configurable[component_t::AlgTool] = cfgAlgTool; }
221 
223  void setConfigurableAuditor( const std::string& cfgAuditor ) { m_configurable[component_t::Auditor] = cfgAuditor; }
224 
226  void setConfigurableService( const std::string& cfgService ) {
227  m_configurable[component_t::Service] = cfgService;
228  m_configurable[component_t::ApplicationMgr] = cfgService;
229  }
230 
231 private:
232  bool genComponent( const std::string& libName, const std::string& componentName, component_t componentType,
233  const vector<PropertyBase*>& properties, const std::vector<std::string>& interfaces );
234  void genImport( std::ostream& s, std::string_view frmt, std::string indent );
235  void genHeader( std::ostream& pyOut, std::ostream& dbOut );
236  void genBody( std::ostream& pyOut, std::ostream& dbOut ) {
237  pyOut << m_pyBuf.str() << flush;
238  dbOut << m_dbBuf.str() << flush;
239  }
240  void genTrailer( std::ostream& pyOut, std::ostream& dbOut );
241 
243  void pythonizeValue( const PropertyBase* prop, string& pvalue, string& ptype, string& ptype2 );
244 };
245 
246 int createAppMgr();
247 
248 void init_logging( boost::log::trivial::severity_level level ) {
249  namespace logging = boost::log;
250  namespace keywords = boost::log::keywords;
251  namespace expr = boost::log::expressions;
252 
253  logging::add_console_log( std::cout, keywords::format =
254  ( expr::stream << "[" << std::setw( 7 ) << std::left
255  << logging::trivial::severity << "] " << expr::smessage ) );
256 
257  logging::core::get()->set_filter( logging::trivial::severity >= level );
258 }
259 
260 //--- Command main program-----------------------------------------------------
261 int main( int argc, char** argv )
262 //-----------------------------------------------------------------------------
263 {
264  init_logging( ( System::isEnvSet( "VERBOSE" ) && !System::getEnv( "VERBOSE" ).empty() )
265  ? boost::log::trivial::info
266  : boost::log::trivial::warning );
267 
268  fs::path pwd = fs::initial_path();
269  fs::path out;
270  Strings_t libs;
271  std::string pkgName;
272  std::string userModule;
273 
274  // declare a group of options that will be allowed only on command line
275  po::options_description generic( "Generic options" );
276  generic.add_options()( "help,h", "produce this help message" )(
277  "package-name,p", po::value<string>(), "name of the package for which we create the configurables file" )(
278  "input-libraries,i", po::value<string>(), "libraries to extract the component configurables from" )(
279  "input-cfg,c", po::value<string>(),
280  "path to the cfg file holding the description of the Configurable base "
281  "classes, the python module holding the Configurable definitions, etc..." )(
282  "output-dir,o", po::value<string>()->default_value( "../genConf" ),
283  "output directory for genconf files." )( "debug-level,d", po::value<int>()->default_value( 0 ), "debug level" )(
284  "load-library,l", po::value<Strings_t>()->composing(), "preloading library" )(
285  "user-module,m", po::value<string>(), "user-defined module to be imported by the genConf-generated one" )(
286  "no-init", "do not generate the (empty) __init__.py" );
287 
288  // declare a group of options that will be allowed both on command line
289  // _and_ in configuration file
290  po::options_description config( "Configuration" );
291  config.add_options()( "configurable-module", po::value<string>()->default_value( "AthenaCommon" ),
292  "Name of the module holding the configurable classes" )(
293  "configurable-default-name", po::value<string>()->default_value( "Configurable.DefaultName" ),
294  "Default name for the configurable instance" )( "configurable-algorithm",
295  po::value<string>()->default_value( "ConfigurableAlgorithm" ),
296  "Name of the configurable base class for Algorithm components" )(
297  "configurable-algtool", po::value<string>()->default_value( "ConfigurableAlgTool" ),
298  "Name of the configurable base class for AlgTool components" )(
299  "configurable-auditor", po::value<string>()->default_value( "ConfigurableAuditor" ),
300  "Name of the configurable base class for Auditor components" )(
301  "configurable-service", po::value<string>()->default_value( "ConfigurableService" ),
302  "Name of the configurable base class for Service components" );
303 
304  po::options_description cmdline_options;
305  cmdline_options.add( generic ).add( config );
306 
307  po::options_description config_file_options;
308  config_file_options.add( config );
309 
310  po::options_description visible( "Allowed options" );
311  visible.add( generic ).add( config );
312 
313  po::variables_map vm;
314 
315  try {
316  po::store( po::command_line_parser( argc, argv ).options( cmdline_options ).run(), vm );
317 
318  po::notify( vm );
319 
320  // try to read configuration from the optionally given configuration file
321  if ( vm.count( "input-cfg" ) ) {
322  string cfgFileName = vm["input-cfg"].as<string>();
323  cfgFileName = fs::system_complete( fs::path( cfgFileName ) ).string();
324  std::ifstream ifs( cfgFileName );
325  po::store( parse_config_file( ifs, config_file_options ), vm );
326  }
327 
328  po::notify( vm );
329  } catch ( po::error& err ) {
330  LOG_ERROR << "error detected while parsing command options: " << err.what();
331  return EXIT_FAILURE;
332  }
333 
334  //--- Process command options -----------------------------------------------
335  if ( vm.count( "help" ) ) {
336  cout << visible << endl;
337  return EXIT_FAILURE;
338  }
339 
340  if ( vm.count( "package-name" ) ) {
341  pkgName = vm["package-name"].as<string>();
342  } else {
343  LOG_ERROR << "'package-name' required";
344  cout << visible << endl;
345  return EXIT_FAILURE;
346  }
347 
348  if ( vm.count( "user-module" ) ) {
349  userModule = vm["user-module"].as<string>();
350  LOG_INFO << "INFO: will import user module " << userModule;
351  }
352 
353  if ( vm.count( "input-libraries" ) ) {
354  // re-shape the input arguments:
355  // - removes spurious spaces,
356  // - split into tokens.
357  Strings_t inputLibs;
358  {
359  std::string tmp = vm["input-libraries"].as<std::string>();
360  boost::trim( tmp );
361  boost::split( inputLibs, tmp, boost::is_any_of( " " ), boost::token_compress_on );
362  }
363 
364  //
365  libs.reserve( inputLibs.size() );
366  for ( const auto& iLib : inputLibs ) {
367  std::string lib = fs::path( iLib ).stem().string();
368  if ( lib.compare( 0, 3, "lib" ) == 0 ) {
369  lib = lib.substr( 3 ); // For *NIX remove "lib"
370  }
371  // remove duplicates
372  if ( !lib.empty() && std::find( libs.begin(), libs.end(), lib ) == libs.end() ) { libs.push_back( lib ); }
373  } //> end loop over input-libraries
374  if ( libs.empty() ) {
375  LOG_ERROR << "input component library(ies) required !\n";
376  LOG_ERROR << "'input-libraries' argument was [" << vm["input-libraries"].as<string>() << "]";
377  return EXIT_FAILURE;
378  }
379  } else {
380  LOG_ERROR << "input component library(ies) required";
381  cout << visible << endl;
382  return EXIT_FAILURE;
383  }
384 
385  if ( vm.count( "output-dir" ) ) { out = fs::system_complete( fs::path( vm["output-dir"].as<string>() ) ); }
386 
387  if ( vm.count( "debug-level" ) ) { Gaudi::PluginService::SetDebug( vm["debug-level"].as<int>() ); }
388 
389  if ( vm.count( "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  if ( !fs::exists( out ) ) {
399  try {
400  fs::create_directory( out );
401  } catch ( fs::filesystem_error& err ) {
402  LOG_ERROR << "error creating directory: " << err.what();
403  return EXIT_FAILURE;
404  }
405  }
406 
407  {
409  msg << ":::::: libraries : [ ";
410  std::copy( libs.begin(), libs.end(), std::ostream_iterator<std::string>( msg, " " ) );
411  msg << "] ::::::";
412  LOG_INFO << msg.str();
413  }
414 
415  configGenerator py( pkgName, out.string() );
416  py.setConfigurableModule( vm["configurable-module"].as<string>() );
417  py.setConfigurableDefaultName( vm["configurable-default-name"].as<string>() );
418  py.setConfigurableAlgorithm( vm["configurable-algorithm"].as<string>() );
419  py.setConfigurableAlgTool( vm["configurable-algtool"].as<string>() );
420  py.setConfigurableAuditor( vm["configurable-auditor"].as<string>() );
421  py.setConfigurableService( vm["configurable-service"].as<string>() );
422 
423  int sc = EXIT_FAILURE;
424  try {
425  sc = py.genConfig( libs, userModule );
426  } catch ( exception& e ) {
427  cout << "ERROR: Could not generate Configurable(s) !\n"
428  << "ERROR: Got exception: " << e.what() << endl;
429  return EXIT_FAILURE;
430  }
431 
432  if ( EXIT_SUCCESS == sc && !vm.count( "no-init" ) ) {
433  // create an empty __init__.py file in the output dir
434  std::fstream initPy( ( out / fs::path( "__init__.py" ) ).string(), std::ios_base::out | std::ios_base::trunc );
435  initPy << "## Hook for " << pkgName << " genConf module\n" << flush;
436  }
437 
438  {
440  msg << ":::::: libraries : [ ";
441  std::copy( libs.begin(), libs.end(), std::ostream_iterator<std::string>( msg, " " ) );
442  msg << "] :::::: [DONE]";
443  LOG_INFO << msg.str();
444  }
445  return sc;
446 }
447 
448 //-----------------------------------------------------------------------------
449 int configGenerator::genConfig( const Strings_t& libs, const string& userModule )
450 //-----------------------------------------------------------------------------
451 {
452  //--- Disable checking StatusCode -------------------------------------------
454 
455  const auto endLib = libs.end();
456 
457  static const std::string gaudiSvc = "GaudiCoreSvc";
458  const bool isGaudiSvc = ( std::find( libs.begin(), endLib, gaudiSvc ) != endLib );
459 
460  //--- Instantiate ApplicationMgr --------------------------------------------
461  if ( !isGaudiSvc && createAppMgr() ) {
462  cout << "ERROR: ApplicationMgr can not be created. Check environment" << endl;
463  return EXIT_FAILURE;
464  }
465 
466  //--- Iterate over component factories --------------------------------------
467  using Gaudi::PluginService::Details::Registry;
468  const Registry& registry = Registry::instance();
469 
470  auto bkgNames = registry.loadedFactoryNames();
471 
472  ISvcLocator* svcLoc = Gaudi::svcLocator();
473  IInterface* dummySvc = new Service( "DummySvc", svcLoc );
474  dummySvc->addRef();
475 
476  bool allGood = true;
477 
478  // iterate over all the requested libraries
479  for ( const auto& iLib : libs ) {
480 
481  LOG_INFO << ":::: processing library: " << iLib << "...";
482 
483  // reset state
484  m_importGaudiHandles = false;
485  m_importDataObjectHandles = false;
486  m_pyBuf.str( "" );
487  m_dbBuf.str( "" );
488  m_db2Buf.str( "" );
489 
490  //--- Load component library ----------------------------------------------
491  System::ImageHandle handle;
492  unsigned long err = System::loadDynamicLib( iLib, &handle );
493  if ( err != 1 ) {
495  allGood = false;
496  continue;
497  }
498 
499  const auto& factories = registry.factories();
500  for ( const auto& factoryName : registry.loadedFactoryNames() ) {
501  if ( bkgNames.find( factoryName ) != bkgNames.end() ) {
503  LOG_INFO << "\t==> skipping [" << factoryName << "]...";
504  }
505  continue;
506  }
507  auto entry = factories.find( factoryName );
508  if ( entry == end( factories ) ) {
509  LOG_ERROR << "inconsistency in component factories list: I cannot find anymore " << factoryName;
510  continue;
511  }
512  const auto& info = entry->second;
513  if ( !info.is_set() ) continue;
514 
515  // do not generate configurables for the Reflex-compatible aliases
516  if ( !info.getprop( "ReflexName" ).empty() ) continue;
517 
518  // Atlas contributed code (patch #1247)
519  // Skip the generation of configurables if the component does not come
520  // from the same library we are processing (i.e. we found a symbol that
521  // is coming from a library loaded by the linker).
522  if ( libNativeName( iLib ) != info.library ) {
523  LOG_WARNING << "library [" << iLib << "] exposes factory [" << factoryName << "] which is declared in ["
524  << info.library << "] !!";
525  continue;
526  }
527 
528  component_t type = component_t::Unknown;
529  {
530  const auto ft = allowedFactories.find( info.factory.type().name() );
531  if ( ft != allowedFactories.end() ) {
532  type = ft->second;
533  } else if ( factoryName == "ApplicationMgr" ) {
534  type = component_t::ApplicationMgr;
535  } else
536  continue;
537  }
538 
539  // handle possible problems with templated components
540  std::string name = boost::trim_copy( factoryName );
541 
542  const auto className = info.getprop( "ClassName" );
543  LOG_INFO << " - component: " << className << " (" << ( className != name ? ( name + ": " ) : std::string() )
544  << type << ")";
545 
546  string cname = "DefaultName";
547  SmartIF<IProperty> prop;
548  try {
549  switch ( type ) {
550  case component_t::Algorithm:
551  prop = SmartIF<IAlgorithm>( Gaudi::Algorithm::Factory::create( factoryName, cname, svcLoc ).release() );
552  break;
553  case component_t::Service:
554  prop = SmartIF<IService>( Service::Factory::create( factoryName, cname, svcLoc ).release() );
555  break;
556  case component_t::AlgTool:
557  prop =
558  SmartIF<IAlgTool>( AlgTool::Factory::create( factoryName, cname, toString( type ), dummySvc ).release() );
559  // FIXME: AlgTool base class increase artificially by 1 the refcount.
560  prop->release();
561  break;
562  case component_t::Auditor:
563  prop = SmartIF<IAuditor>( Auditor::Factory::create( factoryName, cname, svcLoc ).release() );
564  break;
565  case component_t::ApplicationMgr:
566  prop = SmartIF<ISvcLocator>( svcLoc );
567  break;
568  default:
569  continue; // unknown
570  }
571  } catch ( exception& e ) {
572  LOG_ERROR << "Error instantiating " << name << " from " << iLib;
573  LOG_ERROR << "Got exception: " << e.what();
574  allGood = false;
575  continue;
576  } catch ( ... ) {
577  LOG_ERROR << "Error instantiating " << name << " from " << iLib;
578  allGood = false;
579  continue;
580  }
581  if ( prop ) {
582  if ( !genComponent( iLib, name, type, prop->getProperties(), prop->getInterfaceNames() ) ) { allGood = false; }
583  prop.reset();
584  } else {
585  LOG_ERROR << "could not cast IInterface* object to an IProperty* !";
586  LOG_ERROR << "NO Configurable will be generated for [" << name << "] !";
587  allGood = false;
588  }
589  } //> end loop over factories
590 
594  const std::string pyName = ( fs::path( m_outputDirName ) / fs::path( iLib + "Conf.py" ) ).string();
595  const std::string dbName = ( fs::path( m_outputDirName ) / fs::path( iLib + ".confdb" ) ).string();
596 
597  std::fstream py( pyName, std::ios_base::out | std::ios_base::trunc );
598  std::fstream db( dbName, std::ios_base::out | std::ios_base::trunc );
599 
600  genHeader( py, db );
601  if ( !userModule.empty() ) py << "from " << userModule << " import *" << endl;
602  genBody( py, db );
603  genTrailer( py, db );
604 
605  {
606  const std::string db2Name = ( fs::path( m_outputDirName ) / fs::path( iLib + ".confdb2_part" ) ).string();
607  std::fstream db2( db2Name, std::ios_base::out | std::ios_base::trunc );
608  db2 << "{\n" << m_db2Buf.str() << "}\n";
609  }
610 
611  } //> end loop over libraries
612 
613  dummySvc->release();
614  dummySvc = 0;
615 
616  return allGood ? EXIT_SUCCESS : EXIT_FAILURE;
617 }
618 
619 void configGenerator::genImport( std::ostream& s, std::string_view frmt, std::string indent = "" ) {
620 
621  std::string::size_type pos = 0, nxtpos = 0;
623 
624  while ( std::string::npos != pos ) {
625  // find end of module name
626  nxtpos = m_configurable[component_t::Module].find_first_of( ',', pos );
627 
628  // Prepare import string
629  mod = m_configurable[component_t::Module].substr( pos, nxtpos - pos );
630  std::ostringstream import;
631  import << fmt::format( frmt, mod );
632 
633  // append a normal import or a try/except enclosed one depending
634  // on availability of a fall-back module (next in the list)
635  if ( std::string::npos == nxtpos ) {
636  // last possible module
637  s << indent << import.str() << "\n" << flush;
638  pos = std::string::npos;
639  } else {
640  // we have a fallback for this
641  s << indent << "try:\n" << indent << py_tab << import.str() << "\n" << indent << "except ImportError:\n" << flush;
642  pos = nxtpos + 1;
643  }
644  // increase indentation level for next iteration
645  indent += py_tab;
646  }
647 }
648 
649 //-----------------------------------------------------------------------------
651 //-----------------------------------------------------------------------------
652 {
653  // python file part
654  std::string now = Gaudi::Time::current().format( true );
655  py << "#" << now //<< "\n"
656  << "\"\"\"Automatically generated. DO NOT EDIT please\"\"\"\n"
657  << "import sys\n"
658  << "if sys.version_info >= (3,):\n"
659  << " # Python 2 compatibility\n"
660  << " long = int\n";
661 
662  if ( m_importGaudiHandles ) { py << "from GaudiKernel.GaudiHandles import *\n"; }
663 
664  if ( m_importDataObjectHandles ) { py << "from GaudiKernel.DataObjectHandleBase import DataObjectHandleBase\n"; }
665 
666  genImport( py, "from {}.Configurable import *" );
667 
668  // db file part
669  db << "## -*- ascii -*- \n"
670  << "# db file automatically generated by genconf on: " << now << "\n"
671  << flush;
672 }
673 //-----------------------------------------------------------------------------
675 //-----------------------------------------------------------------------------
676 {
677  // db file part
678  db << "## " << m_pkgName << "\n" << std::flush;
679 }
680 
681 //-----------------------------------------------------------------------------
682 bool configGenerator::genComponent( const std::string& libName, const std::string& componentName,
683  component_t componentType, const vector<PropertyBase*>& properties,
684  const vector<std::string>& interfaces )
685 //-----------------------------------------------------------------------------
686 {
687  auto cname = pythonizeName( componentName );
688 
690  propDoc.reserve( properties.size() );
691 
692  m_db2Buf << " '" << componentName << "': {\n";
693  m_db2Buf << " '__component_type__': '";
694  switch ( componentType ) {
695  case component_t::Algorithm:
696  m_db2Buf << "Algorithm";
697  break;
698  case component_t::AlgTool:
699  m_db2Buf << "AlgTool";
700  break;
701  case component_t::ApplicationMgr: // FALLTROUGH
702  case component_t::Service:
703  m_db2Buf << "Service";
704  break;
705  case component_t::Auditor:
706  m_db2Buf << "Auditor";
707  break;
708  default:
709  m_db2Buf << "Unknown";
710  }
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  m_pyBuf << " def __init__(self, name = " << m_configurable[component_t::DefaultName] << ", **kwargs):\n"
754  << " super(" << cname << ", self).__init__(name)\n"
755  << " for n,v in kwargs.items():\n"
756  << " setattr(self, n, v)\n"
757  << " def getDlls( self ):\n"
758  << " return '" << libName << "'\n"
759  << " def getType( self ):\n"
760  << " return '" << componentName << "'\n"
761  << " pass # class " << cname << "\n"
762  << flush;
763 
764  // name of the auto-generated module
765  const string pyName = ( fs::path( m_outputDirName ) / fs::path( libName + "Conf.py" ) ).string();
766  const string modName = fs::basename( fs::path( pyName ).leaf() );
767 
768  m_db2Buf << " },\n },\n";
769 
770  // now the db part
771  m_dbBuf << m_pkgName << "." << modName << " " << libName << " " << cname << "\n" << flush;
772 
773  return true;
774 }
775 
776 //-----------------------------------------------------------------------------
777 void configGenerator::pythonizeValue( const PropertyBase* p, string& pvalue, string& ptype, string& ptype2 )
778 //-----------------------------------------------------------------------------
779 {
780  const std::string cvalue = p->toString();
781  const std::type_index ti = std::type_index( *p->type_info() );
782  ptype2 = System::typeinfoName( *p->type_info() );
783 
784  if ( ti == typeIndex<bool>() ) {
785  pvalue = ( cvalue == "0" || cvalue == "False" || cvalue == "false" ) ? "False" : "True";
786  ptype = "bool";
787  } else if ( ti == typeIndex<char>() || ti == typeIndex<signed char>() || ti == typeIndex<unsigned char>() ||
788  ti == typeIndex<short>() || ti == typeIndex<unsigned short>() || ti == typeIndex<int>() ||
789  ti == typeIndex<unsigned int>() || ti == typeIndex<long>() || ti == typeIndex<unsigned long>() ||
790  ti == typeIndex<long long>() || ti == typeIndex<unsigned long long>() ) {
791  pvalue = cvalue;
792  ptype = "int";
793  } else if ( ti == typeIndex<float>() || ti == typeIndex<double>() ) {
794  // forces python to handle this as a float: put a dot in there...
795  pvalue = boost::to_lower_copy( cvalue );
796  if ( std::string::npos != pvalue.find( "nan" ) ) {
797  pvalue = "float('nan')";
798  std::cout << "WARNING: default value for [" << p->name() << "] is NaN !!" << std::endl;
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 ( ti == typeIndex<DataObjectHandleBase>() ) {
823  const DataObjectHandleProperty& hdl = dynamic_cast<const DataObjectHandleProperty&>( *p );
824  const DataObjectHandleBase& base = hdl.value();
825 
826  pvalue = base.pythonRepr();
827  ptype = "DataObjectHandleBase";
828  m_importDataObjectHandles = 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
852  // printout
853  // messages
854  appUI->configure().ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
855  auto msgSvc = SmartIF<IMessageSvc>{iface}.as<IProperty>();
856  msgSvc->setProperty( "setWarning", "['DefaultName', 'PropertyHolder']" )
857  .ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
858  msgSvc->setProperty( "Format", "%T %0W%M" ).ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
859  return EXIT_SUCCESS;
860 }
GAUDI_API std::string getEnv(const char *var)
get a particular environment variable (returning "UNKNOWN" if not set)
Definition: System.cpp:379
virtual std::vector< std::string > getInterfaceNames() const =0
Returns a vector of strings containing the names of all the implemented interfaces.
int genConfig(const Strings_t &modules, const string &userModule)
main entry point of this class:
Definition: genconf.cpp:449
T setf(T... args)
T empty(T... args)
T copy(T... args)
The ISvcLocator is the interface implemented by the Service Factory in the Application Manager to loc...
Definition: ISvcLocator.h:35
The data converters are responsible to translate data from one representation into another.
Definition: IConverter.h:68
GAUDI_API std::string format(const char *,...)
MsgStream format utility "a la sprintf(...)".
Definition: MsgStream.cpp:119
component_t
Definition: genconf.cpp:103
const GaudiHandleArrayBase & value() const
Definition: Property.h:935
std::vector< std::string > Strings_t
Definition: genconf.cpp:82
GAUDI_API const std::string typeinfoName(const std::type_info &)
Get platform independent information about the class type.
Definition: System.cpp:308
list argv
Definition: gaudirun.py:310
std::string pythonRepr() const override
std::string toString(const TYPE &obj)
the generic implementation of the type conversion to the string
Definition: ToStream.h:341
#define LOG_ERROR
Definition: genconf.cpp:74
std::string pythonPropertyClassName() const override
Name of the componentType with "Handle" appended.
Definition: GaudiHandle.cpp:50
T endl(T... args)
static Time current()
Returns the current time.
Definition: Time.cpp:119
T left(T... args)
virtual void toStream(std::ostream &out) const =0
value -> stream
void pythonizeValue(const PropertyBase *prop, string &pvalue, string &ptype, string &ptype2)
handle the "marshalling" of Properties
Definition: genconf.cpp:777
SmartIF< IFace > as() const
return a new SmartIF instance to another interface
Definition: SmartIF.h:117
void setConfigurableDefaultName(const std::string &defaultName)
customize the default name for configurable instances
Definition: genconf.cpp:210
STL namespace.
std::vector< fs::path > LibPathNames_t
Definition: genconf.cpp:86
void setConfigurableAlgTool(const std::string &cfgAlgTool)
customize the configurable base class for AlgTool component
Definition: genconf.cpp:220
T end(T... args)
const std::string name() const
property name
Definition: Property.h:46
auto get(const Handle &handle, const Algo &, const EventContext &) -> decltype(details::deref(handle.get()))
void * ImageHandle
Definition of an image handle.
Definition: ModuleInfo.h:40
std::string pythonRepr() const override
Python representation of handle, i.e.
Definition: GaudiHandle.cpp:58
bool genComponent(const std::string &libName, const std::string &componentName, component_t componentType, const vector< PropertyBase * > &properties, const std::vector< std::string > &interfaces)
Definition: genconf.cpp:682
STL class.
stringstream m_pyBuf
buffer of auto-generated configurables
Definition: genconf.cpp:174
T setw(T... args)
DataObjectHandleProperty.h GaudiKernel/DataObjectHandleProperty.h.
void setConfigurableModule(const std::string &moduleName)
customize the Module name where configurable base classes are defined
Definition: genconf.cpp:207
STL class.
const std::type_info * type_info() const
property type-info
Definition: Property.h:52
T at(T... args)
T push_back(T... args)
virtual StatusCode setProperty(const Gaudi::Details::PropertyBase &p)=0
Set the property by property.
int main(int argc, char **argv)
Definition: genconf.cpp:261
GAUDI_API ISvcLocator * svcLocator()
GAUDIPS_API Logger & logger()
Return the current logger instance.
T what(T... args)
#define LOG_INFO
Definition: genconf.cpp:76
Definition of the basic interface.
Definition: IInterface.h:254
STL class.
void genHeader(std::ostream &pyOut, std::ostream &dbOut)
Definition: genconf.cpp:650
T str(T... args)
PropertyBase base class allowing PropertyBase* collections to be "homogeneous".
Definition: Property.h:42
stringstream m_dbBuf
buffer of generated configurables informations for the "Db" file The "Db" file is holding information...
Definition: genconf.cpp:185
Converter base class.
Definition: Converter.h:34
configGenerator(const string &pkgName, const string &outputDirName)
Definition: genconf.cpp:197
STL class.
void setConfigurableAlgorithm(const std::string &cfgAlgorithm)
customize the configurable base class for Algorithm component
Definition: genconf.cpp:215
GAUDI_API bool isEnvSet(const char *var)
Check if an environment variable is set or not.
Definition: System.cpp:399
T flush(T... args)
const DataObjectHandleBase & value() const
void init_logging(boost::log::trivial::severity_level level)
Definition: genconf.cpp:248
Alias for backward compatibility.
Definition: Algorithm.h:58
T find(T... args)
T size(T... args)
const StatusCode & ignore() const
Ignore/check StatusCode.
Definition: StatusCode.h:168
Base class of array's of various gaudihandles.
Definition: GaudiHandle.h:342
string m_outputDirName
absolute path to the directory where genconf will store auto-generated files (Configurables and Confi...
Definition: genconf.cpp:171
std::string format(bool local, std::string spec="%c") const
Format the time using strftime.
Definition: Time.cpp:262
virtual unsigned long release()=0
Release Interface instance.
#define LOG_WARNING
Definition: genconf.cpp:75
DataObjectHandleBase GaudiKernel/DataObjectHandleBase.h.
void genImport(std::ostream &s, std::string_view frmt, std::string indent)
Definition: genconf.cpp:619
T begin(T... args)
void setConfigurableService(const std::string &cfgService)
customize the configurable base class for Service component
Definition: genconf.cpp:226
GAUDI_API const std::string & moduleName()
Get the name of the (executable/DLL) file without file-type.
Definition: ModuleInfo.cpp:64
Base class from which all the concrete tool classes should be derived.
Definition: AlgTool.h:57
virtual const std::vector< Gaudi::Details::PropertyBase * > & getProperties() const =0
Get list of properties.
string s
Definition: gaudirun.py:328
STL class.
std::map< component_t, std::string > m_configurable
Configurable customization.
Definition: genconf.cpp:194
string m_pkgName
name of the package we are processing
Definition: genconf.cpp:167
virtual unsigned long addRef()=0
Increment the reference count of Interface instance.
T substr(T... args)
static GAUDI_API void disableChecking()
Definition: StatusCode.cpp:55
void reset(TYPE *ptr=nullptr)
Set the internal pointer to the passed one disposing of the old one.
Definition: SmartIF.h:96
void genTrailer(std::ostream &pyOut, std::ostream &dbOut)
Definition: genconf.cpp:674
GAUDI_API const std::string getLastErrorString()
Get last system error as string.
Definition: System.cpp:272
Base class to handles to be used in lieu of naked pointers to various Gaudi components.
Definition: GaudiHandle.h:99
const GaudiHandleBase & value() const
Definition: Property.h:898
std::string pythonPropertyClassName() const override
Name of the componentType with "HandleArray" appended.
Definition: GaudiHandle.cpp:86
virtual StatusCode configure()=0
Configure the job.
The IProperty is the basic interface for all components which have properties that can be set or get.
Definition: IProperty.h:30
Base class for all services.
Definition: Service.h:46
GAUDIPS_API void SetDebug(int debugLevel)
Backward compatibility with Reflex.
int createAppMgr()
Definition: genconf.cpp:839
STL class.
virtual std::string toString() const =0
value -> string
stringstream m_db2Buf
Definition: genconf.cpp:187
void genBody(std::ostream &pyOut, std::ostream &dbOut)
Definition: genconf.cpp:236
STL class.
T compare(T... args)
GAUDI_API IAppMgrUI * createApplicationMgr(const std::string &dllname, const std::string &factname)
T reserve(T... args)
std::ostream & operator<<(std::ostream &str, const GaudiAlg::ID &id)
Operator overloading for ostream.
Definition: GaudiHistoID.h:142
Base class from which all concrete auditor classes should be derived.
Definition: Auditor.h:44
GAUDI_API unsigned long loadDynamicLib(const std::string &name, ImageHandle *handle)
Load dynamic link library.
Definition: System.cpp:145
void setConfigurableAuditor(const std::string &cfgAuditor)
customize the configurable base class for AlgTool component
Definition: genconf.cpp:223
T emplace_back(T... args)
std::string pythonRepr() const override
Python representation of array of handles, i.e.
Definition: GaudiHandle.cpp:88