21#include "GaudiKernel/EventContext.h"
22#include "GaudiKernel/EventIDBase.h"
23#include "GaudiKernel/IAlgManager.h"
24#include "GaudiKernel/IAlgorithm.h"
25#include "GaudiKernel/ThreadLocalContext.h"
36 declareProperty(
"EvtStore",
47 "No sequences configured; the server would have nothing to "
48 "offer. Set the Sequences property.");
49 return StatusCode::FAILURE;
52 const auto known = [
this](
const std::string& sequence) {
57 if (!known(sequence)) {
58 ATH_MSG_ERROR(
"OutputKeys names sequence '{}', which is not in Sequences",
60 return StatusCode::FAILURE;
64 if (!known(sequence)) {
65 ATH_MSG_ERROR(
"ReplyKeys names sequence '{}', which is not in Sequences",
67 return StatusCode::FAILURE;
71 if (!keys.empty() &&
m_replyKeys.value().count(sequence) == 0) {
72 ATH_MSG_ERROR(
"Sequence '{}' declares outputs but no entry in ReplyKeys",
74 return StatusCode::FAILURE;
78 std::ostringstream
menu;
80 menu << (
menu.tellp() == 0 ?
"" :
", ") << sequence;
85 return StatusCode::SUCCESS;
106 return StatusCode::SUCCESS;
112 m_server = std::make_unique<Server>();
114 std::vector<SequenceInfo>
menu;
118 info.name = sequence;
122 const auto advertise = [](
const std::vector<std::string>& specs,
123 std::vector<BoundaryInfo>& out) {
124 for (
const std::string& spec : specs) {
126 if (boundary.has_value()) {
127 out.push_back(std::move(*boundary));
131 if (
auto inputs =
m_inputKeys.value().find(sequence);
133 advertise(inputs->second, info.inputs);
137 advertise(outputs->second, info.outputs);
139 menu.push_back(std::move(info));
143 const int boundPort =
150 return StatusCode::FAILURE;
155 const std::string temporary =
m_portFile +
".tmp";
157 std::ofstream out(temporary);
158 out << boundPort <<
'\n';
160 if (std::rename(temporary.c_str(),
m_portFile.value().c_str()) != 0) {
162 return StatusCode::FAILURE;
165 return StatusCode::SUCCESS;
170 return StatusCode::SUCCESS;
174 const size_t limit = maxevt < 0 ? std::numeric_limits<size_t>::max()
175 :
static_cast<size_t>(maxevt);
181 std::optional<Clock::time_point> firstAccepted;
184 const auto canAccept = [&] {
194 bool progressed =
false;
196 while (canAccept()) {
198 std::unique_ptr<Server::Job> job;
209 if (!firstAccepted) {
210 firstAccepted = Clock::now();
231 const auto nothingToDo = [&] {
245 ATH_MSG_INFO(
"Request loop finished: {} request(s) accepted, {} event(s) run",
250 const double seconds =
251 std::chrono::duration<double>(Clock::now() - *firstAccepted).count();
254 "Throughput: {} request(s) in {} s = {} request/s over {} slot(s)",
262 const std::string report =
m_server->timingReport();
263 if (!report.empty()) {
270 return StatusCode::SUCCESS;
319 std::deque<std::unique_ptr<Server::Job>> leftover;
320 std::deque<Finished> uncollected;
326 const std::string msgStr{
"the server stopped before this request was served"};
327 for (
const std::unique_ptr<Server::Job>& job : leftover) {
329 ATH_MSG_WARNING(
"Request {} ({}) was still queued when the loop stopped",
330 job->request.requestId, job->request.sequence);
335 for (
const Finished& finished : uncollected) {
341 std::unique_ptr<Server::Job> job;
373 EventContext* finished =
nullptr;
375 std::this_thread::sleep_for(std::chrono::milliseconds(1));
378 const Clock::time_point at = Clock::now();
389std::vector<RemoteExecHiveEventLoopMgr::Finished>
391 std::vector<Finished> finished;
407 request = std::move(job->request);
409 job->timing->taken = Clock::now();
422 diagnostics =
"no sequence named '" + request.
sequence +
"'";
426 if (
const std::vector<std::string> absent = request.
eventId.
missing();
428 std::ostringstream text;
429 text <<
"request carries no usable event identity; missing ";
430 for (
size_t i = 0; i < absent.size(); ++i) {
431 text << (i == 0 ?
"" :
", ") << absent[i];
433 diagnostics = text.str();
438 std::vector<BoundaryInfo> boundaries;
440 for (
const std::string& spec : declared->second) {
442 if (boundary.has_value()) {
443 boundaries.push_back(std::move(*boundary));
448 for (
auto payload = request.
inputs.begin(); payload != request.
inputs.end();
450 if (payload->key.empty()) {
451 diagnostics =
"payload with an empty StoreGate key";
455 if (payload->encoding.empty()) {
457 std::format(
"payload '{}' carries no encoding", payload->key);
461 if (std::any_of(request.
inputs.begin(), payload,
462 [&payload](
const Payload& earlier) {
463 return earlier.key == payload->key;
466 std::format(
"payload '{}' is supplied more than once", payload->key);
470 const auto boundary =
471 std::find_if(boundaries.begin(), boundaries.end(),
473 return candidate.key == payload->key;
475 if (boundary == boundaries.end()) {
476 diagnostics = std::format(
"sequence '{}' declares no input '{}'",
481 if (payload->encoding != boundary->encoding ||
482 payload->schema != boundary->schema) {
483 diagnostics = std::format(
484 "input '{}' arrived as {} [{}] but sequence '{}' declares {} [{}]",
485 payload->key, payload->schema, payload->encoding, request.
sequence,
486 boundary->schema, boundary->encoding);
492 const auto supplied = std::find_if(
494 [&boundary](
const Payload& p) { return p.key == boundary.key; });
495 if (supplied == request.
inputs.end()) {
496 diagnostics = std::format(
"sequence '{}' requires input '{}'",
507 std::string diagnostics;
511 return StatusCode::SUCCESS;
517 "could not allocate an event slot");
518 return StatusCode::SUCCESS;
520 const size_t slot = ctx.slot();
523 ctx.setEventID(EventIDBase(
524 *
id.runNumber,
static_cast<EventIDBase::event_number_t
>(*
id.eventNumber),
525 *
id.timeStamp,
id.timeStampNsOffset, *
id.lumiBlock,
id.bunchCrossingId));
527 Gaudi::Hive::setCurrentContext(ctx);
530 if (
m_eventStore->record(std::make_unique<EventContext>(ctx),
"EventContext")
537 ->record(std::make_unique<RequestDescriptor>(
539 std::move(request.
inputs)),
542 ATH_MSG_ERROR(
"Could not prepare slot {} for request {}", slot,
545 "could not prepare the event store");
548 return StatusCode::SUCCESS;
551 if (job && job->timing) {
552 job->timing->recorded = Clock::now();
556 entry.request = std::move(request);
557 entry.job = std::move(job);
559 entry.hasDeadline =
true;
566 "RemoteExec request {} ({}) dispatched to slot {} as run {} lb {} event "
568 entry.request.requestId, entry.request.sequence, slot, *
id.runNumber,
569 *
id.lumiBlock, *
id.eventNumber);
571 const uint64_t requestId = entry.request.requestId;
572 auto [placed, inserted] =
m_inFlight.emplace(slot, std::move(entry));
575 return StatusCode::FAILURE;
581 "could not submit the event",
587 Gaudi::Hive::setCurrentContext(EventContext());
588 return StatusCode::SUCCESS;
591 if (placed->second.job && placed->second.job->timing) {
592 placed->second.job->timing->pushed = Clock::now();
596 const std::lock_guard<std::mutex>
lock(m_pendingMutex);
597 ++m_awaitingCompletion;
599 m_inFlightCv.notify_one();
602 Gaudi::Hive::setCurrentContext(EventContext());
603 return StatusCode::SUCCESS;
607 if (finished.
ctx ==
nullptr) {
609 return StatusCode::FAILURE;
611 const std::unique_ptr<EventContext> ctx(finished.
ctx);
613 const size_t slot = ctx->slot();
616 ATH_MSG_FATAL(
"Slot {} finished but no request was in flight on it", slot);
617 return StatusCode::FAILURE;
620 if (entry->second.job && entry->second.job->timing) {
621 entry->second.job->timing->finished = finished.
at;
625 if (
sc.isFailure()) {
627 "could not finish the event",
629 entry->second.request.requestId});
632 m_inFlight.erase(entry);
634 Gaudi::Hive::setCurrentContext(EventContext());
643 return StatusCode::SUCCESS;
649 reply.
requestId = entry.request.requestId;
651 if (
m_aess->eventStatus(ctx) != EventStatus::Success) {
652 std::ostringstream diagnostics;
653 diagnostics <<
"sequence '" << entry.request.sequence <<
"' failed ("
654 <<
m_aess->eventStatus(ctx) <<
")";
656 if (!failed.empty()) {
657 diagnostics <<
": " << failed;
664 const std::string replyKey =
replyKeyFor(entry.request.sequence);
665 if (replyKey.empty()) {
671 if (
m_whiteboard->selectStore(ctx.slot()).isFailure()) {
674 "could not select the event slot to read the reply from";
679 if (
m_eventStore->retrieve(staged, replyKey).isFailure() ||
683 "sequence '{}' staged no reply under '{}'; did its gate select it?",
684 entry.request.sequence, replyKey);
689 reply.
requestId = entry.request.requestId;
698 const Clock::time_point now = Clock::now();
700 if (entry.answered || !entry.hasDeadline || now < entry.deadline) {
705 "Request {} ({}) on slot {} exceeded {} s; answering the client now "
706 "and releasing the slot when the event finishes",
707 entry.request.requestId, entry.request.sequence, slot,
709 std::ostringstream diagnostics;
710 diagnostics <<
"the server did not finish within "
715 respond(entry, std::move(reply));
720 if (entry.answered) {
723 entry.answered =
true;
724 reply.
requestId = entry.request.requestId;
728 "RemoteExec request {} ({}) -> {}{}", reply.
requestId,
741 if (entry.job->timing) {
742 entry.job->timing->replied = Clock::now();
744 entry.job->reply.set_value(std::move(reply));
749 const ExecuteRequest& request,
const std::unique_ptr<Server::Job>& job,
753 !diagnostics.empty() ?
" : " + diagnostics :
"");
759 job->reply.set_value(std::move(reply));
764 const EventContext& ctx) {
765 SmartIF<IAlgManager> algMgr = serviceLocator()->as<IAlgManager>();
770 std::ostringstream names;
771 for (IAlgorithm* alg : algMgr->getAlgorithms()) {
772 if (alg ==
nullptr) {
776 const AlgExecStateRef state =
m_aess->algExecState(alg, ctx);
777 if (state.state() == AlgExecState::State::Done &&
778 state.execStatus().isFailure()) {
779 names << (names.tellp() == 0 ?
"" :
", ") << alg->name();
787 const std::string& sequence)
const {
788 const auto found =
m_replyKeys.value().find(sequence);
789 return found ==
m_replyKeys.value().end() ? std::string{} : found->second;
793 const std::string& text) {
795 msg(
static_cast<MSG::Level
>(level)) <<
"[gRPC] " << text <<
endmsg;
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_DEBUG(x,...)
#define ATH_MSG_ERROR(x,...)
#define ATH_MSG_ALWAYS(x,...)
#define ATH_MSG_WARNING(x,...)
#define ATH_MSG_INFO(x,...)
#define ATH_MSG_FATAL(x,...)
Assign a CLID to EventContext.
virtual void lock()=0
Interface to allow an object to lock itself when made const in SG.
Multi-threaded event loop manager driven by RPC requests.
The reply, written by OutputCnvAlg onto SG.
The request, read by InputCnvAlg from SG.
virtual ~RemoteExecHiveEventLoopMgr() override
Take
Where the next request came from.
@ None
none available right now
@ Stopped
no more requests will ever come
StatusCode eventFinished(const EventContext &ctx) override
Process an event's result and decide whether the driving loop may continue.
std::mutex m_messageMutex
std::string replyKeyFor(const std::string &sequence) const
The reply key of sequence, or an empty string if it declares none.
Gaudi::Property< int > m_port
std::condition_variable m_pending
loop waits here
void inputLoop()
Loop and wait for incoming job.
std::map< size_t, InFlight > m_inFlight
keyed by whiteboard slot
StatusCode complete(const Finished &finished)
Read the result of one finished event and release its slot.
Gaudi::Property< std::string > m_address
std::condition_variable m_incomingRoom
input thread waits here
void respond(InFlight &entry, ExecuteReply reply)
Reply to the request.
void respondDirect(const ExecuteRequest &request, const std::unique_ptr< Server::Job > &job, AthRemoteExec::Status status, const std::string &diagnostics)
Reply to the request that never got assigned to slot.
std::mutex m_pendingMutex
Gaudi::Property< std::map< std::string, std::vector< std::string > > > m_inputKeys
StatusCode dispatch(ExecuteRequest request, std::unique_ptr< Server::Job > job)
Give a request a slot and push it to the scheduler.
Gaudi::Property< int > m_maxMessageBytes
void expireDeadlines()
Reply to all request that passed their deadline.
Gaudi::Property< bool > m_reportTiming
virtual Take takeRequest(ExecuteRequest &request, std::unique_ptr< Server::Job > &job)
Take the next request from the incoming event queue.
void drainPending()
Answer to anything that the loop did not manage to finish.
virtual StatusCode startServing()
Create and start the server.
RemoteExecHiveEventLoopMgr(const std::string &name, ISvcLocator *svcLoc)
void startHelpers()
Starts input/output loops.
std::unique_ptr< Server > m_server
void stopHelpers()
Stops input/output loops.
Gaudi::Property< std::map< std::string, std::vector< std::string > > > m_outputKeys
std::condition_variable m_inFlightCv
output thread waits here
virtual StatusCode initialize() override
implementation of IAppMgrUI::initalize
std::deque< std::unique_ptr< Server::Job > > m_incoming
Gaudi::Property< std::string > m_requestKey
ExecuteReply buildReply(const EventContext &ctx, const InFlight &entry)
Turn a finished event into the reply for its request.
AthRemoteExec::Status validate(const ExecuteRequest &request, std::string &diagnostics) const
Reject requests that cannot possibly run, before a slot is spent on them.
virtual StatusCode stopRun() override
Ask the loop to stop accepting work and drain what is in flight.
std::vector< Finished > takeFinished()
Take whatever the output thread has collected from finished event queue.
Gaudi::Property< double > m_requestTimeout
std::thread m_inputThread
void outputLoop()
Loop and wait for finished job.
Gaudi::Property< size_t > m_queueLimit
Gaudi::Property< std::vector< std::string > > m_sequences
virtual StatusCode finalize() override
implementation of IAppMgrUI::finalize
std::thread m_outputThread
Gaudi::Property< std::string > m_portFile
void serverMessage(Server::Level level, const std::string &text)
Thread-safe log sink handed to the RPC server.
Gaudi::Property< unsigned int > m_pollInterval
std::deque< Finished > m_finishedEvents
size_t m_awaitingCompletion
Gaudi::Property< std::map< std::string, std::string > > m_replyKeys
std::atomic< bool > m_stopRequested
virtual StatusCode nextEvent(int maxevt) override
Serve requests.
std::string failedAlgorithms(const EventContext &ctx)
Names of the algorithms that failed in ctx. For the reply diagnostics.
ExecuteReply takeReply()
Hand the reply over, leaving this object empty.
Level
Severity levels, matching MSG::Level so the funnel can forward them.
virtual StatusCode initialize() override
implementation of IAppMgrUI::initalize
SmartIF< IHiveWhiteBoard > m_whiteboard
Reference to the Whiteboard interface.
SmartIF< IAlgExecStateSvc > m_aess
Reference to the Algorithm Execution State Svc.
virtual const std::string & name() const override
std::string m_schedulerName
Name of the scheduler to be used.
EventContext allocateEventContext(size_t eventNumber)
StatusCode submitEvent(EventContext &ctx)
Submit a recorded context; the scheduler receives its own copy.
StoreGateSvc_t m_eventStore
Reference to StoreGateSvc;.
AthenaHiveEventLoopMgr(const std::string &nam, ISvcLocator *svcLoc)
Standard Constructor.
virtual StatusCode finalize() override
implementation of IAppMgrUI::finalize
bool m_scheduledStop
Scheduled stop of event processing.
StatusCode finishEvent(const EventContext &ctx)
Finish one scheduler-returned event on the driving thread.
SmartIF< IScheduler > m_schedulerSvc
A shortcut for the scheduler.
void setConditionsRun(EventIDBase::number_type conditionsRun)
std::optional< BoundaryInfo > parseBoundary(std::string_view spec)
Parse "key#encoding#schema" into BoundaryInfo.
constexpr std::string_view toString(Status status)
String representation of Status enum.
std::string describe(const Payload &payload)
Human-readable rendering of a payload, for log messages.
const ExtendedEventContext & getExtendedEventContext(const EventContext &ctx)
Retrieve an extended context from a context object.
Information what kind of data is expected, in which RPC protocol, and the meaning of the data.
An unique event identifier.
std::vector< std::string > missing() const
Names of the required fields that are missing.
std::vector< Payload > outputs
std::string sequence
fragment name, e.g. "RemoteExecSeqSum"
uint64_t requestId
client correlation id, echoed back
std::vector< Payload > inputs
The actual data that is sent via RPC.
A finished event, from the scheduler's point of view.
A request that has been given a slot and handed to the scheduler.
Information about what sequence the server is capable of executing.