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