The Gaudi Framework  v33r1 (b1225454)
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 "range/v3/algorithm/for_each.hpp"
18 #include "range/v3/view/remove_if.hpp"
19 #include "range/v3/view/reverse.hpp"
20 #include "range/v3/view/transform.hpp"
21 #include <Gaudi/Algorithm.h>
22 #include <algorithm>
23 // upstream has renamed namespace ranges::view ranges::views
24 #if RANGE_V3_VERSION < 900
25 namespace ranges::views {
26  using namespace ranges::view;
27 }
28 #endif
29 
31 
32 namespace {
33  struct AlgorithmRepr {
35 
36  friend std::ostream& operator<<( std::ostream& s, const AlgorithmRepr& a ) {
37  std::string typ = System::typeinfoName( typeid( a.parent ) );
38  s << typ;
39  if ( a.parent.name() != typ ) s << "/" << a.parent.name();
40  return s;
41  }
42  };
43 
44  struct DataObjIDSorter {
45  bool operator()( const DataObjID* a, const DataObjID* b ) { return a->fullKey() < b->fullKey(); }
46  };
47 
48  // Sort a DataObjIDColl in a well-defined, reproducible manner.
49  // Used for making debugging dumps.
50  std::vector<const DataObjID*> sortedDataObjIDColl( const DataObjIDColl& coll ) {
52  v.reserve( coll.size() );
53  for ( const DataObjID& id : coll ) v.push_back( &id );
54  std::sort( v.begin(), v.end(), DataObjIDSorter() );
55  return v;
56  }
57 
58  SmartIF<IAlgorithm> createAlgorithm( IAlgManager& am, const std::string& type, const std::string& name ) {
59  // Maybe modify the AppMgr interface to return Algorithm* ??
60  IAlgorithm* tmp;
61  StatusCode sc = am.createAlgorithm( type, name, tmp );
62  return {sc.isSuccess() ? dynamic_cast<Gaudi::Algorithm*>( tmp ) : nullptr};
63  }
64 } // namespace
65 
67  auto sc = Service::initialize();
68  if ( sc.isFailure() ) return sc;
69  // populate m_algorithms
70  m_algorithms = instantiateAndInitializeAlgorithms( m_producers );
71  if ( sc.isFailure() ) return sc;
72 
73  // warn about non-reentrant algorithms
74  ranges::for_each( m_algorithms | ranges::views::transform( []( const auto& entry ) { return entry.alg; } ) |
75  ranges::views::remove_if( []( const auto* alg ) { return alg->cardinality() == 0; } ),
76  [&]( const Gaudi::Algorithm* alg ) {
77  this->warning() << "non-reentrant algorithm: " << AlgorithmRepr{*alg} << endmsg;
78  } );
79  //== Print the list of the created algorithms
80  if ( msgLevel( MSG::DEBUG ) ) {
81  MsgStream& msg = debug();
82  msg << "Available DataProducers: ";
84  msg, m_algorithms, ", ",
85  []( auto& os, const AlgEntry& e ) -> decltype( auto ) { return os << AlgorithmRepr{*e.alg}; } );
86  msg << endmsg;
87  }
88 
89  // populate m_dependencies
90  m_dependencies = mapProducers( m_algorithms );
91  return sc;
92 }
93 
95 
97  if ( !ss.isSuccess() ) return ss;
98 
99  // sysStart for m_algorithms
100  for ( AlgEntry& algEntry : m_algorithms ) {
101  ss = algEntry.alg->sysStart();
102  if ( ss.isFailure() ) {
103  error() << "Unable to start Algorithm: " << algEntry.alg->name() << endmsg;
104  return ss;
105  }
106  }
107  // sysStart for m_cfnodes
108  for ( AlgEntry& algEntry : m_cfnodes ) {
109  ss = algEntry.alg->sysStart();
110  if ( ss.isFailure() ) {
111  error() << "Unable to start Algorithm: " << algEntry.alg->name() << endmsg;
112  return ss;
113  }
114  }
115  return ss;
116 }
117 
119  StatusCode ss = Service::stop();
120  if ( !ss.isSuccess() ) return ss;
121 
122  // sysStart for m_algorithms
123  for ( AlgEntry& algEntry : m_algorithms ) {
124  ss = algEntry.alg->sysStop();
125  if ( ss.isFailure() ) {
126  error() << "Unable to stop Algorithm: " << algEntry.alg->name() << endmsg;
127  return ss;
128  }
129  }
130  // sysStart for m_cfnodes
131  for ( AlgEntry& algEntry : m_cfnodes ) {
132  ss = algEntry.alg->sysStop();
133  if ( ss.isFailure() ) {
134  error() << "Unable to stop Algorithm: " << algEntry.alg->name() << endmsg;
135  return ss;
136  }
137  }
138  return ss;
139 }
140 
142  ranges::for_each( m_algorithms | ranges::views::transform( &AlgEntry::alg ), []( Gaudi::Algorithm* alg ) {
143  alg->sysFinalize().ignore( /* AUTOMATICALLY ADDED FOR gaudi/Gaudi!763 */ );
144  } );
145  m_algorithms.clear();
146  return Service::finalize();
147 }
148 
149 // populate m_algorithms
152  std::vector<AlgEntry> algorithms;
153 
154  //= Get the Application manager, to see if algorithm exist
155  auto appMgr = service<IAlgManager>( "ApplicationMgr" );
156  for ( const Gaudi::Utils::TypeNameString item : names ) {
157  const std::string& theName = item.name();
158  const std::string& theType = item.type();
159 
160  //== Check wether the specified algorithm already exists. If not, create it
161  SmartIF<IAlgorithm> myIAlg = appMgr->algorithm( item, false ); // do not create it now
162  if ( !myIAlg ) {
163  myIAlg = createAlgorithm( *appMgr, theType, theName );
164  } else {
165  // when the algorithm is not created, the ref count is short by one, so we
166  // have to fix it.
167  myIAlg->addRef();
168  }
169 
170  if ( !myIAlg ) {
171  throw GaudiException{"Failed to create " + boost::lexical_cast<std::string>( item ), __func__,
173  }
174 
175  // propagate the sub-algorithm into own state.
176  StatusCode sc = myIAlg->sysInitialize();
177  if ( sc.isFailure() ) {
178  throw GaudiException{"Failed to initialize " + boost::lexical_cast<std::string>( item ), __func__,
180  }
181 
182  algorithms.emplace_back( std::move( myIAlg ) );
183  }
184 
185  return algorithms;
186 }
187 
190  if ( msgLevel( MSG::DEBUG ) ) {
191  debug() << "Data Dependencies for Algorithms:";
192  for ( const auto& entry : m_algorithms ) {
193  debug() << "\n " << entry.alg->name() << " :";
194  for ( const auto* id : sortedDataObjIDColl( entry.alg->inputDataObjs() ) ) {
195  debug() << "\n o INPUT " << id->key();
196  }
197  for ( const auto* id : sortedDataObjIDColl( entry.alg->outputDataObjs() ) ) {
198  debug() << "\n o OUTPUT " << id->key();
199  }
200  }
201  debug() << endmsg;
202  }
203 
204  // figure out all outputs
206  for ( AlgEntry& alg : algorithms ) {
207  const auto& output = alg.alg->outputDataObjs();
208  if ( output.empty() ) { continue; }
209  for ( auto id : output ) {
210  if ( id.key().find( ":" ) != std::string::npos ) {
211  error() << " in Alg " << AlgorithmRepr{*alg.alg} << " alternatives are NOT allowed for outputs! id: " << id
212  << endmsg;
213  }
214 
215  auto r = producers.emplace( id, &alg );
216  if ( !r.second ) {
217  throw GaudiException( "multiple algorithms declare " + id.key() + " as output (" + alg.alg->name() + " and " +
218  producers[id]->alg->name() + " at least). This is not allowed",
219  __func__, StatusCode::FAILURE );
220  }
221  }
222  }
223 
224  // resolve dependencies
225  for ( auto& algEntry : algorithms ) {
226  auto input = sortedDataObjIDColl( algEntry.alg->inputDataObjs() );
227  for ( const DataObjID* idp : input ) {
228  DataObjID id = *idp;
229  if ( id.key().find( ":" ) != std::string::npos ) {
230  warning() << AlgorithmRepr{*( algEntry.alg )} << " contains alternatives which require resolution...\n";
231  auto tokens = boost::tokenizer<boost::char_separator<char>>{id.key(), boost::char_separator<char>{":"}};
232  auto itok = std::find_if( tokens.begin(), tokens.end(),
233  [&]( DataObjID t ) { return producers.find( t ) != producers.end(); } );
234  if ( itok != tokens.end() ) {
235  warning() << "found matching output for " << *itok << " -- updating info\n";
236  id.updateKey( *itok );
237  warning() << "Please update input to not require alternatives, and "
238  "instead properly configure the dataloader"
239  << endmsg;
240  } else {
241  error() << "failed to find alternate in global output list"
242  << " for id: " << id << " in Alg " << algEntry.alg << endmsg;
243  }
244  }
245  auto iproducer = producers.find( id );
246  if ( iproducer != producers.end() ) {
247  algEntry.dependsOn.insert( iproducer->second );
248  } else {
249  std::ostringstream error_message;
250  error_message << "\nUnknown requested input by " << AlgorithmRepr{*( algEntry.alg )} << " : " << id.key()
251  << " .\n";
252  error_message << "You can set the OutputLevel of HiveDataBrokerSvc to DEBUG to get a list of inputs and "
253  "outputs of every algorithm.\n";
254  throw GaudiException( error_message.str(), __func__, StatusCode::FAILURE );
255  // TODO: assign to dataloader!
256  // algEntry.dependsOn.insert(dataloader.alg);
257  // dataloader.data.emplace( id ); // TODO: we may ask to much of the
258  // dataloader this way...
259  }
260  }
261  }
262  return producers;
263 }
264 
267  const std::vector<std::string>& stoppers ) const {
269 
271  deps.reserve( requested.size() );
272 
273  // start with seeding from the initial request
274  for ( const auto& req : requested ) {
275  DataObjID id = req;
276  if ( id.key().find( ":" ) != std::string::npos ) {
277  warning() << req.key() << " contains alternatives which require resolution...\n";
278  auto tokens = boost::tokenizer<boost::char_separator<char>>{id.key(), boost::char_separator<char>{":"}};
279  auto itok = std::find_if( tokens.begin(), tokens.end(),
280  [&]( DataObjID t ) { return m_dependencies.find( t ) != m_dependencies.end(); } );
281  if ( itok != tokens.end() ) {
282  warning() << "found matching output for " << *itok << " -- updating info\n";
283  id.updateKey( *itok );
284  warning() << "Please update input to not require alternatives, and "
285  "instead properly configure the dataloader"
286  << endmsg;
287  } else {
288  error() << "failed to find alternate in global output list"
289  << " for id: " << id << endmsg;
290  }
291  }
292  auto i = m_dependencies.find( id );
293  if ( i == m_dependencies.end() )
294  throw GaudiException( "unknown requested input: " + id.key(), __func__, StatusCode::FAILURE );
295  deps.push_back( i->second );
296  }
297  // insert the (direct) dependencies of 'current' right after 'current', and
298  // interate until done...
299  for ( auto current = deps.begin(); current != deps.end(); ++current ) {
300  if ( std::any_of( std::begin( stoppers ), std::end( stoppers ),
301  [current]( auto& stopper ) { return ( *current )->alg->name() == stopper; } ) ) {
302  continue;
303  }
304  for ( auto* entry : ( *current )->dependsOn ) {
305  if ( std::find( std::next( current ), deps.end(), entry ) != deps.end() ) continue; // already there downstream...
306 
307  auto dup = std::find( deps.begin(), current, entry );
308  // if present upstream, move it downstream. Otherwise, insert
309  // downstream...
310  current = std::prev( dup != current ? std::rotate( dup, std::next( dup ), std::next( current ) )
311  : deps.insert( std::next( current ), entry ) );
312  }
313  }
314  auto range = ( deps | ranges::views::transform( []( auto& i ) { return i->alg; } ) | ranges::views::reverse );
315  return {begin( range ), end( range )};
316 }
317 
320  const std::vector<std::string>& stoppers ) const {
322 
323  auto alg = std::find_if( begin( m_cfnodes ), end( m_cfnodes ),
324  [&]( const AlgEntry& ae ) { return ae.alg->name() == requested.name(); } );
325 
326  if ( alg != end( m_cfnodes ) && alg->alg->type() != requested.type() ) {
327  error() << "requested " << requested << " but have matching name with different type: " << alg->alg->type()
328  << endmsg;
329  }
330  if ( alg == end( m_cfnodes ) ) {
331  auto av = instantiateAndInitializeAlgorithms( {requested.type() + '/' + requested.name()} );
332  assert( av.size() == 1 );
333  m_cfnodes.push_back( std::move( av.front() ) );
334  alg = std::next( m_cfnodes.rbegin() ).base();
335  }
336  assert( alg != end( m_cfnodes ) );
337  assert( alg->alg != nullptr );
338  if ( std::find_if( std::begin( stoppers ), std::end( stoppers ),
339  [&requested]( auto& stopper ) { return requested.name() == stopper; } ) == std::end( stoppers ) ) {
340  result = algorithmsRequiredFor( alg->alg->inputDataObjs(), stoppers );
341  }
342  result.push_back( alg->alg );
343  if ( msgLevel( MSG::DEBUG ) ) {
344  debug() << std::endl << "requested " << requested << " returning " << std::endl << " ";
346  debug(), result, ",\n ",
347  []( auto& os, const Gaudi::Algorithm* a ) -> decltype( auto ) { return os << AlgorithmRepr{*a}; } );
348  debug() << std::endl << endmsg;
349  }
350  return result;
351 }
Definition of the MsgStream class used to transmit messages.
Definition: MsgStream.h:34
StatusCode initialize() override
Definition: Service.cpp:70
Define general base for Gaudi exception.
StatusCode finalize() override
Definition: Service.cpp:174
GAUDI_API const std::string typeinfoName(const std::type_info &)
Get platform independent information about the class type.
Definition: System.cpp:308
StatusCode start() override
Definition: Service.cpp:139
::details::reverse_wrapper< T > reverse(T &&iterable)
Definition: reverse.h:59
T endl(T... args)
The IAlgManager is the interface implemented by the Algorithm Factory in the Application Manager to s...
Definition: IAlgManager.h:37
std::map< DataObjID, AlgEntry * > mapProducers(std::vector< AlgEntry > &algorithms) const
const std::string & type() const
StatusCode finalize() override
StatusCode start() override
T end(T... args)
std::string fullKey() const
Definition: DataObjID.cpp:99
virtual StatusCode sysInitialize()=0
Initialization method invoked by the framework.
T prev(T... args)
STL class.
StatusCode stop() override
#define DECLARE_COMPONENT(type)
T push_back(T... args)
Helper class to parse a string of format "type/name".
T next(T... args)
const std::string & name() const
This class is used for returning status codes from appropriate routines.
Definition: StatusCode.h:61
T str(T... args)
def end
Definition: IOTest.py:123
StatusCode stop() override
Definition: Service.cpp:133
bool isSuccess() const
Definition: StatusCode.h:365
The IAlgorithm is the interface implemented by the Algorithm base class.
Definition: IAlgorithm.h:38
T move(T... args)
Stream & ostream_joiner(Stream &os, Iterator first, Iterator last, Separator sep, OutputElement output=OutputElement{})
Definition: SerializeSTL.h:47
std::vector< Gaudi::Algorithm * > algorithmsRequiredFor(const DataObjIDColl &requested, const std::vector< std::string > &stoppers={}) const override
T insert(T... args)
T find_if(T... args)
T size(T... args)
STL class.
const std::string & key() const
Definition: DataObjID.h:58
T begin(T... args)
T any_of(T... args)
Base class from which all concrete algorithm classes should be derived.
Definition: Algorithm.h:89
T emplace(T... args)
T rotate(T... args)
appMgr
Definition: IOTest.py:103
string s
Definition: gaudirun.py:328
constexpr static const auto FAILURE
Definition: StatusCode.h:101
const Gaudi::Algorithm & parent
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.
std::vector< AlgEntry > instantiateAndInitializeAlgorithms(const std::vector< std::string > &names) const
T sort(T... args)
decltype(auto) range(Args &&... args)
Zips multiple containers together to form a single range.
StatusCode initialize() override
bool isFailure() const
Definition: StatusCode.h:145
AttribStringParser::Iterator begin(const AttribStringParser &parser)
STL class.
MsgStream & endmsg(MsgStream &s)
MsgStream Modifier: endmsg. Calls the output method of the MsgStream.
Definition: MsgStream.h:202
Gaudi::Algorithm * alg
const std::string & name() const override
The identifying name of the algorithm object.
Definition: Algorithm.cpp:549
T reserve(T... args)
std::ostream & operator<<(std::ostream &str, const GaudiAlg::ID &id)
Operator overloading for ostream.
Definition: GaudiHistoID.h:142
T emplace_back(T... args)