Loading [MathJax]/extensions/tex2jax.js
The Gaudi Framework  v38r1p1 (ae26267b)
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
HiveDataBroker.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 #include "HiveDataBroker.h"
14 #include "GaudiKernel/System.h"
15 #include "boost/lexical_cast.hpp"
16 #include "boost/tokenizer.hpp"
17 #include <Gaudi/Algorithm.h>
18 #include <algorithm>
19 #include <iomanip>
20 #ifdef __cpp_lib_ranges
21 # include <ranges>
22 namespace ranges = std::ranges;
23 #else
24 # include "range/v3/algorithm/for_each.hpp"
25 # include "range/v3/view/filter.hpp"
26 # include "range/v3/view/reverse.hpp"
27 # include "range/v3/view/transform.hpp"
28 // upstream has renamed namespace ranges::view ranges::views
29 # if RANGE_V3_VERSION < 900
30 namespace ranges::views {
31  using namespace ranges::view;
32 }
33 # endif
34 #endif
35 
37 
38 namespace {
39  struct AlgorithmRepr {
40  const Gaudi::Algorithm& parent;
41 
42  friend std::ostream& operator<<( std::ostream& s, const AlgorithmRepr& a ) {
43  std::string typ = System::typeinfoName( typeid( a.parent ) );
44  s << typ;
45  if ( a.parent.name() != typ ) s << "/" << a.parent.name();
46  return s;
47  }
48  };
49 
50  struct DataObjIDSorter {
51  bool operator()( const DataObjID* a, const DataObjID* b ) { return a->fullKey() < b->fullKey(); }
52  };
53 
54  // Sort a DataObjIDColl in a well-defined, reproducible manner.
55  // Used for making debugging dumps.
56  std::vector<const DataObjID*> sortedDataObjIDColl( const DataObjIDColl& coll ) {
58  v.reserve( coll.size() );
59  for ( const DataObjID& id : coll ) v.push_back( &id );
60  std::sort( v.begin(), v.end(), DataObjIDSorter() );
61  return v;
62  }
63 
64  SmartIF<IAlgorithm> createAlgorithm( IAlgManager& am, const std::string& type, const std::string& name ) {
65  // Maybe modify the AppMgr interface to return Algorithm* ??
66  IAlgorithm* tmp = nullptr;
67  StatusCode sc = am.createAlgorithm( type, name, tmp );
68  return sc.isSuccess() ? dynamic_cast<Gaudi::Algorithm*>( tmp ) : nullptr;
69  }
70 } // namespace
71 
73  return Service::initialize().andThen( [&] {
74  // populate m_algorithms
75  m_algorithms = instantiateAndInitializeAlgorithms( m_producers );
76 
77  // warn about non-reentrant algorithms
78  ranges::for_each( m_algorithms | ranges::views::transform( []( const auto& entry ) { return entry.second.alg; } ) |
79  ranges::views::filter( []( const auto* alg ) { return alg->cardinality() > 0; } ),
80  [&]( const Gaudi::Algorithm* alg ) {
81  this->warning() << "non-reentrant algorithm: " << AlgorithmRepr{ *alg } << endmsg;
82  } );
83  //== Print the list of the created algorithms
84  if ( msgLevel( MSG::DEBUG ) ) {
85  MsgStream& msg = debug();
86  msg << "Available DataProducers: ";
88  msg, m_algorithms, ", ", []( auto& os, const std::pair<std::string, AlgEntry>& e ) -> decltype( auto ) {
89  return os << AlgorithmRepr{ *e.second.alg };
90  } );
91  msg << endmsg;
92  }
93 
94  // populate m_dependencies and set AlgEntry::dependsOn
95  m_dependencies = mapProducers( m_algorithms );
96  } );
97 }
98 
100 
101  StatusCode ss = Service::start();
102  if ( !ss.isSuccess() ) return ss;
103 
104  // sysStart for m_algorithms
105  for ( auto& [name, algEntry] : m_algorithms ) {
106  ss = algEntry.alg->sysStart();
107  if ( ss.isFailure() ) {
108  error() << "Unable to start Algorithm: " << name << endmsg;
109  return ss;
110  }
111  }
112  return ss;
113 }
114 
116  StatusCode ss = Service::stop();
117  if ( !ss.isSuccess() ) return ss;
118 
119  // sysStart for m_algorithms
120  for ( auto& [name, algEntry] : m_algorithms ) {
121  ss = algEntry.alg->sysStop();
122  if ( ss.isFailure() ) {
123  error() << "Unable to stop Algorithm: " << name << endmsg;
124  return ss;
125  }
126  }
127  return ss;
128 }
129 
131  for ( auto& [name, algEntry] : m_algorithms ) {
132  algEntry.alg->sysFinalize().ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
133  }
134  m_algorithms.clear();
135  return Service::finalize();
136 }
137 
141 
142  //= Get the Application manager, to see if algorithm exist
143  auto appMgr = service<IAlgManager>( "ApplicationMgr" );
144  size_t index = 0;
145  for ( const Gaudi::Utils::TypeNameString item : names ) {
146  const std::string& theName = item.name();
147  const std::string& theType = item.type();
148 
149  //== Check wether the specified algorithm already exists. If not, create it
150  SmartIF<IAlgorithm> myIAlg = appMgr->algorithm( item, false ); // do not create it now
151  if ( !myIAlg ) {
152  myIAlg = createAlgorithm( *appMgr, theType, theName );
153  } else {
154  // when the algorithm is not created, the ref count is short by one, so we
155  // have to fix it.
156  myIAlg->addRef();
157  }
158 
159  if ( !myIAlg ) {
160  throw GaudiException{ "Failed to create " + boost::lexical_cast<std::string>( item ), __func__,
162  }
163 
164  // propagate the sub-algorithm into own state.
165  StatusCode sc = myIAlg->sysInitialize();
166  if ( sc.isFailure() ) {
167  throw GaudiException{ "Failed to initialize " + boost::lexical_cast<std::string>( item ), __func__,
169  }
170 
171  algorithms.emplace( theName, AlgEntry{ index++, std::move( myIAlg ) } );
172  }
173 
174  return algorithms;
175 }
176 
179  if ( msgLevel( MSG::DEBUG ) ) {
180  debug() << "Data Dependencies for Algorithms:";
181  for ( const auto& [name, entry] : m_algorithms ) {
182  debug() << "\n " << name << " :";
183  for ( const auto* id : sortedDataObjIDColl( entry.alg->inputDataObjs() ) ) {
184  debug() << "\n o INPUT " << id->key();
185  }
186  for ( const auto* id : sortedDataObjIDColl( entry.alg->outputDataObjs() ) ) {
187  debug() << "\n o OUTPUT " << id->key();
188  }
189  }
190  debug() << endmsg;
191  }
192 
193  // figure out all outputs
195  for ( auto& [name, alg] : algorithms ) {
196  const auto& output = alg.alg->outputDataObjs();
197  if ( output.empty() ) { continue; }
198  for ( auto id : output ) {
199  auto r = producers.emplace( id, &alg );
200  if ( !r.second ) {
201  throw GaudiException( "multiple algorithms declare " + id.key() + " as output (" + name + " and " +
202  producers[id]->alg->name() + " at least). This is not allowed",
203  __func__, StatusCode::FAILURE );
204  }
205  }
206  }
207 
208  // resolve dependencies
209  for ( auto& [name, algEntry] : algorithms ) {
210  auto input = sortedDataObjIDColl( algEntry.alg->inputDataObjs() );
211  for ( const DataObjID* idp : input ) {
212  DataObjID id = *idp;
213  auto iproducer = producers.find( id );
214  if ( iproducer != producers.end() ) {
215  algEntry.dependsOn.insert( iproducer->second );
216  } else {
217  std::ostringstream error_message;
218  error_message << "\nUnknown requested input by " << AlgorithmRepr{ *( algEntry.alg ) } << " : "
219  << std::quoted( id.key(), '\'' ) << ".\n";
220  error_message << "You can set the OutputLevel of HiveDataBrokerSvc to DEBUG to get a list of inputs and "
221  "outputs of every registered algorithm.\n";
222  throw GaudiException( error_message.str(), __func__, StatusCode::FAILURE );
223  // TODO: assign to dataloader!
224  // algEntry.dependsOn.insert(dataloader.alg);
225  // dataloader.data.emplace( id ); // TODO: we may ask to much of the
226  // dataloader this way...
227  }
228  }
229  }
230  return producers;
231 }
232 
236  std::vector<bool>& visiting ) const {
237  assert( visited.size() == m_algorithms.size() );
238  assert( visiting.size() == m_algorithms.size() );
239  if ( visited[alg.index] ) { return; }
240  if ( visiting[alg.index] ) { throw GaudiException( "Cycle detected ", __func__, StatusCode::FAILURE ); }
241 
242  if ( std::none_of( std::begin( stoppers ), std::end( stoppers ),
243  [alg]( auto& stopper ) { return alg.alg->name() == stopper; } ) ) {
244  visiting[alg.index] = true;
245  for ( auto* dep : alg.dependsOn ) { visit( *dep, stoppers, sorted, visited, visiting ); }
246  visiting[alg.index] = false;
247  }
248 
249  visited[alg.index] = true;
250  sorted.push_back( alg.alg );
251 }
252 
255  const std::vector<std::string>& stoppers ) const {
257 
259  deps.reserve( requested.size() );
260 
261  // start with seeding from the initial request
262  for ( const auto& req : requested ) {
263  DataObjID id = req;
264  auto i = m_dependencies.find( id );
265  if ( i == m_dependencies.end() )
266  throw GaudiException( "unknown requested input: " + id.key(), __func__, StatusCode::FAILURE );
267  deps.push_back( i->second );
268  }
269  // producers may be responsible for multiple requested DataObjID -- make sure they are only mentioned once
270  std::sort( deps.begin(), deps.end() );
271  deps.erase( std::unique( deps.begin(), deps.end() ), deps.end() );
272 
273  std::vector<bool> visited( m_algorithms.size() );
274  std::vector<bool> visiting( m_algorithms.size() );
275  for ( auto* alg : deps ) { visit( *alg, stoppers, result, visited, visiting ); }
276  return result;
277 }
278 
281  const std::vector<std::string>& stoppers ) const {
283 
284  auto it = m_algorithms.find( requested.name() );
285  if ( it == end( m_algorithms ) ) {
286  throw GaudiException{ "No algorithm with name " + requested.name() + " in DataProducers. Type is " +
287  ( requested.haveType() ? requested.type() : "not specified" ),
288  __func__, StatusCode::FAILURE };
289  }
290  auto const& alg = it->second;
291  if ( requested.haveType() && alg.alg->type() != requested.type() ) {
292  error() << "requested " << requested << " but have matching name with different type: " << alg.alg->type()
293  << endmsg;
294  }
295  assert( alg.alg != nullptr );
296 
297  std::vector<bool> visited( m_algorithms.size() );
298  std::vector<bool> visiting( m_algorithms.size() );
299  visit( alg, stoppers, result, visited, visiting );
300 
301  if ( msgLevel( MSG::DEBUG ) ) {
302  debug() << std::endl << "requested " << requested << " returning " << std::endl << " ";
304  debug(), result, ",\n ",
305  []( auto& os, const Gaudi::Algorithm* a ) -> decltype( auto ) { return os << AlgorithmRepr{ *a }; } );
306  debug() << std::endl << endmsg;
307  }
308  return result;
309 }
MSG::DEBUG
@ DEBUG
Definition: IMessageSvc.h:25
Histograms_with_global.algorithms
algorithms
Definition: Histograms_with_global.py:19
HiveDataBrokerSvc::initialize
StatusCode initialize() override
Definition: HiveDataBroker.cpp:72
IAlgManager.h
Service::initialize
StatusCode initialize() override
Definition: Service.cpp:118
std::string
STL class.
Gaudi::Utils::TypeNameString::name
const std::string & name() const
Definition: TypeNameString.h:49
StatusCode::andThen
StatusCode andThen(F &&f, ARGS &&... args) const
Chain code blocks making the execution conditional a success result.
Definition: StatusCode.h:163
std::move
T move(T... args)
StatusCode::isSuccess
bool isSuccess() const
Definition: StatusCode.h:314
Service::start
StatusCode start() override
Definition: Service.cpp:187
std::unordered_set< DataObjID, DataObjID_Hasher >
System.h
std::pair
std::vector::reserve
T reserve(T... args)
GaudiException.h
gaudirun.s
string s
Definition: gaudirun.py:346
std::vector
STL class.
std::map::find
T find(T... args)
std::unordered_set::size
T size(T... args)
GaudiException
Definition: GaudiException.h:31
GaudiMP.FdsRegistry.msg
msg
Definition: FdsRegistry.py:19
std::map::emplace
T emplace(T... args)
ranges
Definition: details.h:30
std::none_of
T none_of(T... args)
ranges::views
Definition: details.h:30
System::typeinfoName
GAUDI_API const std::string typeinfoName(const std::type_info &)
Get platform independent information about the class type.
Definition: System.cpp:313
gaudirun.output
output
Definition: gaudirun.py:521
HiveDataBrokerSvc::stop
StatusCode stop() override
Definition: HiveDataBroker.cpp:115
std::sort
T sort(T... args)
Service::finalize
StatusCode finalize() override
Definition: Service.cpp:222
HiveDataBrokerSvc::mapProducers
std::map< DataObjID, AlgEntry * > mapProducers(std::map< std::string, AlgEntry > &algorithms) const
Definition: HiveDataBroker.cpp:178
DataObjID::fullKey
std::string fullKey() const
combination of the key and the ClassName, mostly for debugging
Definition: DataObjID.cpp:99
std::vector::push_back
T push_back(T... args)
ManySmallAlgs.alg
alg
Definition: ManySmallAlgs.py:80
IAlgManager
Definition: IAlgManager.h:37
GaudiAlg::operator<<
std::ostream & operator<<(std::ostream &str, const GaudiAlg::ID &id)
Operator overloading for ostream.
Definition: GaudiHistoID.h:141
Gaudi::Utils::TypeNameString
Helper class to parse a string of format "type/name".
Definition: TypeNameString.h:20
StatusCode
Definition: StatusCode.h:65
Gaudi::cxx::for_each
void for_each(ContainerOfSynced &c, Fun &&f)
Definition: SynchronizedValue.h:104
IAlgorithm
Definition: IAlgorithm.h:38
std::ostream
STL class.
HiveDataBrokerSvc::start
StatusCode start() override
Definition: HiveDataBroker.cpp:99
HiveDataBrokerSvc::algorithmsRequiredFor
std::vector< Gaudi::Algorithm * > algorithmsRequiredFor(const DataObjIDColl &requested, const std::vector< std::string > &stoppers={}) const override
Definition: HiveDataBroker.cpp:254
Gaudi::Algorithm
Base class from which all concrete algorithm classes should be derived.
Definition: Algorithm.h:90
HiveDataBrokerSvc::instantiateAndInitializeAlgorithms
std::map< std::string, AlgEntry > instantiateAndInitializeAlgorithms(const std::vector< std::string > &names) const
Definition: HiveDataBroker.cpp:139
std::vector::erase
T erase(T... args)
Algorithm.h
SmartIF< IAlgorithm >
endmsg
MsgStream & endmsg(MsgStream &s)
MsgStream Modifier: endmsg. Calls the output method of the MsgStream.
Definition: MsgStream.h:203
std::map< std::string, HiveDataBrokerSvc::AlgEntry >
MsgStream
Definition: MsgStream.h:34
IAlgManager::createAlgorithm
virtual StatusCode createAlgorithm(std::string algtype, std::string algname, IAlgorithm *&alg, bool managed=false, bool checkIfExists=true)=0
Create an instance of a algorithm type that has been declared beforehand and assigns to it a name.
Gaudi::Utils::TypeNameString::type
const std::string & type() const
Definition: TypeNameString.h:48
DataObjID
Definition: DataObjID.h:47
StatusCode::ignore
const StatusCode & ignore() const
Allow discarding a StatusCode without warning.
Definition: StatusCode.h:139
std::ostringstream
STL class.
StatusCode::isFailure
bool isFailure() const
Definition: StatusCode.h:129
gaudirun.type
type
Definition: gaudirun.py:160
ConditionsStallTest.name
name
Definition: ConditionsStallTest.py:76
std::endl
T endl(T... args)
Service::stop
StatusCode stop() override
Definition: Service.cpp:181
HiveDataBrokerSvc
Definition: HiveDataBroker.h:17
std::begin
T begin(T... args)
DECLARE_COMPONENT
#define DECLARE_COMPONENT(type)
Definition: PluginServiceV1.h:46
Gaudi::Utils::TypeNameString::haveType
bool haveType() const
Definition: TypeNameString.h:50
std::unique
T unique(T... args)
Properties.v
v
Definition: Properties.py:122
std::ostringstream::str
T str(T... args)
std::map::end
T end(T... args)
IOTest.end
end
Definition: IOTest.py:123
HiveDataBrokerSvc::AlgEntry
Definition: HiveDataBroker.h:37
StatusCode::FAILURE
constexpr static const auto FAILURE
Definition: StatusCode.h:101
HiveDataBrokerSvc::visit
void visit(AlgEntry const &alg, std::vector< std::string > const &stoppers, std::vector< Gaudi::Algorithm * > &sorted, std::vector< bool > &visited, std::vector< bool > &visiting) const
Implements DFS topological sorting.
Definition: HiveDataBroker.cpp:234
HiveDataBrokerSvc::finalize
StatusCode finalize() override
Definition: HiveDataBroker.cpp:130
HiveDataBroker.h
ProduceConsume.key
key
Definition: ProduceConsume.py:81
IOTest.appMgr
appMgr
Definition: IOTest.py:103
Gaudi::ParticleProperties::index
size_t index(const Gaudi::ParticleProperty *property, const Gaudi::Interfaces::IParticlePropertySvc *service)
helper utility for mapping of Gaudi::ParticleProperty object into non-negative integral sequential id...
Definition: IParticlePropertySvc.cpp:39
GaudiUtils::details::ostream_joiner
Stream & ostream_joiner(Stream &os, Iterator first, Iterator last, Separator sep, OutputElement output=OutputElement{})
Definition: SerializeSTL.h:73