The Gaudi Framework  master (37c0b60a)
JobOptionsSvc.cpp
Go to the documentation of this file.
1 /***********************************************************************************\
2 * (c) Copyright 1998-2022 CERN for the benefit of the LHCb and ATLAS collaborations *
3 * *
4 * This software is distributed under the terms of the Apache version 2 licence, *
5 * copied verbatim in the file "LICENSE". *
6 * *
7 * In applying this licence, CERN does not waive the privileges and immunities *
8 * granted to it by virtue of its status as an Intergovernmental Organization *
9 * or submit itself to any jurisdiction. *
10 \***********************************************************************************/
11 #include "Analyzer.h"
12 #include "Catalog.h"
13 #include "Messages.h"
14 #include "Node.h"
15 #include "PragmaOptions.h"
16 #include "PropertyId.h"
17 #include "PythonConfig.h"
18 #include "Units.h"
20 #include <Gaudi/Parsers/Factory.h>
21 #include <Gaudi/Property.h>
22 #include <GaudiKernel/IProperty.h>
23 #include <GaudiKernel/MsgStream.h>
26 #include <GaudiKernel/Service.h>
27 #include <GaudiKernel/StatusCode.h>
28 #include <GaudiKernel/System.h>
29 #include <algorithm>
30 #include <functional>
31 #include <memory>
32 #include <nlohmann/json.hpp>
33 #include <string>
34 #include <unordered_map>
35 #include <vector>
36 
37 #if __cplusplus >= 201703
38 # include <string_view>
39 #else
40 # include <experimental/string_view>
41 namespace std {
42  using experimental::string_view;
43 }
44 #endif
45 
46 namespace Gaudi {
47  namespace Parsers {
48  class Catalog;
49  }
50 } // namespace Gaudi
51 
52 class JobOptionsSvc : public extends<Service, Gaudi::Interfaces::IOptionsSvc> {
53 public:
55 
56 private:
59 
61 
64 
65 protected:
67  void set( const std::string& key, const std::string& value ) override { m_options[key] = value; }
68  std::string get( const std::string& key, const std::string& default_ = {} ) const override {
69  auto item = m_options.find( key );
70  return item != m_options.end() ? std::string{ item->second } : default_;
71  }
72  std::string pop( const std::string& key, const std::string& default_ = {} ) override {
73  std::string result = default_;
74 
75  auto item = m_options.find( key );
76  if ( item != m_options.end() ) {
77  result = std::move( item->second );
78  m_options.erase( item );
79  }
80  return result;
81  }
82  bool has( const std::string& key ) const override { return m_options.find( key ) != m_options.end(); }
85  v.reserve( m_options.size() );
86  std::for_each( begin( m_options ), end( m_options ), [&v]( const auto& item ) { v.emplace_back( item ); } );
87  std::sort( begin( v ), end( v ) );
88  return v;
89  }
90  bool isSet( const std::string& key ) const override {
91  auto item = m_options.find( key );
92  return item != m_options.end() && item->second.isSet();
93  }
94 
96 
97  void broadcast( const std::regex& filter, const std::string& value, OnlyDefaults defaults_only ) override;
99 
100 public:
101  // Constructor
102  JobOptionsSvc( const std::string& name, ISvcLocator* svc );
103 
104  StatusCode initialize() override;
105  StatusCode start() override;
106  StatusCode stop() override;
107 
114  StatusCode readOptions( std::string_view file, std::string_view path = "" ) override;
115 
116 private:
117  void fillServiceCatalog( const Gaudi::Parsers::Catalog& catalog );
118 
120  void dump( const std::string& file, const Gaudi::Parsers::Catalog& catalog ) const;
121  void dump( const std::string& file ) const;
122 
123 private:
130 
132  this,
133  "GlobalDefaults",
134  {},
135  "Allow definition of global defaults for properties as list of pairs (regex, value)" };
136 
137  Gaudi::Property<bool> m_reportUnused{ this, "ReportUnused", false, "Print report of properties set, but not used" };
138 
140 };
141 
142 // ============================================================================
144 // ============================================================================
145 // Namespace aliases:
146 // ============================================================================
147 namespace gp = Gaudi::Parsers;
148 // ============================================================================
150  if ( System::isEnvSet( "JOBOPTSEARCHPATH" ) ) m_dir_search_path = System::getEnv( "JOBOPTSEARCHPATH" );
151  if ( System::isEnvSet( "JOBOPTSDUMPFILE" ) ) m_dump = System::getEnv( "JOBOPTSDUMPFILE" );
152 
156  for ( const auto& p : m_globalDefaultsProp ) { m_globalDefaults.emplace_back( p.first, p.second ); }
157  } );
158 }
159 // ============================================================================
161  // Call base class initializer
163  // Read the job options if needed
164  if ( sc ) {
165  if ( m_source_type == "NONE" ) {
166  return sc;
167  } else if ( m_source_type == "PYTHON" ) {
168  PythonConfig conf( this );
169  return conf.evaluateConfig( m_source_path, m_pythonParams, m_pythonAction );
170  } else {
172  }
173  }
174  return sc;
175 }
177  if ( m_reportUnused ) {
179  unused.reserve( m_options.size() );
180 
181  for ( const auto& p : m_options ) {
182  if ( !p.second.isBound() ) unused.emplace_back( p.first );
183  }
184 
185  if ( !unused.empty() ) {
186  std::sort( unused.begin(), unused.end() );
187  auto& log = warning();
188  log << unused.size() << " unused properties:";
189  for ( const auto& k : unused ) log << "\n - " << k;
190  log << endmsg;
191  }
192  }
193  return Service::stop();
194 }
195 
196 // ============================================================================
198  if ( !m_dump.empty() ) { dump( m_dump ); }
199  return StatusCode::SUCCESS;
200 }
201 
202 void JobOptionsSvc::dump( const std::string& file, const gp::Catalog& catalog ) const {
203  std::ofstream out( file, std::ios_base::out | std::ios_base::trunc );
204  if ( !out ) {
205  error() << "Unable to open dump-file \"" + file + "\"" << endmsg;
206  return; // RETURN
207  }
208  info() << "Properties are dumped into \"" + file + "\"" << endmsg;
209  // perform the actual dump:
210  out << catalog;
211 }
212 
213 void JobOptionsSvc::dump( const std::string& file ) const {
214  std::ofstream out( file, std::ios_base::out | std::ios_base::trunc );
215  if ( !out ) {
216  error() << "Unable to open dump-file \"" + file + "\"" << endmsg;
217  } else {
218  info() << "Properties are dumped into \"" + file + "\"" << endmsg;
219  for ( const auto& [key, value] : items() ) {
220  out << key << " = " << value << ';';
221  if ( !m_options.find( key )->second.isBound() ) out << " // unused";
222  out << '\n';
223  }
224  }
225 }
226 
228  for ( const auto& client : catalog ) {
229  for ( const auto& current : client.second ) {
230  set( client.first + '.' + current.NameInClient(), current.ValueAsString() );
231  }
232  }
233 }
234 
235 StatusCode JobOptionsSvc::readOptions( std::string_view file, std::string_view path ) {
236  std::string search_path = std::string{ path };
237  if ( search_path.empty() && !m_dir_search_path.empty() ) { search_path = m_dir_search_path; }
238 
239  if ( msgLevel( MSG::DEBUG ) )
240  debug() << "Reading options from the file "
241  << "'" << file << "'" << endmsg;
242 
243  if ( file.size() >= 5 && file.substr( file.size() - 5 ) == ".json" ) {
246  input >> opts;
247  for ( auto item = opts.begin(); item != opts.end(); ++item ) { set( item.key(), item.value().get<std::string>() ); }
248  return StatusCode::SUCCESS;
249  }
250 
251  gp::Messages messages( msgStream() );
252  gp::Catalog catalog;
253  gp::Units units;
254  gp::PragmaOptions pragma;
255  gp::Node ast;
256  StatusCode sc = gp::ReadOptions( file, path, &messages, &catalog, &units, &pragma, &ast ) ? StatusCode::SUCCESS
258 
259  // --------------------------------------------------------------------------
260  if ( sc.isSuccess() ) {
261  if ( pragma.IsPrintOptions() ) { info() << "Print options" << std::endl << catalog << endmsg; }
262  if ( pragma.IsPrintTree() ) { info() << "Print tree:" << std::endl << ast.ToString() << endmsg; }
263  if ( pragma.HasDumpFile() ) dump( pragma.dumpFile(), catalog );
264  info() << "Job options successfully read in from " << file << endmsg;
265  fillServiceCatalog( catalog );
266  } else {
267  fatal() << "Job options errors." << endmsg;
268  }
269  // ----------------------------------------------------------------------------
270  return sc;
271 }
272 
274  const std::string key = prefix + '.' + property->name();
275 
276  std::tuple<bool, std::string_view> defaultValue{ false, "" };
277  if ( !has( key ) && !m_globalDefaults.empty() ) { // look for a global default only if it was not set
278  std::smatch match;
279  for ( const auto& p : m_globalDefaults ) {
280  if ( regex_match( key, match, p.first ) ) { defaultValue = { true, p.second }; }
281  }
282  }
283 
284  m_options[key] = *property;
285 
286  // at this point the property is bound, so we can set the default if needed
287  if ( std::get<0>( defaultValue ) ) set( key, std::string{ std::get<1>( defaultValue ) } );
288 }
289 
290 void JobOptionsSvc::broadcast( const std::regex& filter, const std::string& value, OnlyDefaults defaults_only ) {
291  std::smatch match;
292  for ( auto& p : m_options ) {
293  if ( !defaults_only || !p.second.isSet() ) {
294  const auto s = p.first.str();
295  if ( regex_match( s, match, filter ) ) { p.second = value; }
296  }
297  }
298 }
JobOptionsSvc::get
std::string get(const std::string &key, const std::string &default_={}) const override
Definition: JobOptionsSvc.cpp:68
MSG::DEBUG
@ DEBUG
Definition: IMessageSvc.h:25
Gaudi::Details::PropertyBase
PropertyBase base class allowing PropertyBase* collections to be "homogeneous".
Definition: PropertyBase.h:35
std::for_each
T for_each(T... args)
Service::initialize
StatusCode initialize() override
Definition: Service.cpp:118
std::string
STL class.
Gaudi.Configuration.log
log
Definition: Configuration.py:28
JobOptionsSvc::m_reportUnused
Gaudi::Property< bool > m_reportUnused
Definition: JobOptionsSvc.cpp:137
std::move
T move(T... args)
AtlasMCRecoFullPrecedenceDump.path
path
Definition: AtlasMCRecoFullPrecedenceDump.py:49
StatusCode::isSuccess
bool isSuccess() const
Definition: StatusCode.h:314
Gaudi::Parsers::Units
Definition: Units.h:28
System.h
std::vector::reserve
T reserve(T... args)
Gaudi::Details::WeakPropertyRef::isBound
bool isBound() const
Definition: PropertyBase.h:208
gaudirun.s
string s
Definition: gaudirun.py:346
JobOptionsSvc::m_old_iface_compat_2
std::map< std::string, PropertiesT > m_old_iface_compat_2
Definition: JobOptionsSvc.cpp:63
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
STL class.
std::unordered_map::find
T find(T... args)
std::unordered_map::size
T size(T... args)
ISvcLocator
Definition: ISvcLocator.h:46
jsonFromLHCbLog.json
json
Definition: jsonFromLHCbLog.py:86
JobOptionsSvc::m_pythonAction
Gaudi::Property< std::string > m_pythonAction
Definition: JobOptionsSvc.cpp:128
JobOptionsSvc::m_source_path
Gaudi::Property< std::string > m_source_path
Definition: JobOptionsSvc.cpp:125
JobOptionsSvc::set
void set(const std::string &key, const std::string &value) override
Definition: JobOptionsSvc.cpp:67
JobOptionsSvc::bind
void bind(const std::string &prefix, Gaudi::Details::PropertyBase *property) override
Definition: JobOptionsSvc.cpp:273
std::tuple
gaudirun.prefix
string prefix
Definition: gaudirun.py:361
Gaudi::Parsers::Node
Definition: Node.h:35
JobOptionsSvc::m_options
StorageType m_options
Definition: JobOptionsSvc.cpp:60
JobOptionsSvc::m_pythonParams
Gaudi::Property< std::string > m_pythonParams
Definition: JobOptionsSvc.cpp:129
StatusCode.h
std::sort
T sort(T... args)
CommonMessaging< implements< IService, IProperty, IStateful > >::msgLevel
MSG::Level msgLevel() const
get the cached level (originally extracted from the embedded MsgStream)
Definition: CommonMessaging.h:148
std::vector::clear
T clear(T... args)
PropertyHolder< CommonMessaging< implements< IService, IProperty, IStateful > > >::property
Gaudi::Details::PropertyBase * property(std::string_view name) const
\fixme property and bindPropertiesTo should be protected
Definition: PropertyHolder.h:238
Gaudi::Details::WeakPropertyRef::isSet
bool isSet() const
Definition: PropertyBase.h:209
JobOptionsSvc::broadcast
void broadcast(const std::regex &filter, const std::string &value, OnlyDefaults defaults_only) override
Definition: JobOptionsSvc.cpp:290
PropertyId.h
JobOptionsSvc::start
StatusCode start() override
Definition: JobOptionsSvc.cpp:197
Gaudi::Parsers::PragmaOptions
Definition: PragmaOptions.h:33
JobOptionsSvc::m_old_iface_compat
std::map< std::string, std::unique_ptr< Gaudi::Details::PropertyBase > > m_old_iface_compat
Definition: JobOptionsSvc.cpp:62
Gaudi::Utils::begin
AttribStringParser::Iterator begin(const AttribStringParser &parser)
Definition: AttribStringParser.h:136
Service::name
const std::string & name() const override
Retrieve name of the service
Definition: Service.cpp:332
StatusCode
Definition: StatusCode.h:65
Gaudi::Parsers::Node::ToString
std::string ToString(int indent=0) const
Definition: Node.cpp:63
gaudirun.opts
opts
Definition: gaudirun.py:336
JobOptionsSvc::m_dump
Gaudi::Property< std::string > m_dump
Definition: JobOptionsSvc.cpp:127
JobOptionsSvc::stop
StatusCode stop() override
Definition: JobOptionsSvc.cpp:176
std::ofstream
STL class.
JobOptionsSvc::m_globalDefaultsProp
Gaudi::Property< std::vector< std::pair< std::string, std::string > > > m_globalDefaultsProp
Definition: JobOptionsSvc.cpp:131
CommonMessaging
Definition: CommonMessaging.h:66
Gaudi::Parsers::Messages
Definition: Messages.h:31
Gaudi::Property::declareUpdateHandler
Details::PropertyBase & declareUpdateHandler(std::function< void(Details::PropertyBase &)> fun) override
set new callback for update
Definition: Property.h:144
std::unordered_map::erase
T erase(T... args)
JobOptionsSvc::readOptions
StatusCode readOptions(std::string_view file, std::string_view path="") override
look for file 'file' into search path 'path' and read it to update existing JobOptionsCatalogue
Definition: JobOptionsSvc.cpp:235
endmsg
MsgStream & endmsg(MsgStream &s)
MsgStream Modifier: endmsg. Calls the output method of the MsgStream.
Definition: MsgStream.h:202
System::isEnvSet
GAUDI_API bool isEnvSet(const char *var)
Check if an environment variable is set or not.
Definition: System.cpp:410
std::map
STL class.
extends
Base class used to extend a class implementing other interfaces.
Definition: extends.h:20
std::regex
Units.h
Gaudi
This file provides a Grammar for the type Gaudi::Accumulators::Axis It allows to use that type from p...
Definition: __init__.py:1
Gaudi::Parsers::ReadOptions
bool ReadOptions(std::string_view filename, std::string_view search_path, Messages *messages, Catalog *catalog, Units *units, PragmaOptions *pragma, Node *root)
Parse and analyze filename, save all messages and properties.
Definition: Analyzer.cpp:387
JobOptionsSvc::dump
void dump(const std::string &file, const Gaudi::Parsers::Catalog &catalog) const
dump properties catalog to file
Definition: JobOptionsSvc.cpp:202
Messages.h
JobOptionsSvc::m_dir_search_path
Gaudi::Property< std::string > m_dir_search_path
Definition: JobOptionsSvc.cpp:126
PythonConfig.h
Service.h
Factory.h
JobOptionsSvc::PropertiesT
std::vector< const Gaudi::Details::PropertyBase * > PropertiesT
Definition: JobOptionsSvc.cpp:54
std::vector::emplace_back
T emplace_back(T... args)
Node.h
Gaudi::Details::PropertyId
Helper to record a property identifier as a sequence of SharedString instances.
Definition: PropertyId.h:73
StatusCode::SUCCESS
constexpr static const auto SUCCESS
Definition: StatusCode.h:100
ConditionsStallTest.name
name
Definition: ConditionsStallTest.py:77
std::endl
T endl(T... args)
Service::stop
StatusCode stop() override
Definition: Service.cpp:181
JobOptionsSvc::initialize
StatusCode initialize() override
Definition: JobOptionsSvc.cpp:160
JobOptionsSvc::m_source_type
Gaudi::Property< std::string > m_source_type
Definition: JobOptionsSvc.cpp:124
Gaudi::Parsers::PragmaOptions::IsPrintOptions
bool IsPrintOptions()
Definition: PragmaOptions.h:49
System::PathResolver::find_file
static std::string find_file(const std::string &logical_file_name, const std::string &search_path, SearchType search_type=LocalSearch)
Definition: PathResolver.cpp:118
JobOptionsSvc
Definition: JobOptionsSvc.cpp:52
std::vector::begin
T begin(T... args)
std
STL namespace.
DECLARE_COMPONENT
#define DECLARE_COMPONENT(type)
Definition: PluginServiceV1.h:46
JobOptionsSvc::isSet
bool isSet(const std::string &key) const override
Definition: JobOptionsSvc.cpp:90
std::vector::empty
T empty(T... args)
Properties.v
v
Definition: Properties.py:122
Gaudi::Parsers::PragmaOptions::HasDumpFile
bool HasDumpFile()
Definition: PragmaOptions.h:51
Gaudi::Parsers
Definition: DODBasicMapper.cpp:17
IProperty.h
std::smatch
std::unordered_map::end
T end(T... args)
IOTest.end
end
Definition: IOTest.py:125
StatusCode::FAILURE
constexpr static const auto FAILURE
Definition: StatusCode.h:101
JobOptionsSvc::pop
std::string pop(const std::string &key, const std::string &default_={}) override
Definition: JobOptionsSvc.cpp:72
PathResolver.h
Catalog.h
JobOptionsSvc::fillServiceCatalog
void fillServiceCatalog(const Gaudi::Parsers::Catalog &catalog)
Definition: JobOptionsSvc.cpp:227
PropertyHolder.h
ProduceConsume.key
key
Definition: ProduceConsume.py:84
JobOptionsSvc::items
std::vector< std::tuple< std::string, std::string > > items() const override
Definition: JobOptionsSvc.cpp:83
std::unordered_map< PropertyId, Gaudi::Details::WeakPropertyRef >
Gaudi::Parsers::PragmaOptions::IsPrintTree
bool IsPrintTree()
Definition: PragmaOptions.h:50
IOptionsSvc.h
Gaudi::Parsers::PragmaOptions::dumpFile
const std::string & dumpFile() const
Definition: PragmaOptions.h:46
JobOptionsSvc::has
bool has(const std::string &key) const override
Definition: JobOptionsSvc.cpp:82
conf
Definition: conf.py:1
JobOptionsSvc::m_globalDefaults
std::vector< std::pair< std::regex, std::string > > m_globalDefaults
Definition: JobOptionsSvc.cpp:139
Gaudi::Property< std::string >
JobOptionsSvc::JobOptionsSvc
JobOptionsSvc(const std::string &name, ISvcLocator *svc)
Definition: JobOptionsSvc.cpp:149
Gaudi::Parsers::Catalog
Definition: Catalog.h:39
Property.h
MsgStream.h
PythonConfig
Definition: PythonConfig.h:33
PrepareBase.out
out
Definition: PrepareBase.py:20
Analyzer.h
std::ifstream
STL class.
PragmaOptions.h