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