Project
Loading...
Searching...
No Matches
DataProcessingDevice.cxx
Go to the documentation of this file.
1// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
2// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
3// All rights not expressly granted are reserved.
4//
5// This software is distributed under the terms of the GNU General Public
6// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
7//
8// In applying this license CERN does not waive the privileges and immunities
9// granted to it by virtue of its status as an Intergovernmental Organization
10// or submit itself to any jurisdiction.
13#include <atomic>
33#include "Framework/InputSpan.h"
34#if defined(__APPLE__) || defined(NDEBUG)
35#define O2_SIGNPOST_IMPLEMENTATION
36#endif
37#include "Framework/Signpost.h"
50
51#include "DecongestionService.h"
54#include "DataRelayerHelpers.h"
55#include "Headers/DataHeader.h"
57
58#include <Framework/Tracing.h>
59
60#include <fairmq/Parts.h>
61#include <fairmq/Socket.h>
62#include <fairmq/ProgOptions.h>
63#include <fairmq/shmem/Message.h>
64#include <Configuration/ConfigurationInterface.h>
65#include <Configuration/ConfigurationFactory.h>
66#include <Monitoring/Monitoring.h>
67#include <TMessage.h>
68#include <TClonesArray.h>
69
70#include <fmt/ostream.h>
71#include <algorithm>
72#include <vector>
73#include <numeric>
74#include <memory>
75#include <uv.h>
76#include <execinfo.h>
77#include <sstream>
78#include <boost/property_tree/json_parser.hpp>
79
80// Formatter to avoid having to rewrite the ostream operator for the enum
81namespace fmt
82{
83template <>
86} // namespace fmt
87
88// A log to use for general device logging
90// A log to use for general device logging
92// Special log to keep track of the lifetime of the parts
94// Stream which keeps track of the calibration lifetime logic
96// Special log to track the async queue behavior
98// Special log to track the forwarding requests
100// Special log to track CCDB related requests
102// Special log to track task scheduling
104
105using namespace o2::framework;
106using ConfigurationInterface = o2::configuration::ConfigurationInterface;
108
109constexpr int DEFAULT_MAX_CHANNEL_AHEAD = 128;
110
111namespace o2::framework
112{
113
114template <>
118
122{
123 auto* state = (DeviceState*)handle->data;
124 state->loopReason |= DeviceState::TIMER_EXPIRED;
125}
126
128{
129 auto* state = (DeviceState*)s->data;
131}
132
133DeviceSpec const& getRunningDevice(RunningDeviceRef const& running, ServiceRegistryRef const& services)
134{
135 auto& devices = services.get<o2::framework::RunningWorkflowInfo const>().devices;
136 return devices[running.index];
137}
138
144
146 : mRunningDevice{running},
147 mConfigRegistry{nullptr},
148 mServiceRegistry{registry}
149{
150 GetConfig()->Subscribe<std::string>("dpl", [&registry = mServiceRegistry](const std::string& key, std::string value) {
151 if (key == "cleanup") {
153 auto& deviceState = ref.get<DeviceState>();
154 int64_t cleanupCount = deviceState.cleanupCount.load();
155 int64_t newCleanupCount = std::stoll(value);
156 if (newCleanupCount <= cleanupCount) {
157 return;
158 }
159 deviceState.cleanupCount.store(newCleanupCount);
160 for (auto& info : deviceState.inputChannelInfos) {
161 fair::mq::Parts parts;
162 while (info.channel->Receive(parts, 0)) {
163 LOGP(debug, "Dropping {} parts", parts.Size());
164 if (parts.Size() == 0) {
165 break;
166 }
167 }
168 }
169 }
170 });
171
172 std::function<void(const fair::mq::State)> stateWatcher = [this, &registry = mServiceRegistry](const fair::mq::State state) -> void {
174 auto& deviceState = ref.get<DeviceState>();
175 auto& control = ref.get<ControlService>();
176 auto& callbacks = ref.get<CallbackService>();
177 control.notifyDeviceState(fair::mq::GetStateName(state));
179
180 if (deviceState.nextFairMQState.empty() == false) {
181 auto state = deviceState.nextFairMQState.back();
182 (void)this->ChangeState(state);
183 deviceState.nextFairMQState.pop_back();
184 }
185 };
186
187 // 99 is to execute DPL callbacks last
188 this->SubscribeToStateChange("99-dpl", stateWatcher);
189
190 auto* poolSizeEnv = getenv("DPL_THREADPOOL_SIZE");
191 // 0 (or unset): synchronous execution on the main thread.
192 // N > 0: N concurrent async streams; I/O runs on the main thread while
193 // computation runs on N pool threads.
194 size_t numStreams = poolSizeEnv ? std::max(0, std::atoi(poolSizeEnv)) : 0;
195 mStreams.resize(std::max(numStreams, 1UL));
196 mHandles.resize(std::max(numStreams, 1UL));
197
198 ServiceRegistryRef ref{mServiceRegistry};
199
200 mAwakeHandle = (uv_async_t*)malloc(sizeof(uv_async_t));
201 auto& state = ref.get<DeviceState>();
202 assert(state.loop);
203 int res = uv_async_init(state.loop, mAwakeHandle, on_communication_requested);
204 mAwakeHandle->data = &state;
205 if (res < 0) {
206 LOG(error) << "Unable to initialise subscription";
207 }
208
210 SubscribeToNewTransition("dpl", [wakeHandle = mAwakeHandle](fair::mq::Transition t) {
211 int res = uv_async_send(wakeHandle);
212 if (res < 0) {
213 LOG(error) << "Unable to notify subscription";
214 }
215 LOG(debug) << "State transition requested";
216 });
217}
218
219// Callback to execute the processing. Receives and relays data (doPrepare)
220// happens on the main thread before this is queued, so we only dispatch here.
221void run_callback(uv_work_t* handle)
222{
223 auto* task = (TaskStreamInfo*)handle->data;
224 auto ref = ServiceRegistryRef{*task->registry, ServiceRegistry::globalStreamSalt(task->id.index + 1)};
225 // We create a new signpost interval for this specific data processor. Same id, same data processor.
226 auto& dataProcessorContext = ref.get<DataProcessorContext>();
227 O2_SIGNPOST_ID_FROM_POINTER(sid, device, &dataProcessorContext);
228 O2_SIGNPOST_START(device, sid, "run_callback", "Starting run callback on stream %d", task->id.index);
230 O2_SIGNPOST_END(device, sid, "run_callback", "Done processing data for stream %d", task->id.index);
231}
232
233// Once the processing in a thread is done, this is executed on the main thread.
234void run_completion(uv_work_t* handle, int status)
235{
236 auto* task = (TaskStreamInfo*)handle->data;
237 // Notice that the completion, while running on the main thread, still
238 // has a salt which is associated to the actual stream which was doing the computation
239 auto ref = ServiceRegistryRef{*task->registry, ServiceRegistry::globalStreamSalt(task->id.index + 1)};
240 auto& state = ref.get<DeviceState>();
241 auto& quotaEvaluator = ref.get<ComputingQuotaEvaluator>();
242
243 using o2::monitoring::Metric;
244 using o2::monitoring::Monitoring;
245 using o2::monitoring::tags::Key;
246 using o2::monitoring::tags::Value;
247
248 static std::function<void(ComputingQuotaOffer const&, ComputingQuotaStats&)> reportConsumedOffer = [ref](ComputingQuotaOffer const& accumulatedConsumed, ComputingQuotaStats& stats) {
249 auto& dpStats = ref.get<DataProcessingStats>();
250 stats.totalConsumedBytes += accumulatedConsumed.sharedMemory;
251 // For now we give back the offer if we did not use it completely.
252 // In principle we should try to run until the offer is fully consumed.
253 stats.totalConsumedTimeslices += std::min<int64_t>(accumulatedConsumed.timeslices, 1);
254
255 dpStats.updateStats({static_cast<short>(ProcessingStatsId::SHM_OFFER_BYTES_CONSUMED), DataProcessingStats::Op::Set, stats.totalConsumedBytes});
256 dpStats.updateStats({static_cast<short>(ProcessingStatsId::TIMESLICE_OFFER_NUMBER_CONSUMED), DataProcessingStats::Op::Set, stats.totalConsumedTimeslices});
257 dpStats.processCommandQueue();
258 assert(stats.totalConsumedBytes == dpStats.metrics[(short)ProcessingStatsId::SHM_OFFER_BYTES_CONSUMED]);
259 assert(stats.totalConsumedTimeslices == dpStats.metrics[(short)ProcessingStatsId::TIMESLICE_OFFER_NUMBER_CONSUMED]);
260 };
261
262 static std::function<void(ComputingQuotaOffer const&, ComputingQuotaStats const&)> reportExpiredOffer = [ref](ComputingQuotaOffer const& offer, ComputingQuotaStats const& stats) {
263 auto& dpStats = ref.get<DataProcessingStats>();
264 dpStats.updateStats({static_cast<short>(ProcessingStatsId::RESOURCE_OFFER_EXPIRED), DataProcessingStats::Op::Set, stats.totalExpiredOffers});
265 dpStats.updateStats({static_cast<short>(ProcessingStatsId::ARROW_BYTES_EXPIRED), DataProcessingStats::Op::Set, stats.totalExpiredBytes});
266 dpStats.updateStats({static_cast<short>(ProcessingStatsId::TIMESLICE_NUMBER_EXPIRED), DataProcessingStats::Op::Set, stats.totalExpiredTimeslices});
267 dpStats.processCommandQueue();
268 };
269
270 for (auto& consumer : state.offerConsumers) {
271 quotaEvaluator.consume(task->id.index, consumer, reportConsumedOffer);
272 }
273 state.offerConsumers.clear();
274 quotaEvaluator.handleExpired(reportExpiredOffer);
275 quotaEvaluator.dispose(task->id.index);
276 task->running = false;
277}
278
279// Context for polling
281 enum struct PollerState : char { Stopped,
283 Connected,
284 Suspended };
285 char const* name = nullptr;
286 uv_loop_t* loop = nullptr;
288 DeviceState* state = nullptr;
289 fair::mq::Socket* socket = nullptr;
291 int fd = -1;
292 bool read = true;
294};
295
296void on_socket_polled(uv_poll_t* poller, int status, int events)
297{
298 auto* context = (PollerContext*)poller->data;
299 assert(context);
300 O2_SIGNPOST_ID_FROM_POINTER(sid, sockets, poller);
301 context->state->loopReason |= DeviceState::DATA_SOCKET_POLLED;
302 switch (events) {
303 case UV_READABLE: {
304 O2_SIGNPOST_EVENT_EMIT(sockets, sid, "socket_state", "Data pending on socket for channel %{public}s", context->name);
305 context->state->loopReason |= DeviceState::DATA_INCOMING;
306 } break;
307 case UV_WRITABLE: {
308 O2_SIGNPOST_END(sockets, sid, "socket_state", "Socket connected for channel %{public}s", context->name);
309 if (context->read) {
310 O2_SIGNPOST_START(sockets, sid, "socket_state", "Socket connected for read in context %{public}s", context->name);
311 uv_poll_start(poller, UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED, &on_socket_polled);
312 context->state->loopReason |= DeviceState::DATA_CONNECTED;
313 } else {
314 O2_SIGNPOST_START(sockets, sid, "socket_state", "Socket connected for write for channel %{public}s", context->name);
315 context->state->loopReason |= DeviceState::DATA_OUTGOING;
316 // If the socket is writable, fairmq will handle the rest, so we can stop polling and
317 // just wait for the disconnect.
318 uv_poll_start(poller, UV_DISCONNECT | UV_PRIORITIZED, &on_socket_polled);
319 }
320 context->pollerState = PollerContext::PollerState::Connected;
321 } break;
322 case UV_DISCONNECT: {
323 O2_SIGNPOST_END(sockets, sid, "socket_state", "Socket disconnected in context %{public}s", context->name);
324 } break;
325 case UV_PRIORITIZED: {
326 O2_SIGNPOST_EVENT_EMIT(sockets, sid, "socket_state", "Socket prioritized for context %{public}s", context->name);
327 } break;
328 }
329 // We do nothing, all the logic for now stays in DataProcessingDevice::doRun()
330}
331
332void on_out_of_band_polled(uv_poll_t* poller, int status, int events)
333{
334 O2_SIGNPOST_ID_FROM_POINTER(sid, sockets, poller);
335 auto* context = (PollerContext*)poller->data;
336 context->state->loopReason |= DeviceState::OOB_ACTIVITY;
337 if (status < 0) {
338 LOGP(fatal, "Error while polling {}: {}", context->name, status);
339 uv_poll_start(poller, UV_WRITABLE, &on_out_of_band_polled);
340 }
341 switch (events) {
342 case UV_READABLE: {
343 O2_SIGNPOST_EVENT_EMIT(sockets, sid, "socket_state", "Data pending on socket for channel %{public}s", context->name);
344 context->state->loopReason |= DeviceState::DATA_INCOMING;
345 assert(context->channelInfo);
346 context->channelInfo->readPolled = true;
347 } break;
348 case UV_WRITABLE: {
349 O2_SIGNPOST_END(sockets, sid, "socket_state", "OOB socket connected for channel %{public}s", context->name);
350 if (context->read) {
351 O2_SIGNPOST_START(sockets, sid, "socket_state", "OOB socket connected for read in context %{public}s", context->name);
352 uv_poll_start(poller, UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED, &on_out_of_band_polled);
353 } else {
354 O2_SIGNPOST_START(sockets, sid, "socket_state", "OOB socket connected for write for channel %{public}s", context->name);
355 context->state->loopReason |= DeviceState::DATA_OUTGOING;
356 }
357 } break;
358 case UV_DISCONNECT: {
359 O2_SIGNPOST_END(sockets, sid, "socket_state", "OOB socket disconnected in context %{public}s", context->name);
360 uv_poll_start(poller, UV_WRITABLE, &on_out_of_band_polled);
361 } break;
362 case UV_PRIORITIZED: {
363 O2_SIGNPOST_EVENT_EMIT(sockets, sid, "socket_state", "OOB socket prioritized for context %{public}s", context->name);
364 } break;
365 }
366 // We do nothing, all the logic for now stays in DataProcessingDevice::doRun()
367}
368
377{
378 auto ref = ServiceRegistryRef{mServiceRegistry};
379 auto& context = ref.get<DataProcessorContext>();
380 auto& spec = getRunningDevice(mRunningDevice, ref);
381
382 O2_SIGNPOST_ID_FROM_POINTER(cid, device, &context);
383 O2_SIGNPOST_START(device, cid, "Init", "Entering Init callback.");
384 context.statelessProcess = spec.algorithm.onProcess;
385 context.statefulProcess = nullptr;
386 context.error = spec.algorithm.onError;
387 context.initError = spec.algorithm.onInitError;
388
389 auto configStore = DeviceConfigurationHelpers::getConfiguration(mServiceRegistry, spec.name.c_str(), spec.options);
390 if (configStore == nullptr) {
391 std::vector<std::unique_ptr<ParamRetriever>> retrievers;
392 retrievers.emplace_back(std::make_unique<FairOptionsRetriever>(GetConfig()));
393 configStore = std::make_unique<ConfigParamStore>(spec.options, std::move(retrievers));
394 configStore->preload();
395 configStore->activate();
396 }
397
398 using boost::property_tree::ptree;
399
401 for (auto& entry : configStore->store()) {
402 std::stringstream ss;
403 std::string str;
404 if (entry.second.empty() == false) {
405 boost::property_tree::json_parser::write_json(ss, entry.second, false);
406 str = ss.str();
407 } else {
408 str = entry.second.get_value<std::string>();
409 }
410 std::string configString = fmt::format("[CONFIG] {}={} 1 {}", entry.first, str, configStore->provenance(entry.first.c_str())).c_str();
411 mServiceRegistry.get<DriverClient>(ServiceRegistry::globalDeviceSalt()).tell(configString.c_str());
412 }
413
414 mConfigRegistry = std::make_unique<ConfigParamRegistry>(std::move(configStore));
415
416 // Setup the error handlers for init
417 if (context.initError) {
418 context.initErrorHandling = [&errorCallback = context.initError,
419 &serviceRegistry = mServiceRegistry](RuntimeErrorRef e) {
423 auto& context = ref.get<DataProcessorContext>();
424 auto& err = error_from_ref(e);
425 O2_SIGNPOST_ID_FROM_POINTER(cid, device, &context);
426 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid, "Init", "Exception caught while in Init: %{public}s. Invoking errorCallback.", err.what);
427 BacktraceHelpers::demangled_backtrace_symbols(err.backtrace, err.maxBacktrace, STDERR_FILENO);
428 auto& stats = ref.get<DataProcessingStats>();
430 InitErrorContext errorContext{ref, e};
431 errorCallback(errorContext);
432 };
433 } else {
434 context.initErrorHandling = [&serviceRegistry = mServiceRegistry](RuntimeErrorRef e) {
435 auto& err = error_from_ref(e);
439 auto& context = ref.get<DataProcessorContext>();
440 O2_SIGNPOST_ID_FROM_POINTER(cid, device, &context);
441 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid, "Init", "Exception caught while in Init: %{public}s. Exiting with 1.", err.what);
442 BacktraceHelpers::demangled_backtrace_symbols(err.backtrace, err.maxBacktrace, STDERR_FILENO);
443 auto& stats = ref.get<DataProcessingStats>();
445 exit(1);
446 };
447 }
448
449 context.expirationHandlers.clear();
450 context.init = spec.algorithm.onInit;
451 if (context.init) {
452 static bool noCatch = getenv("O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv("O2_NO_CATCHALL_EXCEPTIONS"), "0");
453 InitContext initContext{*mConfigRegistry, mServiceRegistry};
454
455 if (noCatch) {
456 try {
457 context.statefulProcess = context.init(initContext);
459 if (context.initErrorHandling) {
460 (context.initErrorHandling)(e);
461 }
462 }
463 } else {
464 try {
465 context.statefulProcess = context.init(initContext);
466 } catch (std::exception& ex) {
470 auto e = runtime_error(ex.what());
471 (context.initErrorHandling)(e);
473 (context.initErrorHandling)(e);
474 }
475 }
476 }
477 auto& state = ref.get<DeviceState>();
478 state.inputChannelInfos.resize(spec.inputChannels.size());
482 int validChannelId = 0;
483 for (size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
484 auto& name = spec.inputChannels[ci].name;
485 if (name.find(spec.channelPrefix + "from_internal-dpl-clock") == 0) {
486 state.inputChannelInfos[ci].state = InputChannelState::Pull;
487 state.inputChannelInfos[ci].id = {ChannelIndex::INVALID};
488 validChannelId++;
489 } else {
490 state.inputChannelInfos[ci].id = {validChannelId++};
491 }
492 }
493
494 // Invoke the callback policy for this device.
495 if (spec.callbacksPolicy.policy != nullptr) {
496 InitContext initContext{*mConfigRegistry, mServiceRegistry};
497 spec.callbacksPolicy.policy(mServiceRegistry.get<CallbackService>(ServiceRegistry::globalDeviceSalt()), initContext);
498 }
499
500 // Services which are stream should be initialised now
501 auto* options = GetConfig();
502 for (size_t si = 0; si < mStreams.size(); ++si) {
504 mServiceRegistry.lateBindStreamServices(state, *options, streamSalt);
505 }
506 O2_SIGNPOST_END(device, cid, "Init", "Exiting Init callback.");
507}
508
509void on_signal_callback(uv_signal_t* handle, int signum)
510{
511 O2_SIGNPOST_ID_FROM_POINTER(sid, device, handle);
512 O2_SIGNPOST_START(device, sid, "signal_state", "Signal %d received.", signum);
513
514 auto* registry = (ServiceRegistry*)handle->data;
515 if (!registry) {
516 O2_SIGNPOST_END(device, sid, "signal_state", "No registry active. Ignoring signal.");
517 return;
518 }
519 ServiceRegistryRef ref{*registry};
520 auto& state = ref.get<DeviceState>();
521 auto& quotaEvaluator = ref.get<ComputingQuotaEvaluator>();
522 auto& stats = ref.get<DataProcessingStats>();
524 size_t ri = 0;
525 while (ri != quotaEvaluator.mOffers.size()) {
526 auto& offer = quotaEvaluator.mOffers[ri];
527 // We were already offered some sharedMemory, so we
528 // do not consider the offer.
529 // FIXME: in principle this should account for memory
530 // available and being offered, however we
531 // want to get out of the woods for now.
532 if (offer.valid && offer.sharedMemory != 0) {
533 O2_SIGNPOST_END(device, sid, "signal_state", "Memory already offered.");
534 return;
535 }
536 ri++;
537 }
538 // Find the first empty offer and have 1GB of shared memory there
539 for (auto& offer : quotaEvaluator.mOffers) {
540 if (offer.valid == false) {
541 offer.cpu = 0;
542 offer.memory = 0;
543 offer.sharedMemory = 1000000000;
544 offer.valid = true;
545 offer.user = -1;
546 break;
547 }
548 }
550 O2_SIGNPOST_END(device, sid, "signal_state", "Done processing signals.");
551}
552
553struct DecongestionContext {
556};
557
558auto decongestionCallbackLate = [](AsyncTask& task, size_t aid) -> void {
559 auto& oldestTimeslice = task.user<DecongestionContext>().oldestTimeslice;
560 auto& ref = task.user<DecongestionContext>().ref;
561
562 auto& decongestion = ref.get<DecongestionService>();
563 auto& proxy = ref.get<FairMQDeviceProxy>();
564 if (oldestTimeslice.timeslice.value <= decongestion.lastTimeslice) {
565 LOG(debug) << "Not sending already sent oldest possible timeslice " << oldestTimeslice.timeslice.value;
566 return;
567 }
568 for (int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
569 auto& info = proxy.getForwardChannelInfo(ChannelIndex{fi});
570 auto& state = proxy.getForwardChannelState(ChannelIndex{fi});
571 O2_SIGNPOST_ID_GENERATE(aid, async_queue);
572 // TODO: this we could cache in the proxy at the bind moment.
573 if (info.channelType != ChannelAccountingType::DPL) {
574 O2_SIGNPOST_EVENT_EMIT(async_queue, aid, "forwardInputsCallback", "Skipping channel %{public}s because it's not a DPL channel",
575 info.name.c_str());
576
577 continue;
578 }
579 if (DataProcessingHelpers::sendOldestPossibleTimeframe(ref, info, state, oldestTimeslice.timeslice.value)) {
580 O2_SIGNPOST_EVENT_EMIT(async_queue, aid, "forwardInputsCallback", "Forwarding to channel %{public}s oldest possible timeslice %zu, prio 20",
581 info.name.c_str(), oldestTimeslice.timeslice.value);
582 }
583 }
584};
585
586// This is how we do the forwarding, i.e. we push
587// the inputs which are shared between this device and others
588// to the next one in the daisy chain.
589// FIXME: do it in a smarter way than O(N^2)
590static auto forwardInputs = [](ServiceRegistryRef registry, TimesliceSlot slot, std::vector<std::vector<fair::mq::MessagePtr>>& currentSetOfInputs,
591 TimesliceIndex::OldestOutputInfo oldestTimeslice, bool copy, bool consume = true) {
592 auto& proxy = registry.get<FairMQDeviceProxy>();
593
594 O2_SIGNPOST_ID_GENERATE(sid, forwarding);
595 O2_SIGNPOST_START(forwarding, sid, "forwardInputs", "Starting forwarding for slot %zu with oldestTimeslice %zu %{public}s%{public}s%{public}s",
596 slot.index, oldestTimeslice.timeslice.value, copy ? "with copy" : "", copy && consume ? " and " : "", consume ? "with consume" : "");
597 auto forwardedParts = DataProcessingHelpers::routeForwardedMessageSet(proxy, currentSetOfInputs, copy, consume);
598
599 for (int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
600 if (forwardedParts[fi].Size() == 0) {
601 continue;
602 }
603 ForwardChannelInfo info = proxy.getForwardChannelInfo(ChannelIndex{fi});
604 auto& parts = forwardedParts[fi];
605 if (info.policy == nullptr) {
606 O2_SIGNPOST_EVENT_EMIT_ERROR(forwarding, sid, "forwardInputs", "Forwarding to %{public}s %d has no policy.", info.name.c_str(), fi);
607 continue;
608 }
609 O2_SIGNPOST_EVENT_EMIT(forwarding, sid, "forwardInputs", "Forwarding to %{public}s %d", info.name.c_str(), fi);
610 info.policy->forward(parts, ChannelIndex{fi}, registry);
611 }
612
613 auto& asyncQueue = registry.get<AsyncQueue>();
614 auto& decongestion = registry.get<DecongestionService>();
615 O2_SIGNPOST_ID_GENERATE(aid, async_queue);
616 O2_SIGNPOST_EVENT_EMIT(async_queue, aid, "forwardInputs", "Queuing forwarding oldestPossible %zu", oldestTimeslice.timeslice.value);
617 AsyncQueueHelpers::post(asyncQueue, AsyncTask{.timeslice = oldestTimeslice.timeslice, .id = decongestion.oldestPossibleTimesliceTask, .debounce = -1, .callback = decongestionCallbackLate}
618 .user<DecongestionContext>({.ref = registry, .oldestTimeslice = oldestTimeslice}));
619 O2_SIGNPOST_END(forwarding, sid, "forwardInputs", "Forwarding done");
620};
621
622static auto cleanEarlyForward = [](ServiceRegistryRef registry, TimesliceSlot slot, std::vector<std::vector<fair::mq::MessagePtr>>& currentSetOfInputs,
623 TimesliceIndex::OldestOutputInfo oldestTimeslice, bool copy, bool consume = true) {
624 auto& proxy = registry.get<FairMQDeviceProxy>();
625
626 O2_SIGNPOST_ID_GENERATE(sid, forwarding);
627 O2_SIGNPOST_START(forwarding, sid, "forwardInputs", "Cleaning up slot %zu with oldestTimeslice %zu %{public}s%{public}s%{public}s",
628 slot.index, oldestTimeslice.timeslice.value, copy ? "with copy" : "", copy && consume ? " and " : "", consume ? "with consume" : "");
629 // Always copy them, because we do not want to actually send them.
630 // We merely need the side effect of the consume, if applicable.
631 for (size_t ii = 0, ie = currentSetOfInputs.size(); ii < ie; ++ii) {
632 auto span = std::span<fair::mq::MessagePtr>(currentSetOfInputs[ii]);
634 }
635
636 O2_SIGNPOST_END(forwarding, sid, "forwardInputs", "Cleaning done");
637};
638
639extern volatile int region_read_global_dummy_variable;
641
643void handleRegionCallbacks(ServiceRegistryRef registry, std::vector<fair::mq::RegionInfo>& infos)
644{
645 if (infos.empty() == false) {
646 std::vector<fair::mq::RegionInfo> toBeNotified;
647 toBeNotified.swap(infos); // avoid any MT issue.
648 static bool dummyRead = getenv("DPL_DEBUG_MAP_ALL_SHM_REGIONS") && atoi(getenv("DPL_DEBUG_MAP_ALL_SHM_REGIONS"));
649 for (auto const& info : toBeNotified) {
650 if (dummyRead) {
651 for (size_t i = 0; i < info.size / sizeof(region_read_global_dummy_variable); i += 4096 / sizeof(region_read_global_dummy_variable)) {
652 region_read_global_dummy_variable = ((int*)info.ptr)[i];
653 }
654 }
655 registry.get<CallbackService>().call<CallbackService::Id::RegionInfoCallback>(info);
656 }
657 }
658}
659
660namespace
661{
663{
664 auto* state = (DeviceState*)handle->data;
666}
667} // namespace
668
669void DataProcessingDevice::initPollers()
670{
671 auto ref = ServiceRegistryRef{mServiceRegistry};
672 auto& deviceContext = ref.get<DeviceContext>();
673 auto& context = ref.get<DataProcessorContext>();
674 auto& spec = ref.get<DeviceSpec const>();
675 auto& state = ref.get<DeviceState>();
676 // We add a timer only in case a channel poller is not there.
677 if ((context.statefulProcess != nullptr) || (context.statelessProcess != nullptr)) {
678 for (auto& [channelName, channel] : GetChannels()) {
679 InputChannelInfo* channelInfo;
680 for (size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
681 auto& channelSpec = spec.inputChannels[ci];
682 channelInfo = &state.inputChannelInfos[ci];
683 if (channelSpec.name != channelName) {
684 continue;
685 }
686 channelInfo->channel = &this->GetChannel(channelName, 0);
687 break;
688 }
689 if ((channelName.rfind("from_internal-dpl", 0) == 0) &&
690 (channelName.rfind("from_internal-dpl-aod", 0) != 0) &&
691 (channelName.rfind("from_internal-dpl-ccdb-backend", 0) != 0) &&
692 (channelName.rfind("from_internal-dpl-injected", 0)) != 0) {
693 LOGP(detail, "{} is an internal channel. Skipping as no input will come from there.", channelName);
694 continue;
695 }
696 // We only watch receiving sockets.
697 if (channelName.rfind("from_" + spec.name + "_", 0) == 0) {
698 LOGP(detail, "{} is to send data. Not polling.", channelName);
699 continue;
700 }
701
702 if (channelName.rfind("from_", 0) != 0) {
703 LOGP(detail, "{} is not a DPL socket. Not polling.", channelName);
704 continue;
705 }
706
707 // We assume there is always a ZeroMQ socket behind.
708 int zmq_fd = 0;
709 size_t zmq_fd_len = sizeof(zmq_fd);
710 // FIXME: I should probably save those somewhere... ;-)
711 auto* poller = (uv_poll_t*)malloc(sizeof(uv_poll_t));
712 channel[0].GetSocket().GetOption("fd", &zmq_fd, &zmq_fd_len);
713 if (zmq_fd == 0) {
714 LOG(error) << "Cannot get file descriptor for channel." << channelName;
715 continue;
716 }
717 LOGP(detail, "Polling socket for {}", channelName);
718 auto* pCtx = (PollerContext*)malloc(sizeof(PollerContext));
719 pCtx->name = strdup(channelName.c_str());
720 pCtx->loop = state.loop;
721 pCtx->device = this;
722 pCtx->state = &state;
723 pCtx->fd = zmq_fd;
724 assert(channelInfo != nullptr);
725 pCtx->channelInfo = channelInfo;
726 pCtx->socket = &channel[0].GetSocket();
727 pCtx->read = true;
728 poller->data = pCtx;
729 uv_poll_init(state.loop, poller, zmq_fd);
730 if (channelName.rfind("from_", 0) != 0) {
731 LOGP(detail, "{} is an out of band channel.", channelName);
732 state.activeOutOfBandPollers.push_back(poller);
733 } else {
734 channelInfo->pollerIndex = state.activeInputPollers.size();
735 state.activeInputPollers.push_back(poller);
736 }
737 }
738 // In case we do not have any input channel and we do not have
739 // any timers or signal watchers we still wake up whenever we can send data to downstream
740 // devices to allow for enumerations.
741 if (state.activeInputPollers.empty() &&
742 state.activeOutOfBandPollers.empty() &&
743 state.activeTimers.empty() &&
744 state.activeSignals.empty()) {
745 // FIXME: this is to make sure we do not reset the output timer
746 // for readout proxies or similar. In principle this should go once
747 // we move to OutOfBand InputSpec.
748 if (state.inputChannelInfos.empty()) {
749 LOGP(detail, "No input channels. Setting exit transition timeout to 0.");
750 deviceContext.exitTransitionTimeout = 0;
751 }
752 for (auto& [channelName, channel] : GetChannels()) {
753 if (channelName.rfind(spec.channelPrefix + "from_internal-dpl", 0) == 0) {
754 LOGP(detail, "{} is an internal channel. Not polling.", channelName);
755 continue;
756 }
757 if (channelName.rfind(spec.channelPrefix + "from_" + spec.name + "_", 0) == 0) {
758 LOGP(detail, "{} is an out of band channel. Not polling for output.", channelName);
759 continue;
760 }
761 // We assume there is always a ZeroMQ socket behind.
762 int zmq_fd = 0;
763 size_t zmq_fd_len = sizeof(zmq_fd);
764 // FIXME: I should probably save those somewhere... ;-)
765 auto* poller = (uv_poll_t*)malloc(sizeof(uv_poll_t));
766 channel[0].GetSocket().GetOption("fd", &zmq_fd, &zmq_fd_len);
767 if (zmq_fd == 0) {
768 LOGP(error, "Cannot get file descriptor for channel {}", channelName);
769 continue;
770 }
771 LOG(detail) << "Polling socket for " << channel[0].GetName();
772 // FIXME: leak
773 auto* pCtx = (PollerContext*)malloc(sizeof(PollerContext));
774 pCtx->name = strdup(channelName.c_str());
775 pCtx->loop = state.loop;
776 pCtx->device = this;
777 pCtx->state = &state;
778 pCtx->fd = zmq_fd;
779 pCtx->read = false;
780 poller->data = pCtx;
781 uv_poll_init(state.loop, poller, zmq_fd);
782 state.activeOutputPollers.push_back(poller);
783 }
784 }
785 } else {
786 LOGP(detail, "This is a fake device so we exit after the first iteration.");
787 deviceContext.exitTransitionTimeout = 0;
788 // This is a fake device, so we can request to exit immediately
789 ServiceRegistryRef ref{mServiceRegistry};
790 ref.get<ControlService>().readyToQuit(QuitRequest::Me);
791 // A two second timer to stop internal devices which do not want to
792 auto* timer = (uv_timer_t*)malloc(sizeof(uv_timer_t));
793 uv_timer_init(state.loop, timer);
794 timer->data = &state;
795 uv_update_time(state.loop);
796 uv_timer_start(timer, on_idle_timer, 2000, 2000);
797 state.activeTimers.push_back(timer);
798 }
799}
800
801void DataProcessingDevice::startPollers()
802{
803 auto ref = ServiceRegistryRef{mServiceRegistry};
804 auto& deviceContext = ref.get<DeviceContext>();
805 auto& state = ref.get<DeviceState>();
806
807 for (auto* poller : state.activeInputPollers) {
808 O2_SIGNPOST_ID_FROM_POINTER(sid, device, poller);
809 O2_SIGNPOST_START(device, sid, "socket_state", "Input socket waiting for connection.");
810 uv_poll_start(poller, UV_WRITABLE, &on_socket_polled);
811 ((PollerContext*)poller->data)->pollerState = PollerContext::PollerState::Disconnected;
812 }
813 for (auto& poller : state.activeOutOfBandPollers) {
814 uv_poll_start(poller, UV_WRITABLE, &on_out_of_band_polled);
815 ((PollerContext*)poller->data)->pollerState = PollerContext::PollerState::Disconnected;
816 }
817 for (auto* poller : state.activeOutputPollers) {
818 O2_SIGNPOST_ID_FROM_POINTER(sid, device, poller);
819 O2_SIGNPOST_START(device, sid, "socket_state", "Output socket waiting for connection.");
820 uv_poll_start(poller, UV_WRITABLE, &on_socket_polled);
821 ((PollerContext*)poller->data)->pollerState = PollerContext::PollerState::Disconnected;
822 }
823
824 deviceContext.gracePeriodTimer = (uv_timer_t*)malloc(sizeof(uv_timer_t));
825 deviceContext.gracePeriodTimer->data = new ServiceRegistryRef(mServiceRegistry);
826 uv_timer_init(state.loop, deviceContext.gracePeriodTimer);
827
828 deviceContext.dataProcessingGracePeriodTimer = (uv_timer_t*)malloc(sizeof(uv_timer_t));
829 deviceContext.dataProcessingGracePeriodTimer->data = new ServiceRegistryRef(mServiceRegistry);
830 uv_timer_init(state.loop, deviceContext.dataProcessingGracePeriodTimer);
831}
832
833void DataProcessingDevice::stopPollers()
834{
835 auto ref = ServiceRegistryRef{mServiceRegistry};
836 auto& deviceContext = ref.get<DeviceContext>();
837 auto& state = ref.get<DeviceState>();
838 LOGP(detail, "Stopping {} input pollers", state.activeInputPollers.size());
839 for (auto* poller : state.activeInputPollers) {
840 O2_SIGNPOST_ID_FROM_POINTER(sid, device, poller);
841 O2_SIGNPOST_END(device, sid, "socket_state", "Output socket closed.");
842 uv_poll_stop(poller);
843 ((PollerContext*)poller->data)->pollerState = PollerContext::PollerState::Stopped;
844 }
845 LOGP(detail, "Stopping {} out of band pollers", state.activeOutOfBandPollers.size());
846 for (auto* poller : state.activeOutOfBandPollers) {
847 uv_poll_stop(poller);
848 ((PollerContext*)poller->data)->pollerState = PollerContext::PollerState::Stopped;
849 }
850 LOGP(detail, "Stopping {} output pollers", state.activeOutOfBandPollers.size());
851 for (auto* poller : state.activeOutputPollers) {
852 O2_SIGNPOST_ID_FROM_POINTER(sid, device, poller);
853 O2_SIGNPOST_END(device, sid, "socket_state", "Output socket closed.");
854 uv_poll_stop(poller);
855 ((PollerContext*)poller->data)->pollerState = PollerContext::PollerState::Stopped;
856 }
857
858 uv_timer_stop(deviceContext.gracePeriodTimer);
859 delete (ServiceRegistryRef*)deviceContext.gracePeriodTimer->data;
860 free(deviceContext.gracePeriodTimer);
861 deviceContext.gracePeriodTimer = nullptr;
862
863 uv_timer_stop(deviceContext.dataProcessingGracePeriodTimer);
864 delete (ServiceRegistryRef*)deviceContext.dataProcessingGracePeriodTimer->data;
865 free(deviceContext.dataProcessingGracePeriodTimer);
866 deviceContext.dataProcessingGracePeriodTimer = nullptr;
867}
868
870{
871 auto ref = ServiceRegistryRef{mServiceRegistry};
872 auto& deviceContext = ref.get<DeviceContext>();
873 auto& context = ref.get<DataProcessorContext>();
874
875 O2_SIGNPOST_ID_FROM_POINTER(cid, device, &context);
876 O2_SIGNPOST_START(device, cid, "InitTask", "Entering InitTask callback.");
877 auto& spec = getRunningDevice(mRunningDevice, mServiceRegistry);
878 auto distinct = DataRelayerHelpers::createDistinctRouteIndex(spec.inputs);
879 auto& state = ref.get<DeviceState>();
880 int i = 0;
881 for (auto& di : distinct) {
882 auto& route = spec.inputs[di];
883 if (route.configurator.has_value() == false) {
884 i++;
885 continue;
886 }
887 ExpirationHandler handler{
888 .name = route.configurator->name,
889 .routeIndex = RouteIndex{i++},
890 .lifetime = route.matcher.lifetime,
891 .creator = route.configurator->creatorConfigurator(state, mServiceRegistry, *mConfigRegistry),
892 .checker = route.configurator->danglingConfigurator(state, *mConfigRegistry),
893 .handler = route.configurator->expirationConfigurator(state, *mConfigRegistry)};
894 context.expirationHandlers.emplace_back(std::move(handler));
895 }
896
897 if (state.awakeMainThread == nullptr) {
898 state.awakeMainThread = (uv_async_t*)malloc(sizeof(uv_async_t));
899 state.awakeMainThread->data = &state;
900 uv_async_init(state.loop, state.awakeMainThread, on_awake_main_thread);
901 }
902
903 deviceContext.expectedRegionCallbacks = std::stoi(fConfig->GetValue<std::string>("expected-region-callbacks"));
904 deviceContext.exitTransitionTimeout = std::stoi(fConfig->GetValue<std::string>("exit-transition-timeout"));
905 deviceContext.dataProcessingTimeout = std::stoi(fConfig->GetValue<std::string>("data-processing-timeout"));
906
907 for (auto& channel : GetChannels()) {
908 channel.second.at(0).Transport()->SubscribeToRegionEvents([&context = deviceContext,
909 &registry = mServiceRegistry,
910 &pendingRegionInfos = mPendingRegionInfos,
911 &regionInfoMutex = mRegionInfoMutex](fair::mq::RegionInfo info) {
912 std::lock_guard<std::mutex> lock(regionInfoMutex);
913 LOG(detail) << ">>> Region info event" << info.event;
914 LOG(detail) << "id: " << info.id;
915 LOG(detail) << "ptr: " << info.ptr;
916 LOG(detail) << "size: " << info.size;
917 LOG(detail) << "flags: " << info.flags;
918 // Now we check for pending events with the mutex,
919 // so the lines below are atomic.
920 pendingRegionInfos.push_back(info);
921 context.expectedRegionCallbacks -= 1;
922 // We always want to handle these on the main loop,
923 // so we awake it.
924 ServiceRegistryRef ref{registry};
925 uv_async_send(ref.get<DeviceState>().awakeMainThread);
926 });
927 }
928
929 // Add a signal manager for SIGUSR1 so that we can force
930 // an event from the outside, making sure that the event loop can
931 // be unblocked (e.g. by a quitting DPL driver) even when there
932 // is no data pending to be processed.
933 if (deviceContext.sigusr1Handle == nullptr) {
934 deviceContext.sigusr1Handle = (uv_signal_t*)malloc(sizeof(uv_signal_t));
935 deviceContext.sigusr1Handle->data = &mServiceRegistry;
936 uv_signal_init(state.loop, deviceContext.sigusr1Handle);
937 uv_signal_start(deviceContext.sigusr1Handle, on_signal_callback, SIGUSR1);
938 }
939 // If there is any signal, we want to make sure they are active
940 for (auto& handle : state.activeSignals) {
941 handle->data = &state;
942 }
943 // When we start, we must make sure that we do listen to the signal
944 deviceContext.sigusr1Handle->data = &mServiceRegistry;
945
947 DataProcessingDevice::initPollers();
948
949 // Whenever we InitTask, we consider as if the previous iteration
950 // was successful, so that even if there is no timer or receiving
951 // channel, we can still start an enumeration.
952 DataProcessorContext* initialContext = nullptr;
953 bool idle = state.lastActiveDataProcessor.compare_exchange_strong(initialContext, (DataProcessorContext*)-1);
954 if (!idle) {
955 LOG(error) << "DataProcessor " << state.lastActiveDataProcessor.load()->spec->name << " was unexpectedly active";
956 }
957
958 // We should be ready to run here. Therefore we copy all the
959 // required parts in the DataProcessorContext. Eventually we should
960 // do so on a per thread basis, with fine grained locks.
961 // FIXME: this should not use ServiceRegistry::threadSalt, but
962 // more a ServiceRegistry::globalDataProcessorSalt(N) where
963 // N is the number of the multiplexed data processor.
964 // We will get there.
965 this->fillContext(mServiceRegistry.get<DataProcessorContext>(ServiceRegistry::globalDeviceSalt()), deviceContext);
966
967 O2_SIGNPOST_END(device, cid, "InitTask", "Exiting InitTask callback waiting for the remaining region callbacks.");
968
969 auto hasPendingEvents = [&mutex = mRegionInfoMutex, &pendingRegionInfos = mPendingRegionInfos](DeviceContext& deviceContext) {
970 std::lock_guard<std::mutex> lock(mutex);
971 return (pendingRegionInfos.empty() == false) || deviceContext.expectedRegionCallbacks > 0;
972 };
973 O2_SIGNPOST_START(device, cid, "InitTask", "Waiting for registation events.");
978 while (hasPendingEvents(deviceContext)) {
979 // Wait for the callback to signal its done, so that we do not busy wait.
980 uv_run(state.loop, UV_RUN_ONCE);
981 // Handle callbacks if any
982 {
983 O2_SIGNPOST_EVENT_EMIT(device, cid, "InitTask", "Memory registration event received.");
984 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
985 handleRegionCallbacks(mServiceRegistry, mPendingRegionInfos);
986 }
987 }
988 O2_SIGNPOST_END(device, cid, "InitTask", "Done waiting for registration events.");
989}
990
992{
993 context.isSink = false;
994 // If nothing is a sink, the rate limiting simply does not trigger.
995 bool enableRateLimiting = std::stoi(fConfig->GetValue<std::string>("timeframes-rate-limit"));
996
997 auto ref = ServiceRegistryRef{mServiceRegistry};
998 auto& spec = ref.get<DeviceSpec const>();
999
1000 // The policy is now allowed to state the default.
1001 context.balancingInputs = spec.completionPolicy.balanceChannels;
1002 // This is needed because the internal injected dummy sink should not
1003 // try to balance inputs unless the rate limiting is requested.
1004 if (enableRateLimiting == false && spec.name.find("internal-dpl-injected-dummy-sink") != std::string::npos) {
1005 context.balancingInputs = false;
1006 }
1007 if (enableRateLimiting) {
1008 for (auto& spec : spec.outputs) {
1009 if (spec.matcher.binding.value == "dpl-summary") {
1010 context.isSink = true;
1011 break;
1012 }
1013 }
1014 }
1015
1016 context.registry = &mServiceRegistry;
1019 if (context.error != nullptr) {
1020 context.errorHandling = [&errorCallback = context.error,
1021 &serviceRegistry = mServiceRegistry](RuntimeErrorRef e, InputRecord& record) {
1025 auto& err = error_from_ref(e);
1026 auto& context = ref.get<DataProcessorContext>();
1027 O2_SIGNPOST_ID_FROM_POINTER(cid, device, &context);
1028 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid, "Run", "Exception while running: %{public}s. Invoking callback.", err.what);
1029 BacktraceHelpers::demangled_backtrace_symbols(err.backtrace, err.maxBacktrace, STDERR_FILENO);
1030 auto& stats = ref.get<DataProcessingStats>();
1032 ErrorContext errorContext{record, ref, e};
1033 errorCallback(errorContext);
1034 };
1035 } else {
1036 context.errorHandling = [&serviceRegistry = mServiceRegistry](RuntimeErrorRef e, InputRecord& record) {
1037 auto& err = error_from_ref(e);
1041 auto& context = ref.get<DataProcessorContext>();
1042 auto& deviceContext = ref.get<DeviceContext>();
1043 O2_SIGNPOST_ID_FROM_POINTER(cid, device, &context);
1044 BacktraceHelpers::demangled_backtrace_symbols(err.backtrace, err.maxBacktrace, STDERR_FILENO);
1045 auto& stats = ref.get<DataProcessingStats>();
1047 switch (deviceContext.processingPolicies.error) {
1049 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid, "Run", "Exception while running: %{public}s. Rethrowing.", err.what);
1050 throw e;
1051 default:
1052 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid, "Run", "Exception while running: %{public}s. Skipping to next timeframe.", err.what);
1053 break;
1054 }
1055 };
1056 }
1057
1058 auto decideEarlyForward = [&context, &deviceContext, &spec, this]() -> ForwardPolicy {
1059 ForwardPolicy defaultEarlyForwardPolicy = getenv("DPL_OLD_EARLY_FORWARD") ? ForwardPolicy::AtCompletionPolicySatisified : ForwardPolicy::AtInjection;
1060 // FIXME: try again with the new policy by default.
1061 //
1062 // Make the new policy optional until we handle some of the corner cases
1063 // with custom policies which expect the early forward to happen only when
1064 // all the data is available, like in the TPC case.
1065 // ForwardPolicy defaultEarlyForwardPolicy = getenv("DPL_NEW_EARLY_FORWARD") ? ForwardPolicy::AtInjection : ForwardPolicy::AtCompletionPolicySatisified;
1066 for (auto& forward : spec.forwards) {
1067 if (DataSpecUtils::match(forward.matcher, ConcreteDataTypeMatcher{"TPC", "DIGITSMCTR"}) ||
1068 DataSpecUtils::match(forward.matcher, ConcreteDataTypeMatcher{"TPC", "CLNATIVEMCLBL"}) ||
1069 DataSpecUtils::match(forward.matcher, ConcreteDataTypeMatcher{o2::header::gDataOriginTPC, "DIGITS"}) ||
1070 DataSpecUtils::match(forward.matcher, ConcreteDataTypeMatcher{o2::header::gDataOriginTPC, "CLUSTERNATIVE"})) {
1071 defaultEarlyForwardPolicy = ForwardPolicy::AtCompletionPolicySatisified;
1072 break;
1073 }
1074 }
1075 // Output proxies should wait for the completion policy before forwarding.
1076 // Because they actually do not do anything, that's equivalent to
1077 // forwarding after the processing.
1078 for (auto& label : spec.labels) {
1079 if (label.value == "output-proxy") {
1080 defaultEarlyForwardPolicy = ForwardPolicy::AfterProcessing;
1081 break;
1082 }
1083 }
1084
1087 ForwardPolicy forwardPolicy = defaultEarlyForwardPolicy;
1088 if (spec.forwards.empty() == false) {
1089 switch (deviceContext.processingPolicies.earlyForward) {
1091 forwardPolicy = ForwardPolicy::AfterProcessing;
1092 break;
1094 forwardPolicy = defaultEarlyForwardPolicy;
1095 break;
1097 forwardPolicy = defaultEarlyForwardPolicy;
1098 break;
1099 }
1100 }
1101 bool onlyConditions = true;
1102 bool overriddenEarlyForward = false;
1103 for (auto& forwarded : spec.forwards) {
1104 if (forwarded.matcher.lifetime != Lifetime::Condition) {
1105 onlyConditions = false;
1106 }
1108 forwardPolicy = ForwardPolicy::AfterProcessing;
1109 overriddenEarlyForward = true;
1110 LOG(detail) << "Cannot forward early because of RAWDATA input: " << DataSpecUtils::describe(forwarded.matcher);
1111 break;
1112 }
1113 if (forwarded.matcher.lifetime == Lifetime::Optional) {
1114 forwardPolicy = ForwardPolicy::AfterProcessing;
1115 overriddenEarlyForward = true;
1116 LOG(detail) << "Cannot forward early because of Optional input: " << DataSpecUtils::describe(forwarded.matcher);
1117 break;
1118 }
1119 }
1120 if (!overriddenEarlyForward && onlyConditions) {
1121 forwardPolicy = defaultEarlyForwardPolicy;
1122 LOG(detail) << "Enabling early forwarding because only conditions to be forwarded";
1123 }
1124 return forwardPolicy;
1125 };
1126 context.forwardPolicy = decideEarlyForward();
1127}
1128
1130{
1131 auto ref = ServiceRegistryRef{mServiceRegistry};
1132 auto& state = ref.get<DeviceState>();
1133
1134 O2_SIGNPOST_ID_FROM_POINTER(cid, device, state.loop);
1135 O2_SIGNPOST_START(device, cid, "PreRun", "Entering PreRun callback.");
1136 state.quitRequested = false;
1138 state.allowedProcessing = DeviceState::Any;
1139 for (auto& info : state.inputChannelInfos) {
1140 if (info.state != InputChannelState::Pull) {
1141 info.state = InputChannelState::Running;
1142 }
1143 }
1144
1145 // Catch callbacks which fail before we start.
1146 // Notice that when running multiple dataprocessors
1147 // we should probably allow expendable ones to fail.
1148 try {
1149 auto& dpContext = ref.get<DataProcessorContext>();
1150 dpContext.preStartCallbacks(ref);
1151 for (size_t i = 0; i < mStreams.size(); ++i) {
1152 auto streamRef = ServiceRegistryRef{mServiceRegistry, ServiceRegistry::globalStreamSalt(i + 1)};
1153 auto& context = streamRef.get<StreamContext>();
1154 context.preStartStreamCallbacks(streamRef);
1155 }
1156 } catch (std::exception& e) {
1157 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid, "PreRun", "Exception of type std::exception caught in PreRun: %{public}s. Rethrowing.", e.what());
1158 O2_SIGNPOST_END(device, cid, "PreRun", "Exiting PreRun due to exception thrown.");
1159 throw;
1160 } catch (o2::framework::RuntimeErrorRef& e) {
1161 auto& err = error_from_ref(e);
1162 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid, "PreRun", "Exception of type o2::framework::RuntimeErrorRef caught in PreRun: %{public}s. Rethrowing.", err.what);
1163 O2_SIGNPOST_END(device, cid, "PreRun", "Exiting PreRun due to exception thrown.");
1164 throw;
1165 } catch (...) {
1166 O2_SIGNPOST_END(device, cid, "PreRun", "Unknown exception being thrown. Rethrowing.");
1167 throw;
1168 }
1169
1170 ref.get<CallbackService>().call<CallbackService::Id::Start>();
1171 startPollers();
1172
1173 // Raise to 1 when we are ready to start processing
1174 using o2::monitoring::Metric;
1175 using o2::monitoring::Monitoring;
1176 using o2::monitoring::tags::Key;
1177 using o2::monitoring::tags::Value;
1178
1179 auto& monitoring = ref.get<Monitoring>();
1180 monitoring.send(Metric{(uint64_t)1, "device_state"}.addTag(Key::Subsystem, Value::DPL));
1181 O2_SIGNPOST_END(device, cid, "PreRun", "Exiting PreRun callback.");
1182}
1183
1185{
1186 ServiceRegistryRef ref{mServiceRegistry};
1187 // Raise to 1 when we are ready to start processing
1188 using o2::monitoring::Metric;
1189 using o2::monitoring::Monitoring;
1190 using o2::monitoring::tags::Key;
1191 using o2::monitoring::tags::Value;
1192
1193 auto& monitoring = ref.get<Monitoring>();
1194 monitoring.send(Metric{(uint64_t)0, "device_state"}.addTag(Key::Subsystem, Value::DPL));
1195
1196 stopPollers();
1197 ref.get<CallbackService>().call<CallbackService::Id::Stop>();
1198 auto& dpContext = ref.get<DataProcessorContext>();
1199 dpContext.postStopCallbacks(ref);
1200}
1201
1203{
1204 ServiceRegistryRef ref{mServiceRegistry};
1205 ref.get<CallbackService>().call<CallbackService::Id::Reset>();
1206}
1207
1209{
1210 ServiceRegistryRef ref{mServiceRegistry};
1211 auto& state = ref.get<DeviceState>();
1213 bool firstLoop = true;
1214 O2_SIGNPOST_ID_FROM_POINTER(lid, device, state.loop);
1215 O2_SIGNPOST_START(device, lid, "device_state", "First iteration of the device loop");
1216
1217 auto* poolSizeEnv = getenv("DPL_THREADPOOL_SIZE");
1218 bool dplEnableMultithreding = poolSizeEnv && std::atoi(poolSizeEnv) > 0;
1219
1220 while (state.transitionHandling != TransitionHandlingState::Expired) {
1221 if (state.nextFairMQState.empty() == false) {
1222 (void)this->ChangeState(state.nextFairMQState.back());
1223 state.nextFairMQState.pop_back();
1224 }
1225 // Notify on the main thread the new region callbacks, making sure
1226 // no callback is issued if there is something still processing.
1227 {
1228 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1229 handleRegionCallbacks(mServiceRegistry, mPendingRegionInfos);
1230 }
1231 // This will block for the correct delay (or until we get data
1232 // on a socket). We also do not block on the first iteration
1233 // so that devices which do not have a timer can still start an
1234 // enumeration.
1235 {
1236 ServiceRegistryRef ref{mServiceRegistry};
1237 ref.get<DriverClient>().flushPending(mServiceRegistry);
1238 DataProcessorContext* lastActive = state.lastActiveDataProcessor.load();
1239 // Reset to zero unless some other DataPorcessorContext completed in the meanwhile.
1240 // In such case we will take care of it at next iteration.
1241 state.lastActiveDataProcessor.compare_exchange_strong(lastActive, nullptr);
1242
1243 auto shouldNotWait = (lastActive != nullptr &&
1244 (state.streaming != StreamingState::Idle) && (state.activeSignals.empty())) ||
1246 if (firstLoop) {
1247 shouldNotWait = true;
1248 firstLoop = false;
1249 }
1250 if (lastActive != nullptr) {
1252 }
1253 if (NewStatePending()) {
1254 O2_SIGNPOST_EVENT_EMIT(device, lid, "run_loop", "New state pending. Waiting for it to be handled.");
1255 shouldNotWait = true;
1257 }
1259 // If we are Idle, we can then consider the transition to be expired.
1260 if (state.transitionHandling == TransitionHandlingState::Requested && state.streaming == StreamingState::Idle) {
1261 O2_SIGNPOST_EVENT_EMIT(device, lid, "run_loop", "State transition requested and we are now in Idle. We can consider it to be completed.");
1262 state.transitionHandling = TransitionHandlingState::Expired;
1263 }
1264 if (state.severityStack.empty() == false) {
1265 fair::Logger::SetConsoleSeverity((fair::Severity)state.severityStack.back());
1266 state.severityStack.pop_back();
1267 }
1268 // for (auto &info : mDeviceContext.state->inputChannelInfos) {
1269 // shouldNotWait |= info.readPolled;
1270 // }
1271 state.loopReason = DeviceState::NO_REASON;
1272 state.firedTimers.clear();
1273 if ((state.tracingFlags & DeviceState::LoopReason::TRACE_CALLBACKS) != 0) {
1274 state.severityStack.push_back((int)fair::Logger::GetConsoleSeverity());
1275 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
1276 }
1277 // Run the asynchronous queue just before sleeping again, so that:
1278 // - we can trigger further events from the queue
1279 // - we can guarantee this is the last thing we do in the loop (
1280 // assuming no one else is adding to the queue before this point).
1281 auto onDrop = [&registry = mServiceRegistry, lid](TimesliceSlot slot, std::vector<std::vector<fair::mq::MessagePtr>>& dropped, TimesliceIndex::OldestOutputInfo oldestOutputInfo) {
1282 O2_SIGNPOST_START(device, lid, "run_loop", "Dropping message from slot %" PRIu64 ". Forwarding as needed.", (uint64_t)slot.index);
1283 ServiceRegistryRef ref{registry};
1284 ref.get<AsyncQueue>();
1285 ref.get<DecongestionService>();
1286 ref.get<DataRelayer>();
1287 // Get the current timeslice for the slot.
1288 auto& variables = ref.get<TimesliceIndex>().getVariablesForSlot(slot);
1290 forwardInputs(registry, slot, dropped, oldestOutputInfo, false, true);
1291 };
1292 auto& relayer = ref.get<DataRelayer>();
1293 relayer.prunePending(onDrop);
1294 auto& queue = ref.get<AsyncQueue>();
1295 auto oldestPossibleTimeslice = relayer.getOldestPossibleOutput();
1296 AsyncQueueHelpers::run(queue, {oldestPossibleTimeslice.timeslice.value});
1297 if (shouldNotWait == false) {
1298 auto& dpContext = ref.get<DataProcessorContext>();
1299 dpContext.preLoopCallbacks(ref);
1300 }
1301 O2_SIGNPOST_END(device, lid, "run_loop", "Run loop completed. %{}s", shouldNotWait ? "Will immediately schedule a new one" : "Waiting for next event.");
1302 uv_run(state.loop, shouldNotWait ? UV_RUN_NOWAIT : UV_RUN_ONCE);
1303 O2_SIGNPOST_START(device, lid, "run_loop", "Run loop started. Loop reason %d.", state.loopReason);
1304 if ((state.loopReason & state.tracingFlags) != 0) {
1305 state.severityStack.push_back((int)fair::Logger::GetConsoleSeverity());
1306 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
1307 } else if (state.severityStack.empty() == false) {
1308 fair::Logger::SetConsoleSeverity((fair::Severity)state.severityStack.back());
1309 state.severityStack.pop_back();
1310 }
1311 O2_SIGNPOST_EVENT_EMIT(device, lid, "run_loop", "Loop reason mask %x & %x = %x", state.loopReason, state.tracingFlags, state.loopReason & state.tracingFlags);
1312
1313 if ((state.loopReason & DeviceState::LoopReason::OOB_ACTIVITY) != 0) {
1314 O2_SIGNPOST_EVENT_EMIT(device, lid, "run_loop", "Out of band activity detected. Rescanning everything.");
1315 relayer.rescan();
1316 }
1317
1318 if (!state.pendingOffers.empty()) {
1319 O2_SIGNPOST_EVENT_EMIT(device, lid, "run_loop", "Pending %" PRIu64 " offers. updating the ComputingQuotaEvaluator.", (uint64_t)state.pendingOffers.size());
1320 ref.get<ComputingQuotaEvaluator>().updateOffers(state.pendingOffers, uv_now(state.loop));
1321 }
1322 }
1323
1324 // Notify on the main thread the new region callbacks, making sure
1325 // no callback is issued if there is something still processing.
1326 // Notice that we still need to perform callbacks also after
1327 // the socket epolled, because otherwise we would end up serving
1328 // the callback after the first data arrives is the system is too
1329 // fast to transition from Init to Run.
1330 {
1331 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1332 handleRegionCallbacks(mServiceRegistry, mPendingRegionInfos);
1333 }
1334
1335 // Receive and relay incoming data on the main thread so that I/O
1336 // overlaps with computation running concurrently on work threads.
1338
1339 assert(mStreams.size() == mHandles.size());
1341 TaskStreamRef streamRef{-1};
1342 for (size_t ti = 0; ti < mStreams.size(); ti++) {
1343 auto& taskInfo = mStreams[ti];
1344 if (taskInfo.running) {
1345 continue;
1346 }
1347 // Stream 0 is for when we run in
1348 streamRef.index = ti;
1349 }
1350 using o2::monitoring::Metric;
1351 using o2::monitoring::Monitoring;
1352 using o2::monitoring::tags::Key;
1353 using o2::monitoring::tags::Value;
1354 // We have an empty stream, let's check if we have enough
1355 // resources for it to run something
1356 if (streamRef.index != -1) {
1357 // Synchronous execution of the callbacks. This will be moved in the
1358 // moved in the on_socket_polled once we have threading in place.
1359 uv_work_t& handle = mHandles[streamRef.index];
1360 TaskStreamInfo& stream = mStreams[streamRef.index];
1361 handle.data = &mStreams[streamRef.index];
1362
1363 static std::function<void(ComputingQuotaOffer const&, ComputingQuotaStats const& stats)> reportExpiredOffer = [&registry = mServiceRegistry](ComputingQuotaOffer const& offer, ComputingQuotaStats const& stats) {
1364 ServiceRegistryRef ref{registry};
1365 auto& dpStats = ref.get<DataProcessingStats>();
1366 dpStats.updateStats({static_cast<short>(ProcessingStatsId::RESOURCE_OFFER_EXPIRED), DataProcessingStats::Op::Set, stats.totalExpiredOffers});
1367 dpStats.updateStats({static_cast<short>(ProcessingStatsId::ARROW_BYTES_EXPIRED), DataProcessingStats::Op::Set, stats.totalExpiredBytes});
1368 dpStats.updateStats({static_cast<short>(ProcessingStatsId::TIMESLICE_NUMBER_EXPIRED), DataProcessingStats::Op::Set, stats.totalExpiredTimeslices});
1369 dpStats.processCommandQueue();
1370 };
1371 auto ref = ServiceRegistryRef{mServiceRegistry};
1372
1373 // Deciding wether to run or not can be done by passing a request to
1374 // the evaluator. In this case, the request is always satisfied and
1375 // we run on whatever resource is available.
1376 auto& spec = ref.get<DeviceSpec const>();
1377 ComputingQuotaOffer accumulated;
1378 bool enough = ref.get<ComputingQuotaEvaluator>().selectOffer(streamRef.index, spec.resourcePolicy.request, uv_now(state.loop), &accumulated);
1379
1380 struct SchedulingStats {
1381 std::atomic<size_t> lastScheduled = 0;
1382 std::atomic<size_t> numberOfUnscheduledSinceLastScheduled = 0;
1383 std::atomic<size_t> numberOfUnscheduled = 0;
1384 std::atomic<size_t> numberOfScheduled = 0;
1385 std::atomic<size_t> nextWarnAt = 1;
1386 };
1387 static SchedulingStats schedulingStats;
1388 O2_SIGNPOST_ID_GENERATE(sid, scheduling);
1389 if (enough) {
1390 stream.id = streamRef;
1391 stream.running = true;
1392 stream.registry = &mServiceRegistry;
1393 schedulingStats.lastScheduled = uv_now(state.loop);
1394 schedulingStats.numberOfScheduled++;
1395 schedulingStats.numberOfUnscheduledSinceLastScheduled = 0;
1396 schedulingStats.nextWarnAt = 1;
1397 O2_SIGNPOST_EVENT_EMIT(scheduling, sid, "Run", "Enough resources to schedule computation on stream %d", streamRef.index);
1398 if (dplEnableMultithreding) [[unlikely]] {
1399 stream.task = &handle;
1400 uv_queue_work(state.loop, stream.task, run_callback, run_completion);
1401 } else {
1402 run_callback(&handle);
1403 run_completion(&handle, 0);
1404 }
1405 } else {
1406 auto const lastSched = schedulingStats.lastScheduled.load();
1407 auto const schedInfo = lastSched ? fmt::format(", last scheduled {} ms ago", uv_now(state.loop) - lastSched) : std::string(", never successfully scheduled");
1408 auto const buildMissingInfo = [&]() {
1409 auto const& required = spec.resourcePolicy.minRequired;
1410 std::string missingInfo;
1411 if (required.sharedMemory > 0 && accumulated.sharedMemory < required.sharedMemory) {
1412 missingInfo += fmt::format(" shared memory (have {} MB, need {} MB)", accumulated.sharedMemory / 1000000, required.sharedMemory / 1000000);
1413 }
1414 if (required.timeslices > 0 && accumulated.timeslices < required.timeslices) {
1415 missingInfo += fmt::format(" timeslices (have {}, need {})", accumulated.timeslices, required.timeslices);
1416 }
1417 if (required.cpu > 0 && accumulated.cpu < required.cpu) {
1418 missingInfo += fmt::format(" CPU cores (have {}, need {})", accumulated.cpu, required.cpu);
1419 }
1420 if (required.memory > 0 && accumulated.memory < required.memory) {
1421 missingInfo += fmt::format(" memory (have {} MB, need {} MB)", accumulated.memory / 1000000, required.memory / 1000000);
1422 }
1423 return missingInfo.empty() ? std::string(" (policy: ") + spec.resourcePolicy.name + ")" : " -" + missingInfo;
1424 };
1425 auto const timeSinceLastScheduled = lastSched ? uv_now(state.loop) - lastSched : 0;
1426 if (schedulingStats.numberOfUnscheduledSinceLastScheduled >= schedulingStats.nextWarnAt) {
1427 auto const missingStr = buildMissingInfo();
1428 if (timeSinceLastScheduled >= 50) {
1429 O2_SIGNPOST_EVENT_EMIT_WARN(scheduling, sid, "Run",
1430 "Not enough resources to schedule computation on stream %d. %zu consecutive skips%s. Missing:%s. Data is not lost and it will be scheduled again.",
1431 streamRef.index,
1432 schedulingStats.numberOfUnscheduledSinceLastScheduled.load(),
1433 schedInfo.c_str(),
1434 missingStr.c_str());
1435 } else {
1436 O2_SIGNPOST_EVENT_EMIT(scheduling, sid, "Run",
1437 "Not enough resources to schedule computation on stream %d. %zu consecutive skips%s. Missing:%s. Data is not lost and it will be scheduled again.",
1438 streamRef.index,
1439 schedulingStats.numberOfUnscheduledSinceLastScheduled.load(),
1440 schedInfo.c_str(),
1441 missingStr.c_str());
1442 }
1443 schedulingStats.nextWarnAt = schedulingStats.nextWarnAt * 2;
1444 } else {
1445 auto const missingStr = buildMissingInfo();
1446 O2_SIGNPOST_EVENT_EMIT(scheduling, sid, "Run",
1447 "Not enough resources to schedule computation on stream %d. %zu consecutive skips%s. Missing:%s. Data is not lost and it will be scheduled again.",
1448 streamRef.index,
1449 schedulingStats.numberOfUnscheduledSinceLastScheduled.load(),
1450 schedInfo.c_str(),
1451 missingStr.c_str());
1452 }
1453 schedulingStats.numberOfUnscheduled++;
1454 schedulingStats.numberOfUnscheduledSinceLastScheduled++;
1455 auto ref = ServiceRegistryRef{mServiceRegistry};
1456 ref.get<ComputingQuotaEvaluator>().handleExpired(reportExpiredOffer);
1457 }
1458 }
1459 }
1460
1461 O2_SIGNPOST_END(device, lid, "run_loop", "Run loop completed. Transition handling state %d.", (int)state.transitionHandling);
1462 auto& spec = ref.get<DeviceSpec const>();
1464 for (size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
1465 auto& info = state.inputChannelInfos[ci];
1466 info.parts.fParts.clear();
1467 }
1468 state.transitionHandling = TransitionHandlingState::NoTransition;
1469}
1470
1474{
1475 auto& context = ref.get<DataProcessorContext>();
1476 O2_SIGNPOST_ID_FROM_POINTER(dpid, device, &context);
1477 O2_SIGNPOST_START(device, dpid, "do_prepare", "Starting DataProcessorContext::doPrepare.");
1478
1479 {
1480 ref.get<CallbackService>().call<CallbackService::Id::ClockTick>();
1481 }
1482 // Whether or not we had something to do.
1483
1484 // Initialise the value for context.allDone. It will possibly be updated
1485 // below if any of the channels is not done.
1486 //
1487 // Notice that fake input channels (InputChannelState::Pull) cannot possibly
1488 // expect to receive an EndOfStream signal. Thus we do not wait for these
1489 // to be completed. In the case of data source devices, as they do not have
1490 // real data input channels, they have to signal EndOfStream themselves.
1491 auto& state = ref.get<DeviceState>();
1492 auto& spec = ref.get<DeviceSpec const>();
1493 O2_SIGNPOST_ID_FROM_POINTER(cid, device, state.inputChannelInfos.data());
1494 O2_SIGNPOST_START(device, cid, "do_prepare", "Reported channel states.");
1495 context.allDone = std::any_of(state.inputChannelInfos.begin(), state.inputChannelInfos.end(), [cid](const auto& info) {
1496 if (info.channel) {
1497 O2_SIGNPOST_EVENT_EMIT(device, cid, "do_prepare", "Input channel %{public}s%{public}s has %zu parts left and is in state %d.",
1498 info.channel->GetName().c_str(), (info.id.value == ChannelIndex::INVALID ? " (non DPL)" : ""), info.parts.fParts.size(), (int)info.state);
1499 } else {
1500 O2_SIGNPOST_EVENT_EMIT(device, cid, "do_prepare", "External channel %d is in state %d.", info.id.value, (int)info.state);
1501 }
1502 return (info.parts.fParts.empty() == true && info.state != InputChannelState::Pull);
1503 });
1504 O2_SIGNPOST_END(device, cid, "do_prepare", "End report.");
1505 O2_SIGNPOST_EVENT_EMIT(device, dpid, "do_prepare", "Processing %zu input channels.", spec.inputChannels.size());
1508 static std::vector<int> pollOrder;
1509 pollOrder.resize(state.inputChannelInfos.size());
1510 std::iota(pollOrder.begin(), pollOrder.end(), 0);
1511 std::sort(pollOrder.begin(), pollOrder.end(), [&infos = state.inputChannelInfos](int a, int b) {
1512 return infos[a].oldestForChannel.value < infos[b].oldestForChannel.value;
1513 });
1514
1515 // Nothing to poll...
1516 if (pollOrder.empty()) {
1517 O2_SIGNPOST_END(device, dpid, "do_prepare", "Nothing to poll. Waiting for next iteration.");
1518 return;
1519 }
1520 auto currentOldest = state.inputChannelInfos[pollOrder.front()].oldestForChannel;
1521 auto currentNewest = state.inputChannelInfos[pollOrder.back()].oldestForChannel;
1522 auto delta = currentNewest.value - currentOldest.value;
1523 O2_SIGNPOST_EVENT_EMIT(device, dpid, "do_prepare", "Oldest possible timeframe range %" PRIu64 " => %" PRIu64 " delta %" PRIu64,
1524 (int64_t)currentOldest.value, (int64_t)currentNewest.value, (int64_t)delta);
1525 auto& infos = state.inputChannelInfos;
1526
1527 if (context.balancingInputs) {
1528 static int pipelineLength = DefaultsHelpers::pipelineLength(*ref.get<RawDeviceService>().device()->fConfig);
1529 static uint64_t ahead = getenv("DPL_MAX_CHANNEL_AHEAD") ? std::atoll(getenv("DPL_MAX_CHANNEL_AHEAD")) : std::max(8, std::min(pipelineLength - 48, pipelineLength / 2));
1530 auto newEnd = std::remove_if(pollOrder.begin(), pollOrder.end(), [&infos, limitNew = currentOldest.value + ahead](int a) -> bool {
1531 return infos[a].oldestForChannel.value > limitNew;
1532 });
1533 for (auto it = pollOrder.begin(); it < pollOrder.end(); it++) {
1534 const auto& channelInfo = state.inputChannelInfos[*it];
1535 if (channelInfo.pollerIndex != -1) {
1536 auto& poller = state.activeInputPollers[channelInfo.pollerIndex];
1537 auto& pollerContext = *(PollerContext*)(poller->data);
1538 if (pollerContext.pollerState == PollerContext::PollerState::Connected || pollerContext.pollerState == PollerContext::PollerState::Suspended) {
1539 bool running = pollerContext.pollerState == PollerContext::PollerState::Connected;
1540 bool shouldBeRunning = it < newEnd;
1541 if (running != shouldBeRunning) {
1542 uv_poll_start(poller, shouldBeRunning ? UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED : 0, &on_socket_polled);
1543 pollerContext.pollerState = shouldBeRunning ? PollerContext::PollerState::Connected : PollerContext::PollerState::Suspended;
1544 }
1545 }
1546 }
1547 }
1548 pollOrder.erase(newEnd, pollOrder.end());
1549 }
1550 O2_SIGNPOST_END(device, dpid, "do_prepare", "%zu channels pass the channel inbalance balance check.", pollOrder.size());
1551
1552 for (auto sci : pollOrder) {
1553 auto& info = state.inputChannelInfos[sci];
1554 O2_SIGNPOST_ID_FROM_POINTER(cid, device, &info);
1555 O2_SIGNPOST_START(device, cid, "channels", "Processing channel %s", info.channel->GetName().c_str());
1556
1558 context.allDone = false;
1559 }
1560 if (info.state != InputChannelState::Running) {
1561 // Remember to flush data if we are not running
1562 // and there is some message pending.
1563 if (info.parts.Size()) {
1565 }
1566 O2_SIGNPOST_END(device, cid, "channels", "Flushing channel %s which is in state %d and has %zu parts still pending.",
1567 info.channel->GetName().c_str(), (int)info.state, info.parts.Size());
1568 continue;
1569 }
1570 if (info.channel == nullptr) {
1571 O2_SIGNPOST_END(device, cid, "channels", "Channel %s which is in state %d is nullptr and has %zu parts still pending.",
1572 info.channel->GetName().c_str(), (int)info.state, info.parts.Size());
1573 continue;
1574 }
1575 // Only poll DPL channels for now.
1576 if (info.channelType != ChannelAccountingType::DPL) {
1577 O2_SIGNPOST_END(device, cid, "channels", "Channel %s which is in state %d is not a DPL channel and has %zu parts still pending.",
1578 info.channel->GetName().c_str(), (int)info.state, info.parts.Size());
1579 continue;
1580 }
1581 auto& socket = info.channel->GetSocket();
1582 // If we have pending events from a previous iteration,
1583 // we do receive in any case.
1584 // Otherwise we check if there is any pending event and skip
1585 // this channel in case there is none.
1586 if (info.hasPendingEvents == 0) {
1587 socket.Events(&info.hasPendingEvents);
1588 // If we do not read, we can continue.
1589 if ((info.hasPendingEvents & 1) == 0 && (info.parts.Size() == 0)) {
1590 O2_SIGNPOST_END(device, cid, "channels", "No pending events and no remaining parts to process for channel %{public}s", info.channel->GetName().c_str());
1591 continue;
1592 }
1593 }
1594 // We can reset this, because it means we have seen at least 1
1595 // message after the UV_READABLE was raised.
1596 info.readPolled = false;
1597 // Notice that there seems to be a difference between the documentation
1598 // of zeromq and the observed behavior. The fact that ZMQ_POLLIN
1599 // is raised does not mean that a message is immediately available to
1600 // read, just that it will be available soon, so the receive can
1601 // still return -2. To avoid this we keep receiving on the socket until
1602 // we get a message. In order not to overflow the DPL queue we process
1603 // one message at the time and we keep track of wether there were more
1604 // to process.
1605 bool newMessages = false;
1606 while (true) {
1607 O2_SIGNPOST_EVENT_EMIT(device, cid, "channels", "Receiving loop called for channel %{public}s (%d) with oldest possible timeslice %zu",
1608 info.channel->GetName().c_str(), info.id.value, info.oldestForChannel.value);
1609 if (info.parts.Size() < 64) {
1610 fair::mq::Parts parts;
1611 info.channel->Receive(parts, 0);
1612 if (parts.Size()) {
1613 O2_SIGNPOST_EVENT_EMIT(device, cid, "channels", "Received %zu parts from channel %{public}s (%d).", parts.Size(), info.channel->GetName().c_str(), info.id.value);
1614 }
1615 for (auto&& part : parts) {
1616 info.parts.fParts.emplace_back(std::move(part));
1617 }
1618 newMessages |= true;
1619 }
1620
1621 if (info.parts.Size() >= 0) {
1623 // Receiving data counts as activity now, so that
1624 // We can make sure we process all the pending
1625 // messages without hanging on the uv_run.
1626 break;
1627 }
1628 }
1629 // We check once again for pending events, keeping track if this was the
1630 // case so that we can immediately repeat this loop and avoid remaining
1631 // stuck in uv_run. This is because we will not get notified on the socket
1632 // if more events are pending due to zeromq level triggered approach.
1633 socket.Events(&info.hasPendingEvents);
1634 if (info.hasPendingEvents) {
1635 info.readPolled = false;
1636 // In case there were messages, we consider it as activity
1637 if (newMessages) {
1638 state.lastActiveDataProcessor.store(&context);
1639 }
1640 }
1641 O2_SIGNPOST_END(device, cid, "channels", "Done processing channel %{public}s (%d).",
1642 info.channel->GetName().c_str(), info.id.value);
1643 }
1644}
1645
1647{
1648 auto& context = ref.get<DataProcessorContext>();
1649 auto& streamContext = ref.get<StreamContext>();
1650 O2_SIGNPOST_ID_FROM_POINTER(dpid, device, &context);
1651 auto& state = ref.get<DeviceState>();
1652 auto& spec = ref.get<DeviceSpec const>();
1653
1654 if (state.streaming == StreamingState::Idle) {
1655 return;
1656 }
1657
1658 streamContext.completed.clear();
1659 streamContext.completed.reserve(16);
1660 if (DataProcessingDevice::tryDispatchComputation(ref, streamContext.completed)) {
1661 state.lastActiveDataProcessor.store(&context);
1662 }
1663 DanglingContext danglingContext{*context.registry};
1664
1665 context.preDanglingCallbacks(danglingContext);
1666 if (state.lastActiveDataProcessor.load() == nullptr) {
1667 ref.get<CallbackService>().call<CallbackService::Id::Idle>();
1668 }
1669 auto activity = ref.get<DataRelayer>().processDanglingInputs(context.expirationHandlers, *context.registry, true);
1670 if (activity.expiredSlots > 0) {
1671 state.lastActiveDataProcessor = &context;
1672 }
1673
1674 streamContext.completed.clear();
1675 if (DataProcessingDevice::tryDispatchComputation(ref, streamContext.completed)) {
1676 state.lastActiveDataProcessor = &context;
1677 }
1678
1679 context.postDanglingCallbacks(danglingContext);
1680
1681 // If we got notified that all the sources are done, we call the EndOfStream
1682 // callback and return false. Notice that what happens next is actually
1683 // dependent on the callback, not something which is controlled by the
1684 // framework itself.
1685 if (context.allDone == true && state.streaming == StreamingState::Streaming) {
1687 state.lastActiveDataProcessor = &context;
1688 }
1689
1690 if (state.streaming == StreamingState::EndOfStreaming) {
1691 O2_SIGNPOST_EVENT_EMIT(device, dpid, "state", "We are in EndOfStreaming. Flushing queues.");
1692 // We keep processing data until we are Idle.
1693 // FIXME: not sure this is the correct way to drain the queues, but
1694 // I guess we will see.
1697 auto& relayer = ref.get<DataRelayer>();
1698
1699 bool shouldProcess = DataProcessingHelpers::hasOnlyGenerated(spec) == false;
1700
1701 while (DataProcessingDevice::tryDispatchComputation(ref, streamContext.completed) && shouldProcess) {
1702 relayer.processDanglingInputs(context.expirationHandlers, *context.registry, false);
1703 }
1704
1705 auto& timingInfo = ref.get<TimingInfo>();
1706 // We should keep the data generated at end of stream only for those
1707 // which are not sources.
1708 timingInfo.keepAtEndOfStream = shouldProcess;
1709 // Fill timinginfo with some reasonable values for data sent with endOfStream
1710 timingInfo.timeslice = relayer.getOldestPossibleOutput().timeslice.value;
1711 timingInfo.tfCounter = -1;
1712 timingInfo.firstTForbit = -1;
1713 // timingInfo.runNumber = ; // Not sure where to get this if not already set
1714 timingInfo.creation = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count();
1715 O2_SIGNPOST_EVENT_EMIT(calibration, dpid, "calibration", "TimingInfo.keepAtEndOfStream %d", timingInfo.keepAtEndOfStream);
1716
1717 EndOfStreamContext eosContext{*context.registry, ref.get<DataAllocator>()};
1718
1719 context.preEOSCallbacks(eosContext);
1720 auto& streamContext = ref.get<StreamContext>();
1721 streamContext.preEOSCallbacks(eosContext);
1722 ref.get<CallbackService>().call<CallbackService::Id::EndOfStream>(eosContext);
1723 streamContext.postEOSCallbacks(eosContext);
1724 context.postEOSCallbacks(eosContext);
1725
1726 for (auto& channel : spec.outputChannels) {
1727 O2_SIGNPOST_EVENT_EMIT(device, dpid, "state", "Sending end of stream to %{public}s.", channel.name.c_str());
1729 }
1730 // This is needed because the transport is deleted before the device.
1731 relayer.clear();
1733 // In case we should process, note the data processor responsible for it
1734 if (shouldProcess) {
1735 state.lastActiveDataProcessor = &context;
1736 }
1737 // On end of stream we shut down all output pollers.
1738 O2_SIGNPOST_EVENT_EMIT(device, dpid, "state", "Shutting down output pollers.");
1739 for (auto& poller : state.activeOutputPollers) {
1740 uv_poll_stop(poller);
1741 }
1742 return;
1743 }
1744
1745 if (state.streaming == StreamingState::Idle) {
1746 // On end of stream we shut down all output pollers.
1747 O2_SIGNPOST_EVENT_EMIT(device, dpid, "state", "Shutting down output pollers.");
1748 for (auto& poller : state.activeOutputPollers) {
1749 uv_poll_stop(poller);
1750 }
1751 }
1752
1753 return;
1754}
1755
1757{
1758 ServiceRegistryRef ref{mServiceRegistry};
1759 ref.get<DataRelayer>().clear();
1760 auto& deviceContext = ref.get<DeviceContext>();
1761 // If the signal handler is there, we should
1762 // hide the registry from it, so that we do not
1763 // end up calling the signal handler on something
1764 // which might not be there anymore.
1765 if (deviceContext.sigusr1Handle) {
1766 deviceContext.sigusr1Handle->data = nullptr;
1767 }
1768 // Makes sure we do not have a working context on
1769 // shutdown.
1770 for (auto& handle : ref.get<DeviceState>().activeSignals) {
1771 handle->data = nullptr;
1772 }
1773}
1774
1777 {
1778 }
1779};
1780
1781auto forwardOnInsertion(ServiceRegistryRef& ref, std::span<fair::mq::MessagePtr>& messages) -> void
1782{
1783 O2_SIGNPOST_ID_GENERATE(sid, forwarding);
1784
1785 auto& spec = ref.get<DeviceSpec const>();
1786 auto& context = ref.get<DataProcessorContext>();
1787 if (context.forwardPolicy == ForwardPolicy::AfterProcessing || spec.forwards.empty()) {
1788 O2_SIGNPOST_EVENT_EMIT(device, sid, "device", "Early forwardinding not enabled / needed.");
1789 return;
1790 }
1791
1792 O2_SIGNPOST_EVENT_EMIT(device, sid, "device", "Early forwardinding before injecting data into relayer.");
1793 auto& timesliceIndex = ref.get<TimesliceIndex>();
1794 auto oldestTimeslice = timesliceIndex.getOldestPossibleOutput();
1795
1796 auto& proxy = ref.get<FairMQDeviceProxy>();
1797
1798 O2_SIGNPOST_START(forwarding, sid, "forwardInputs",
1799 "Starting forwarding for incoming messages with oldestTimeslice %zu with copy",
1800 oldestTimeslice.timeslice.value);
1801 std::vector<fair::mq::Parts> forwardedParts(proxy.getNumForwardChannels());
1802 DataProcessingHelpers::routeForwardedMessages(proxy, messages, forwardedParts, true, false);
1803
1804 for (int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
1805 if (forwardedParts[fi].Size() == 0) {
1806 continue;
1807 }
1808 ForwardChannelInfo info = proxy.getForwardChannelInfo(ChannelIndex{fi});
1809 auto& parts = forwardedParts[fi];
1810 if (info.policy == nullptr) {
1811 O2_SIGNPOST_EVENT_EMIT_ERROR(forwarding, sid, "forwardInputs", "Forwarding to %{public}s %d has no policy.", info.name.c_str(), fi);
1812 continue;
1813 }
1814 O2_SIGNPOST_EVENT_EMIT(forwarding, sid, "forwardInputs", "Forwarding to %{public}s %d", info.name.c_str(), fi);
1815 info.policy->forward(parts, ChannelIndex{fi}, ref);
1816 }
1817 auto& asyncQueue = ref.get<AsyncQueue>();
1818 auto& decongestion = ref.get<DecongestionService>();
1819 O2_SIGNPOST_ID_GENERATE(aid, async_queue);
1820 O2_SIGNPOST_EVENT_EMIT(async_queue, aid, "forwardInputs", "Queuing forwarding oldestPossible %zu", oldestTimeslice.timeslice.value);
1821 AsyncQueueHelpers::post(asyncQueue, AsyncTask{.timeslice = oldestTimeslice.timeslice, .id = decongestion.oldestPossibleTimesliceTask, .debounce = -1, .callback = decongestionCallbackLate}
1822 .user<DecongestionContext>({.ref = ref, .oldestTimeslice = oldestTimeslice}));
1823 O2_SIGNPOST_END(forwarding, sid, "forwardInputs", "Forwarding done");
1824};
1825
1831{
1834
1835 auto& context = ref.get<DataProcessorContext>();
1836 // This is the same id as the upper level function, so we get the events
1837 // associated with the same interval. We will simply use "handle_data" as
1838 // the category.
1839 O2_SIGNPOST_ID_FROM_POINTER(cid, device, &info);
1840
1841 // This is how we validate inputs. I.e. we try to enforce the O2 Data model
1842 // and we do a few stats. We bind parts as a lambda captured variable, rather
1843 // than an input, because we do not want the outer loop actually be exposed
1844 // to the implementation details of the messaging layer.
1845 auto getInputTypes = [&info, &context]() -> std::optional<std::vector<InputInfo>> {
1846 O2_SIGNPOST_ID_FROM_POINTER(cid, device, &info);
1847 auto ref = ServiceRegistryRef{*context.registry};
1848 auto& stats = ref.get<DataProcessingStats>();
1849 auto& state = ref.get<DeviceState>();
1850 auto& parts = info.parts;
1851 stats.updateStats({(int)ProcessingStatsId::TOTAL_INPUTS, DataProcessingStats::Op::Set, (int64_t)parts.Size()});
1852
1853 std::vector<InputInfo> results;
1854 // we can reserve the upper limit
1855 results.reserve(parts.Size() / 2);
1856 size_t nTotalPayloads = 0;
1857
1858 auto insertInputInfo = [&results, &nTotalPayloads](size_t position, size_t length, InputType type, ChannelIndex index) {
1859 results.emplace_back(position, length, type, index);
1860 if (type != InputType::Invalid && length > 1) {
1861 nTotalPayloads += length - 1;
1862 }
1863 };
1864
1865 for (size_t pi = 0; pi < parts.Size(); pi += 2) {
1866 auto* headerData = parts.At(pi)->GetData();
1867 auto sih = o2::header::get<SourceInfoHeader*>(headerData);
1868 auto dh = o2::header::get<DataHeader*>(headerData);
1869 if (sih) {
1870 O2_SIGNPOST_EVENT_EMIT(device, cid, "handle_data", "Got SourceInfoHeader with state %d", (int)sih->state);
1871 info.state = sih->state;
1872 insertInputInfo(pi, 2, InputType::SourceInfo, info.id);
1873 state.lastActiveDataProcessor = &context;
1874 if (dh) {
1875 LOGP(error, "Found data attached to a SourceInfoHeader");
1876 }
1877 continue;
1878 }
1879 auto dih = o2::header::get<DomainInfoHeader*>(headerData);
1880 if (dih) {
1881 O2_SIGNPOST_EVENT_EMIT(device, cid, "handle_data", "Got DomainInfoHeader with oldestPossibleTimeslice %d", (int)dih->oldestPossibleTimeslice);
1882 insertInputInfo(pi, 2, InputType::DomainInfo, info.id);
1883 state.lastActiveDataProcessor = &context;
1884 if (dh) {
1885 LOGP(error, "Found data attached to a DomainInfoHeader");
1886 }
1887 continue;
1888 }
1889 if (!dh) {
1890 insertInputInfo(pi, 0, InputType::Invalid, info.id);
1891 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid, "handle_data", "Header is not a DataHeader?");
1892 continue;
1893 }
1894 if (dh->payloadSize > parts.At(pi + 1)->GetSize()) {
1895 insertInputInfo(pi, 0, InputType::Invalid, info.id);
1896 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid, "handle_data", "DataHeader payloadSize mismatch");
1897 continue;
1898 }
1899 auto dph = o2::header::get<DataProcessingHeader*>(headerData);
1900 // We only deal with the tracking of parts if the log is enabled.
1901 // This is because in principle we should track the size of each of
1902 // the parts and sum it up. Not for now.
1903 O2_SIGNPOST_ID_FROM_POINTER(pid, parts, headerData);
1904 O2_SIGNPOST_START(parts, pid, "parts", "Processing DataHeader %{public}-4s/%{public}-16s/%d with splitPayloadParts %d and splitPayloadIndex %d",
1905 dh->dataOrigin.str, dh->dataDescription.str, dh->subSpecification, dh->splitPayloadParts, dh->splitPayloadIndex);
1906 if (!dph) {
1907 insertInputInfo(pi, 2, InputType::Invalid, info.id);
1908 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid, "handle_data", "Header stack does not contain DataProcessingHeader");
1909 continue;
1910 }
1911 if (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) {
1912 // this is indicating a sequence of payloads following the header
1913 // FIXME: we will probably also set the DataHeader version
1914 insertInputInfo(pi, dh->splitPayloadParts + 1, InputType::Data, info.id);
1915 pi += dh->splitPayloadParts - 1;
1916 } else {
1917 // We can set the type for the next splitPayloadParts
1918 // because we are guaranteed they are all the same.
1919 // If splitPayloadParts = 0, we assume that means there is only one (header, payload)
1920 // pair.
1921 size_t finalSplitPayloadIndex = pi + (dh->splitPayloadParts > 0 ? dh->splitPayloadParts : 1) * 2;
1922 if (finalSplitPayloadIndex > parts.Size()) {
1923 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid, "handle_data", "DataHeader::splitPayloadParts invalid");
1924 insertInputInfo(pi, 0, InputType::Invalid, info.id);
1925 continue;
1926 }
1927 insertInputInfo(pi, 2, InputType::Data, info.id);
1928 for (; pi + 2 < finalSplitPayloadIndex; pi += 2) {
1929 insertInputInfo(pi + 2, 2, InputType::Data, info.id);
1930 }
1931 }
1932 }
1933 if (results.size() + nTotalPayloads != parts.Size()) {
1934 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid, "handle_data", "inconsistent number of inputs extracted. %zu vs parts (%zu)", results.size() + nTotalPayloads, parts.Size());
1935 return std::nullopt;
1936 }
1937 return results;
1938 };
1939
1940 auto reportError = [ref](const char* message) {
1941 auto& stats = ref.get<DataProcessingStats>();
1943 };
1944
1945 auto handleValidMessages = [&info, ref, &reportError, &context](std::vector<InputInfo> const& inputInfos) {
1946 auto& relayer = ref.get<DataRelayer>();
1947 auto& state = ref.get<DeviceState>();
1948 static WaitBackpressurePolicy policy;
1949 auto& parts = info.parts;
1950 // We relay execution to make sure we have a complete set of parts
1951 // available.
1952 bool hasBackpressure = false;
1953 size_t minBackpressureTimeslice = -1;
1954 bool hasData = false;
1955 size_t oldestPossibleTimeslice = -1;
1956 static std::vector<int> ordering;
1957 // Same as inputInfos but with iota.
1958 ordering.resize(inputInfos.size());
1959 std::iota(ordering.begin(), ordering.end(), 0);
1960 // stable sort orderings by type and position
1961 std::stable_sort(ordering.begin(), ordering.end(), [&inputInfos](int const& a, int const& b) {
1962 auto const& ai = inputInfos[a];
1963 auto const& bi = inputInfos[b];
1964 if (ai.type != bi.type) {
1965 return ai.type < bi.type;
1966 }
1967 return ai.position < bi.position;
1968 });
1969 for (size_t ii = 0; ii < inputInfos.size(); ++ii) {
1970 auto const& input = inputInfos[ordering[ii]];
1971 switch (input.type) {
1972 case InputType::Data: {
1973 hasData = true;
1974 auto headerIndex = input.position;
1975 auto nMessages = 0;
1976 auto nPayloadsPerHeader = 0;
1977 if (input.size > 2) {
1978 // header and multiple payload sequence
1979 nMessages = input.size;
1980 nPayloadsPerHeader = nMessages - 1;
1981 } else {
1982 // multiple header-payload pairs
1983 auto dh = o2::header::get<DataHeader*>(parts.At(headerIndex)->GetData());
1984 nMessages = dh->splitPayloadParts > 0 ? dh->splitPayloadParts * 2 : 2;
1985 nPayloadsPerHeader = 1;
1986 ii += (nMessages / 2) - 1;
1987 }
1988 auto onDrop = [ref](TimesliceSlot slot, std::vector<std::vector<fair::mq::MessagePtr>>& dropped, TimesliceIndex::OldestOutputInfo oldestOutputInfo) {
1989 O2_SIGNPOST_ID_GENERATE(cid, async_queue);
1990 O2_SIGNPOST_EVENT_EMIT(async_queue, cid, "onDrop", "Dropping message from slot %zu. Forwarding as needed. Timeslice %zu",
1991 slot.index, oldestOutputInfo.timeslice.value);
1992 ref.get<AsyncQueue>();
1993 ref.get<DecongestionService>();
1994 ref.get<DataRelayer>();
1995 // Get the current timeslice for the slot.
1996 auto& variables = ref.get<TimesliceIndex>().getVariablesForSlot(slot);
1998 forwardInputs(ref, slot, dropped, oldestOutputInfo, false, true);
1999 };
2000
2001 auto relayed = relayer.relay(parts.At(headerIndex)->GetData(),
2002 &parts.At(headerIndex),
2003 input,
2004 nMessages,
2005 nPayloadsPerHeader,
2006 context.forwardPolicy == ForwardPolicy::AtInjection ? forwardOnInsertion : nullptr,
2007 onDrop);
2008 switch (relayed.type) {
2010 if (info.normalOpsNotified == true && info.backpressureNotified == false) {
2011 LOGP(alarm, "Backpressure on channel {}. Waiting.", info.channel->GetName());
2012 auto& monitoring = ref.get<o2::monitoring::Monitoring>();
2013 monitoring.send(o2::monitoring::Metric{1, fmt::format("backpressure_{}", info.channel->GetName())});
2014 info.backpressureNotified = true;
2015 info.normalOpsNotified = false;
2016 }
2017 policy.backpressure(info);
2018 hasBackpressure = true;
2019 minBackpressureTimeslice = std::min<size_t>(minBackpressureTimeslice, relayed.timeslice.value);
2020 break;
2024 if (info.normalOpsNotified == false && info.backpressureNotified == true) {
2025 LOGP(info, "Back to normal on channel {}.", info.channel->GetName());
2026 auto& monitoring = ref.get<o2::monitoring::Monitoring>();
2027 monitoring.send(o2::monitoring::Metric{0, fmt::format("backpressure_{}", info.channel->GetName())});
2028 info.normalOpsNotified = true;
2029 info.backpressureNotified = false;
2030 }
2031 break;
2032 }
2033 } break;
2034 case InputType::SourceInfo: {
2035 LOGP(detail, "Received SourceInfo");
2036 auto& context = ref.get<DataProcessorContext>();
2037 state.lastActiveDataProcessor = &context;
2038 auto headerIndex = input.position;
2039 auto payloadIndex = input.position + 1;
2040 assert(payloadIndex < parts.Size());
2041 // FIXME: the message with the end of stream cannot contain
2042 // split parts.
2043 parts.At(headerIndex).reset(nullptr);
2044 parts.At(payloadIndex).reset(nullptr);
2045 // for (size_t i = 0; i < dh->splitPayloadParts > 0 ? dh->splitPayloadParts * 2 - 1 : 1; ++i) {
2046 // parts.At(headerIndex + 1 + i).reset(nullptr);
2047 // }
2048 // pi += dh->splitPayloadParts > 0 ? dh->splitPayloadParts - 1 : 0;
2049
2050 } break;
2051 case InputType::DomainInfo: {
2054 auto& context = ref.get<DataProcessorContext>();
2055 state.lastActiveDataProcessor = &context;
2056 auto headerIndex = input.position;
2057 auto payloadIndex = input.position + 1;
2058 assert(payloadIndex < parts.Size());
2059 // FIXME: the message with the end of stream cannot contain
2060 // split parts.
2061
2062 auto dih = o2::header::get<DomainInfoHeader*>(parts.At(headerIndex)->GetData());
2063 if (hasBackpressure && dih->oldestPossibleTimeslice >= minBackpressureTimeslice) {
2064 break;
2065 }
2066 oldestPossibleTimeslice = std::min(oldestPossibleTimeslice, dih->oldestPossibleTimeslice);
2067 LOGP(debug, "Got DomainInfoHeader, new oldestPossibleTimeslice {} on channel {}", oldestPossibleTimeslice, info.id.value);
2068 parts.At(headerIndex).reset(nullptr);
2069 parts.At(payloadIndex).reset(nullptr);
2070 } break;
2071 case InputType::Invalid: {
2072 reportError("Invalid part found.");
2073 } break;
2074 }
2075 }
2078 if (oldestPossibleTimeslice != (size_t)-1) {
2079 info.oldestForChannel = {oldestPossibleTimeslice};
2080 auto& context = ref.get<DataProcessorContext>();
2081 context.domainInfoUpdatedCallback(*context.registry, oldestPossibleTimeslice, info.id);
2082 ref.get<CallbackService>().call<CallbackService::Id::DomainInfoUpdated>((ServiceRegistryRef)*context.registry, (size_t)oldestPossibleTimeslice, (ChannelIndex)info.id);
2083 state.lastActiveDataProcessor = &context;
2084 }
2085 auto it = std::remove_if(parts.fParts.begin(), parts.fParts.end(), [](auto& msg) -> bool { return msg.get() == nullptr; });
2086 parts.fParts.erase(it, parts.end());
2087 if (parts.fParts.size()) {
2088 LOG(debug) << parts.fParts.size() << " messages backpressured";
2089 }
2090 };
2091
2092 // Second part. This is the actual outer loop we want to obtain, with
2093 // implementation details which can be read. Notice how most of the state
2094 // is actually hidden. For example we do not expose what "input" is. This
2095 // will allow us to keep the same toplevel logic even if the actual meaning
2096 // of input is changed (for example we might move away from multipart
2097 // messages). Notice also that we need to act diffently depending on the
2098 // actual CompletionOp we want to perform. In particular forwarding inputs
2099 // also gets rid of them from the cache.
2100 auto inputTypes = getInputTypes();
2101 if (bool(inputTypes) == false) {
2102 reportError("Parts should come in couples. Dropping it.");
2103 return;
2104 }
2105 handleValidMessages(*inputTypes);
2106 return;
2107}
2108
2109namespace
2110{
2111struct InputLatency {
2112 uint64_t minLatency = std::numeric_limits<uint64_t>::max();
2113 uint64_t maxLatency = std::numeric_limits<uint64_t>::min();
2114};
2115
2116auto calculateInputRecordLatency(InputRecord const& record, uint64_t currentTime) -> InputLatency
2117{
2118 InputLatency result;
2119
2120 for (auto& item : record) {
2121 auto* header = o2::header::get<DataProcessingHeader*>(item.header);
2122 if (header == nullptr) {
2123 continue;
2124 }
2125 int64_t partLatency = (0x7fffffffffffffff & currentTime) - (0x7fffffffffffffff & header->creation);
2126 if (partLatency < 0) {
2127 partLatency = 0;
2128 }
2129 result.minLatency = std::min(result.minLatency, (uint64_t)partLatency);
2130 result.maxLatency = std::max(result.maxLatency, (uint64_t)partLatency);
2131 }
2132 return result;
2133};
2134
2135auto calculateTotalInputRecordSize(InputRecord const& record) -> int
2136{
2137 size_t totalInputSize = 0;
2138 for (auto& item : record) {
2139 auto* header = o2::header::get<DataHeader*>(item.header);
2140 if (header == nullptr) {
2141 continue;
2142 }
2143 totalInputSize += header->payloadSize;
2144 }
2145 return totalInputSize;
2146};
2147
2148template <typename T>
2149void update_maximum(std::atomic<T>& maximum_value, T const& value) noexcept
2150{
2151 T prev_value = maximum_value;
2152 while (prev_value < value &&
2153 !maximum_value.compare_exchange_weak(prev_value, value)) {
2154 }
2155}
2156} // namespace
2157
2158bool DataProcessingDevice::tryDispatchComputation(ServiceRegistryRef ref, std::vector<DataRelayer::RecordAction>& completed)
2159{
2160 auto& context = ref.get<DataProcessorContext>();
2161 LOGP(debug, "DataProcessingDevice::tryDispatchComputation");
2162 // This is the actual hidden state for the outer loop. In case we decide we
2163 // want to support multithreaded dispatching of operations, I can simply
2164 // move these to some thread local store and the rest of the lambdas
2165 // should work just fine.
2166 std::vector<std::vector<fair::mq::MessagePtr>> currentSetOfInputs;
2167
2168 //
2169 auto getInputSpan = [ref, &currentSetOfInputs](TimesliceSlot slot, bool consume = true) {
2170 auto& relayer = ref.get<DataRelayer>();
2171 if (consume) {
2172 currentSetOfInputs = relayer.consumeAllInputsForTimeslice(slot);
2173 } else {
2174 currentSetOfInputs = relayer.consumeExistingInputsForTimeslice(slot);
2175 }
2176 // Convert raw message indices directly to a DataRef in O(1).
2177 // Used both by the sequential PartIterator and as the fallback for positional access.
2178 auto indicesGetter = [&currentSetOfInputs](size_t i, DataRefIndices indices) -> DataRef {
2179 auto const& msgs = currentSetOfInputs[i];
2180 if (msgs.size() <= indices.headerIdx) {
2181 return DataRef{};
2182 }
2183 auto const& headerMsg = msgs[indices.headerIdx];
2184 char const* payloadData = nullptr;
2185 size_t payloadSize = 0;
2186 if (msgs.size() > indices.payloadIdx && msgs[indices.payloadIdx]) {
2187 payloadData = static_cast<char const*>(msgs[indices.payloadIdx]->GetData());
2188 payloadSize = msgs[indices.payloadIdx]->GetSize();
2189 }
2190 return DataRef{nullptr,
2191 headerMsg ? static_cast<char const*>(headerMsg->GetData()) : nullptr,
2192 payloadData,
2193 payloadSize};
2194 };
2195 auto nofPartsGetter = [&currentSetOfInputs](size_t i) -> size_t {
2196 return (currentSetOfInputs[i] | count_payloads{});
2197 };
2198 auto refCountGetter = [&currentSetOfInputs](size_t idx) -> int {
2199 auto& header = static_cast<const fair::mq::shmem::Message&>(*(currentSetOfInputs[idx] | get_header{0}));
2200 return header.GetRefCount();
2201 };
2202 auto nextIndicesGetter = [&currentSetOfInputs](size_t i, DataRefIndices current) -> DataRefIndices {
2203 auto next = currentSetOfInputs[i] | get_next_pair{current};
2204 return next.headerIdx < currentSetOfInputs[i].size() ? next : DataRefIndices{size_t(-1), size_t(-1)};
2205 };
2206 return InputSpan{nofPartsGetter, refCountGetter, indicesGetter, nextIndicesGetter, currentSetOfInputs.size()};
2207 };
2208
2209 auto markInputsAsDone = [ref](TimesliceSlot slot) -> void {
2210 auto& relayer = ref.get<DataRelayer>();
2212 };
2213
2214 // I need a preparation step which gets the current timeslice id and
2215 // propagates it to the various contextes (i.e. the actual entities which
2216 // create messages) because the messages need to have the timeslice id into
2217 // it.
2218 auto prepareAllocatorForCurrentTimeSlice = [ref](TimesliceSlot i) -> void {
2219 auto& relayer = ref.get<DataRelayer>();
2220 auto& timingInfo = ref.get<TimingInfo>();
2221 auto timeslice = relayer.getTimesliceForSlot(i);
2222
2223 timingInfo.timeslice = timeslice.value;
2224 timingInfo.tfCounter = relayer.getFirstTFCounterForSlot(i);
2225 timingInfo.firstTForbit = relayer.getFirstTFOrbitForSlot(i);
2226 timingInfo.runNumber = relayer.getRunNumberForSlot(i);
2227 timingInfo.creation = relayer.getCreationTimeForSlot(i);
2228 };
2229 auto updateRunInformation = [ref](TimesliceSlot i) -> void {
2230 auto& dataProcessorContext = ref.get<DataProcessorContext>();
2231 auto& relayer = ref.get<DataRelayer>();
2232 auto& timingInfo = ref.get<TimingInfo>();
2233 auto timeslice = relayer.getTimesliceForSlot(i);
2234 // We report wether or not this timing info refers to a new Run.
2235 timingInfo.globalRunNumberChanged = !TimingInfo::timesliceIsTimer(timeslice.value) && dataProcessorContext.lastRunNumberProcessed != timingInfo.runNumber;
2236 // A switch to runNumber=0 should not appear and thus does not set globalRunNumberChanged, unless it is seen in the first processed timeslice
2237 timingInfo.globalRunNumberChanged &= (dataProcessorContext.lastRunNumberProcessed == -1 || timingInfo.runNumber != 0);
2238 // FIXME: for now there is only one stream, however we
2239 // should calculate this correctly once we finally get the
2240 // the StreamContext in.
2241 timingInfo.streamRunNumberChanged = timingInfo.globalRunNumberChanged;
2242 };
2243
2244 // When processing them, timers will have to be cleaned up
2245 // to avoid double counting them.
2246 // This was actually the easiest solution we could find for
2247 // O2-646.
2248 auto cleanTimers = [&currentSetOfInputs](TimesliceSlot slot, InputRecord& record) {
2249 assert(record.size() == currentSetOfInputs.size());
2250 for (size_t ii = 0, ie = record.size(); ii < ie; ++ii) {
2251 // assuming that for timer inputs we do have exactly one PartRef object
2252 // in the MessageSet, multiple PartRef Objects are only possible for either
2253 // split payload messages of wildcard matchers, both for data inputs
2254 DataRef input = record.getByPos(ii);
2255 if (input.spec->lifetime != Lifetime::Timer) {
2256 continue;
2257 }
2258 if (input.header == nullptr) {
2259 continue;
2260 }
2261 // This will hopefully delete the message.
2262 currentSetOfInputs[ii].clear();
2263 }
2264 };
2265
2266 // Function to cleanup record. For the moment we
2267 // simply use it to keep track of input messages
2268 // which are not needed, to display them in the GUI.
2269 auto cleanupRecord = [](InputRecord& record) {
2270 if (O2_LOG_ENABLED(parts) == false) {
2271 return;
2272 }
2273 for (size_t pi = 0, pe = record.size(); pi < pe; ++pi) {
2274 DataRef input = record.getByPos(pi);
2275 if (input.header == nullptr) {
2276 continue;
2277 }
2278 auto sih = o2::header::get<SourceInfoHeader*>(input.header);
2279 if (sih) {
2280 continue;
2281 }
2282
2283 auto dh = o2::header::get<DataHeader*>(input.header);
2284 if (!dh) {
2285 continue;
2286 }
2287 // We use the address of the first header of a split payload
2288 // to identify the interval.
2289 O2_SIGNPOST_ID_FROM_POINTER(pid, parts, dh);
2290 O2_SIGNPOST_END(parts, pid, "parts", "Cleaning up parts associated to %p", dh);
2291
2292 // No split parts, we simply skip the payload
2293 if (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) {
2294 // this is indicating a sequence of payloads following the header
2295 // FIXME: we will probably also set the DataHeader version
2296 pi += dh->splitPayloadParts - 1;
2297 } else {
2298 size_t pi = pi + (dh->splitPayloadParts > 0 ? dh->splitPayloadParts : 1) * 2;
2299 }
2300 }
2301 };
2302
2303 ref.get<DataRelayer>().getReadyToProcess(completed);
2304 if (completed.empty() == true) {
2305 LOGP(debug, "No computations available for dispatching.");
2306 return false;
2307 }
2308
2309 int pipelineLength = DefaultsHelpers::pipelineLength(*ref.get<RawDeviceService>().device()->fConfig);
2310
2311 auto postUpdateStats = [ref, pipelineLength](DataRelayer::RecordAction const& action, InputRecord const& record, uint64_t tStart, uint64_t tStartMilli) {
2312 auto& stats = ref.get<DataProcessingStats>();
2313 auto& states = ref.get<DataProcessingStates>();
2314 std::atomic_thread_fence(std::memory_order_release);
2315 char relayerSlotState[1024];
2316 int written = snprintf(relayerSlotState, 1024, "%d ", pipelineLength);
2317 char* buffer = relayerSlotState + written;
2318 for (size_t ai = 0; ai != record.size(); ai++) {
2319 buffer[ai] = record.isValid(ai) ? '3' : '0';
2320 }
2321 buffer[record.size()] = 0;
2322 states.updateState({.id = short((int)ProcessingStateId::DATA_RELAYER_BASE + action.slot.index),
2323 .size = (int)(record.size() + buffer - relayerSlotState),
2324 .data = relayerSlotState});
2325 uint64_t tEnd = uv_hrtime();
2326 // tEnd and tStart are in nanoseconds according to https://docs.libuv.org/en/v1.x/misc.html#c.uv_hrtime
2327 int64_t wallTimeMs = (tEnd - tStart) / 1000000;
2329 // Sum up the total wall time, in milliseconds.
2331 // The time interval is in seconds while tEnd - tStart is in nanoseconds, so we divide by 1000000 to get the fraction in ms/s.
2333 stats.updateStats({(int)ProcessingStatsId::LAST_PROCESSED_SIZE, DataProcessingStats::Op::Set, calculateTotalInputRecordSize(record)});
2334 stats.updateStats({(int)ProcessingStatsId::TOTAL_PROCESSED_SIZE, DataProcessingStats::Op::Add, calculateTotalInputRecordSize(record)});
2335 auto latency = calculateInputRecordLatency(record, tStartMilli);
2336 stats.updateStats({(int)ProcessingStatsId::LAST_MIN_LATENCY, DataProcessingStats::Op::Set, (int)latency.minLatency});
2337 stats.updateStats({(int)ProcessingStatsId::LAST_MAX_LATENCY, DataProcessingStats::Op::Set, (int)latency.maxLatency});
2338 static int count = 0;
2340 count++;
2341 };
2342
2343 auto preUpdateStats = [ref, pipelineLength](DataRelayer::RecordAction const& action, InputRecord const& record, uint64_t) {
2344 auto& states = ref.get<DataProcessingStates>();
2345 std::atomic_thread_fence(std::memory_order_release);
2346 char relayerSlotState[1024];
2347 snprintf(relayerSlotState, 1024, "%d ", pipelineLength);
2348 char* buffer = strchr(relayerSlotState, ' ') + 1;
2349 for (size_t ai = 0; ai != record.size(); ai++) {
2350 buffer[ai] = record.isValid(ai) ? '2' : '0';
2351 }
2352 buffer[record.size()] = 0;
2353 states.updateState({.id = short((int)ProcessingStateId::DATA_RELAYER_BASE + action.slot.index), .size = (int)(record.size() + buffer - relayerSlotState), .data = relayerSlotState});
2354 };
2355
2356 // This is the main dispatching loop
2357 auto& state = ref.get<DeviceState>();
2358 auto& spec = ref.get<DeviceSpec const>();
2359
2360 auto& dpContext = ref.get<DataProcessorContext>();
2361 auto& streamContext = ref.get<StreamContext>();
2362 O2_SIGNPOST_ID_GENERATE(sid, device);
2363 O2_SIGNPOST_START(device, sid, "device", "Start processing ready actions");
2364
2365 auto& stats = ref.get<DataProcessingStats>();
2366 auto& relayer = ref.get<DataRelayer>();
2367 using namespace o2::framework;
2368 stats.updateStats({(int)ProcessingStatsId::PENDING_INPUTS, DataProcessingStats::Op::Set, static_cast<int64_t>(relayer.getParallelTimeslices() - completed.size())});
2369 stats.updateStats({(int)ProcessingStatsId::INCOMPLETE_INPUTS, DataProcessingStats::Op::Set, completed.empty() ? 1 : 0});
2370 switch (spec.completionPolicy.order) {
2372 std::sort(completed.begin(), completed.end(), [](auto const& a, auto const& b) { return a.timeslice.value < b.timeslice.value; });
2373 break;
2375 std::sort(completed.begin(), completed.end(), [](auto const& a, auto const& b) { return a.slot.index < b.slot.index; });
2376 break;
2378 default:
2379 break;
2380 }
2381
2382 for (auto action : completed) {
2383 O2_SIGNPOST_ID_GENERATE(aid, device);
2384 O2_SIGNPOST_START(device, aid, "device", "Processing action on slot %lu for action %{public}s", action.slot.index, fmt::format("{}", action.op).c_str());
2385 if (action.op == CompletionPolicy::CompletionOp::Wait) {
2386 O2_SIGNPOST_END(device, aid, "device", "Waiting for more data.");
2387 continue;
2388 }
2389
2390 bool shouldConsume = action.op == CompletionPolicy::CompletionOp::Consume ||
2392 prepareAllocatorForCurrentTimeSlice(TimesliceSlot{action.slot});
2393 if (action.op != CompletionPolicy::CompletionOp::Discard &&
2396 updateRunInformation(TimesliceSlot{action.slot});
2397 }
2398 InputSpan span = getInputSpan(action.slot, shouldConsume);
2399 auto& spec = ref.get<DeviceSpec const>();
2400 InputRecord record{spec.inputs,
2401 span,
2402 *context.registry};
2403 ProcessingContext processContext{record, ref, ref.get<DataAllocator>()};
2404 {
2405 // Notice this should be thread safe and reentrant
2406 // as it is called from many threads.
2407 streamContext.preProcessingCallbacks(processContext);
2408 dpContext.preProcessingCallbacks(processContext);
2409 }
2410 if (action.op == CompletionPolicy::CompletionOp::Discard) {
2411 context.postDispatchingCallbacks(processContext);
2412 if (spec.forwards.empty() == false) {
2413 auto& timesliceIndex = ref.get<TimesliceIndex>();
2414 forwardInputs(ref, action.slot, currentSetOfInputs, timesliceIndex.getOldestPossibleOutput(), false);
2415 O2_SIGNPOST_END(device, aid, "device", "Forwarding inputs consume: %d.", false);
2416 continue;
2417 }
2418 }
2419 // If there is no optional inputs we canForwardEarly
2420 // the messages to that parallel processing can happen.
2421 // In this case we pass true to indicate that we want to
2422 // copy the messages to the subsequent data processor.
2423 bool hasForwards = spec.forwards.empty() == false;
2424 bool consumeSomething = action.op == CompletionPolicy::CompletionOp::Consume || action.op == CompletionPolicy::CompletionOp::ConsumeExisting;
2425
2426 if (context.forwardPolicy == ForwardPolicy::AtCompletionPolicySatisified && hasForwards && consumeSomething) {
2427 O2_SIGNPOST_EVENT_EMIT(device, aid, "device", "Early forwarding: %{public}s.", fmt::format("{}", action.op).c_str());
2428 auto& timesliceIndex = ref.get<TimesliceIndex>();
2429 forwardInputs(ref, action.slot, currentSetOfInputs, timesliceIndex.getOldestPossibleOutput(), true, action.op == CompletionPolicy::CompletionOp::Consume);
2430 } else if (context.forwardPolicy == ForwardPolicy::AtInjection && hasForwards && consumeSomething) {
2431 // We used to do fowarding here, however we now do it much earlier.
2432 // We still need to clean the inputs which were already consumed
2433 // via ConsumeExisting and which still have an header to hold the slot.
2434 // FIXME: do we? This should really happen when we do the forwarding on
2435 // insertion, because otherwise we lose the relevant information on how to
2436 // navigate the set of headers. We could actually rely on the messageset index,
2437 // is that the right thing to do though?
2438 O2_SIGNPOST_EVENT_EMIT(device, aid, "device", "cleaning early forwarding: %{public}s.", fmt::format("{}", action.op).c_str());
2439 auto& timesliceIndex = ref.get<TimesliceIndex>();
2440 cleanEarlyForward(ref, action.slot, currentSetOfInputs, timesliceIndex.getOldestPossibleOutput(), true, action.op == CompletionPolicy::CompletionOp::Consume);
2441 }
2442
2443 markInputsAsDone(action.slot);
2444
2445 uint64_t tStart = uv_hrtime();
2446 uint64_t tStartMilli = TimingHelpers::getRealtimeSinceEpochStandalone();
2447 preUpdateStats(action, record, tStart);
2448
2449 static bool noCatch = getenv("O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv("O2_NO_CATCHALL_EXCEPTIONS"), "0");
2450
2451 auto runNoCatch = [&context, ref, &processContext](DataRelayer::RecordAction& action) mutable {
2452 auto& state = ref.get<DeviceState>();
2453 auto& spec = ref.get<DeviceSpec const>();
2454 auto& streamContext = ref.get<StreamContext>();
2455 auto& dpContext = ref.get<DataProcessorContext>();
2456 auto shouldProcess = [](DataRelayer::RecordAction& action) -> bool {
2457 switch (action.op) {
2462 return true;
2463 break;
2464 default:
2465 return false;
2466 }
2467 };
2468 if (state.quitRequested == false) {
2469 {
2470 // Callbacks from services
2471 dpContext.preProcessingCallbacks(processContext);
2472 streamContext.preProcessingCallbacks(processContext);
2473 dpContext.preProcessingCallbacks(processContext);
2474 // Callbacks from users
2475 ref.get<CallbackService>().call<CallbackService::Id::PreProcessing>(o2::framework::ServiceRegistryRef{ref}, (int)action.op);
2476 }
2477 O2_SIGNPOST_ID_FROM_POINTER(pcid, device, &processContext);
2478 if (context.statefulProcess && shouldProcess(action)) {
2479 // This way, usercode can use the the same processing context to identify
2480 // its signposts and we can map user code to device iterations.
2481 O2_SIGNPOST_START(device, pcid, "device", "Stateful process");
2482 (context.statefulProcess)(processContext);
2483 O2_SIGNPOST_END(device, pcid, "device", "Stateful process");
2484 } else if (context.statelessProcess && shouldProcess(action)) {
2485 O2_SIGNPOST_START(device, pcid, "device", "Stateful process");
2486 (context.statelessProcess)(processContext);
2487 O2_SIGNPOST_END(device, pcid, "device", "Stateful process");
2488 } else if (context.statelessProcess || context.statefulProcess) {
2489 O2_SIGNPOST_EVENT_EMIT(device, pcid, "device", "Skipping processing because we are discarding.");
2490 } else {
2491 O2_SIGNPOST_EVENT_EMIT(device, pcid, "device", "No processing callback provided. Switching to %{public}s.", "Idle");
2493 }
2494 if (shouldProcess(action)) {
2495 auto& timingInfo = ref.get<TimingInfo>();
2496 if (timingInfo.globalRunNumberChanged) {
2497 context.lastRunNumberProcessed = timingInfo.runNumber;
2498 }
2499 }
2500
2501 // Notify the sink we just consumed some timeframe data
2502 if (context.isSink && action.op == CompletionPolicy::CompletionOp::Consume) {
2503 O2_SIGNPOST_EVENT_EMIT(device, pcid, "device", "Sending dpl-summary");
2504 auto& allocator = ref.get<DataAllocator>();
2505 allocator.make<int>(OutputRef{"dpl-summary", runtime_hash(spec.name.c_str())}, 1);
2506 }
2507
2508 // Extra callback which allows a service to add extra outputs.
2509 // This is needed e.g. to ensure that injected CCDB outputs are added
2510 // before an end of stream.
2511 {
2512 ref.get<CallbackService>().call<CallbackService::Id::FinaliseOutputs>(o2::framework::ServiceRegistryRef{ref}, (int)action.op);
2513 dpContext.finaliseOutputsCallbacks(processContext);
2514 streamContext.finaliseOutputsCallbacks(processContext);
2515 }
2516
2517 {
2518 ref.get<CallbackService>().call<CallbackService::Id::PostProcessing>(o2::framework::ServiceRegistryRef{ref}, (int)action.op);
2519 dpContext.postProcessingCallbacks(processContext);
2520 streamContext.postProcessingCallbacks(processContext);
2521 }
2522 }
2523 };
2524
2525 if ((state.tracingFlags & DeviceState::LoopReason::TRACE_USERCODE) != 0) {
2526 state.severityStack.push_back((int)fair::Logger::GetConsoleSeverity());
2527 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
2528 }
2529 if (noCatch) {
2530 try {
2531 runNoCatch(action);
2532 } catch (o2::framework::RuntimeErrorRef e) {
2533 (context.errorHandling)(e, record);
2534 }
2535 } else {
2536 try {
2537 runNoCatch(action);
2538 } catch (std::exception& ex) {
2542 auto e = runtime_error(ex.what());
2543 (context.errorHandling)(e, record);
2544 } catch (o2::framework::RuntimeErrorRef e) {
2545 (context.errorHandling)(e, record);
2546 }
2547 }
2548 if (state.severityStack.empty() == false) {
2549 fair::Logger::SetConsoleSeverity((fair::Severity)state.severityStack.back());
2550 state.severityStack.pop_back();
2551 }
2552
2553 postUpdateStats(action, record, tStart, tStartMilli);
2554 // We forward inputs only when we consume them. If we simply Process them,
2555 // we keep them for next message arriving.
2556 if (action.op == CompletionPolicy::CompletionOp::Consume) {
2557 cleanupRecord(record);
2558 context.postDispatchingCallbacks(processContext);
2559 ref.get<CallbackService>().call<CallbackService::Id::DataConsumed>(o2::framework::ServiceRegistryRef{ref});
2560 }
2561 if ((context.forwardPolicy == ForwardPolicy::AfterProcessing) && hasForwards && consumeSomething) {
2562 O2_SIGNPOST_EVENT_EMIT(device, aid, "device", "Late forwarding");
2563 auto& timesliceIndex = ref.get<TimesliceIndex>();
2564 forwardInputs(ref, action.slot, currentSetOfInputs, timesliceIndex.getOldestPossibleOutput(), false, action.op == CompletionPolicy::CompletionOp::Consume);
2565 }
2566 context.postForwardingCallbacks(processContext);
2567 if (action.op == CompletionPolicy::CompletionOp::Process) {
2568 cleanTimers(action.slot, record);
2569 }
2570 O2_SIGNPOST_END(device, aid, "device", "Done processing action on slot %lu for action %{public}s", action.slot.index, fmt::format("{}", action.op).c_str());
2571 }
2572 O2_SIGNPOST_END(device, sid, "device", "Start processing ready actions");
2573
2574 // We now broadcast the end of stream if it was requested
2575 if (state.streaming == StreamingState::EndOfStreaming) {
2576 LOGP(detail, "Broadcasting end of stream");
2577 for (auto& channel : spec.outputChannels) {
2579 }
2581 }
2582
2583 return true;
2584}
2585
2587{
2588 LOG(error) << msg;
2589 ServiceRegistryRef ref{mServiceRegistry};
2590 auto& stats = ref.get<DataProcessingStats>();
2592}
2593
2594std::unique_ptr<ConfigParamStore> DeviceConfigurationHelpers::getConfiguration(ServiceRegistryRef registry, const char* name, std::vector<ConfigParamSpec> const& options)
2595{
2596
2597 if (registry.active<ConfigurationInterface>()) {
2598 auto& cfg = registry.get<ConfigurationInterface>();
2599 try {
2600 cfg.getRecursive(name);
2601 std::vector<std::unique_ptr<ParamRetriever>> retrievers;
2602 retrievers.emplace_back(std::make_unique<ConfigurationOptionsRetriever>(&cfg, name));
2603 auto configStore = std::make_unique<ConfigParamStore>(options, std::move(retrievers));
2604 configStore->preload();
2605 configStore->activate();
2606 return configStore;
2607 } catch (...) {
2608 // No overrides...
2609 }
2610 }
2611 return {nullptr};
2612}
2613
2614} // namespace o2::framework
benchmark::State & state
struct uv_timer_s uv_timer_t
struct uv_signal_s uv_signal_t
struct uv_async_s uv_async_t
struct uv_poll_s uv_poll_t
struct uv_loop_s uv_loop_t
o2::monitoring::Metric Metric
uint64_t maxLatency
o2::configuration::ConfigurationInterface ConfigurationInterface
constexpr int DEFAULT_MAX_CHANNEL_AHEAD
uint64_t minLatency
std::ostringstream debug
int32_t i
std::enable_if_t< std::is_signed< T >::value, bool > hasData(const CalArray< T > &cal)
Definition Painter.cxx:600
uint16_t pid
Definition RawData.h:2
uint32_t res
Definition RawData.h:0
#define O2_SIGNPOST_EVENT_EMIT_ERROR(log, id, name, format,...)
Definition Signpost.h:554
#define O2_DECLARE_DYNAMIC_LOG(name)
Definition Signpost.h:490
#define O2_SIGNPOST_ID_FROM_POINTER(name, log, pointer)
Definition Signpost.h:506
#define O2_SIGNPOST_END(log, id, name, format,...)
Definition Signpost.h:609
#define O2_LOG_ENABLED(log)
Definition Signpost.h:111
#define O2_SIGNPOST_ID_GENERATE(name, log)
Definition Signpost.h:507
#define O2_SIGNPOST_EVENT_EMIT_WARN(log, id, name, format,...)
Definition Signpost.h:564
#define O2_SIGNPOST_EVENT_EMIT(log, id, name, format,...)
Definition Signpost.h:523
#define O2_SIGNPOST_START(log, id, name, format,...)
Definition Signpost.h:603
constexpr uint32_t runtime_hash(char const *str)
o2::monitoring::Monitoring Monitoring
StringRef key
@ DeviceStateChanged
Invoked the device undergoes a state change.
decltype(auto) make(const Output &spec, Args... args)
static void doRun(ServiceRegistryRef)
void fillContext(DataProcessorContext &context, DeviceContext &deviceContext)
DataProcessingDevice(RunningDeviceRef ref, ServiceRegistry &)
static void doPrepare(ServiceRegistryRef)
static bool tryDispatchComputation(ServiceRegistryRef ref, std::vector< DataRelayer::RecordAction > &completed)
static void handleData(ServiceRegistryRef, InputChannelInfo &)
uint32_t getFirstTFOrbitForSlot(TimesliceSlot slot)
Get the firstTForbit associate to a given slot.
void updateCacheStatus(TimesliceSlot slot, CacheEntryStatus oldStatus, CacheEntryStatus newStatus)
uint32_t getRunNumberForSlot(TimesliceSlot slot)
Get the runNumber associated to a given slot.
void prunePending(OnDropCallback)
Prune all the pending entries in the cache.
std::vector< std::vector< fair::mq::MessagePtr > > consumeAllInputsForTimeslice(TimesliceSlot id)
uint64_t getCreationTimeForSlot(TimesliceSlot slot)
Get the creation time associated to a given slot.
ActivityStats processDanglingInputs(std::vector< ExpirationHandler > const &, ServiceRegistryRef context, bool createNew)
uint32_t getFirstTFCounterForSlot(TimesliceSlot slot)
Get the firstTFCounter associate to a given slot.
A service API to communicate with the driver.
The input API of the Data Processing Layer This class holds the inputs which are valid for processing...
size_t size() const
Number of elements in the InputSpan.
Definition InputSpan.h:93
virtual fair::mq::Device * device()=0
bool active() const
Check if service of type T is currently active.
OldestOutputInfo getOldestPossibleOutput() const
GLint GLsizei count
Definition glcorearb.h:399
GLuint64EXT * result
Definition glcorearb.h:5662
GLuint buffer
Definition glcorearb.h:655
GLuint entry
Definition glcorearb.h:5735
GLuint index
Definition glcorearb.h:781
GLuint const GLchar * name
Definition glcorearb.h:781
GLboolean GLboolean GLboolean b
Definition glcorearb.h:1233
GLsizei const GLfloat * value
Definition glcorearb.h:819
GLint GLint GLsizei GLint GLenum GLenum type
Definition glcorearb.h:275
GLboolean * data
Definition glcorearb.h:298
GLuint GLsizei GLsizei * length
Definition glcorearb.h:790
GLuint GLsizei const GLchar * label
Definition glcorearb.h:2519
GLsizei GLenum const void * indices
Definition glcorearb.h:400
typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode)
GLuint GLsizei const GLchar * message
Definition glcorearb.h:2517
GLboolean GLboolean GLboolean GLboolean a
Definition glcorearb.h:1233
GLuint GLuint stream
Definition glcorearb.h:1806
GLint ref
Definition glcorearb.h:291
GLuint * states
Definition glcorearb.h:4932
Defining ITS Vertex explicitly as messageable.
Definition Cartesian.h:288
RuntimeErrorRef runtime_error(const char *)
ServiceKind
The kind of service we are asking for.
void on_idle_timer(uv_timer_t *handle)
@ DPL
The channel is a normal input channel.
void run_completion(uv_work_t *handle, int status)
void on_socket_polled(uv_poll_t *poller, int status, int events)
void run_callback(uv_work_t *handle)
auto forwardOnInsertion(ServiceRegistryRef &ref, std::span< fair::mq::MessagePtr > &messages) -> void
volatile int region_read_global_dummy_variable
void handleRegionCallbacks(ServiceRegistryRef registry, std::vector< fair::mq::RegionInfo > &infos)
Invoke the callbacks for the mPendingRegionInfos.
void on_out_of_band_polled(uv_poll_t *poller, int status, int events)
DeviceSpec const & getRunningDevice(RunningDeviceRef const &running, ServiceRegistryRef const &services)
@ EndOfStreaming
End of streaming requested, but not notified.
@ Streaming
Data is being processed.
@ Idle
End of streaming notified.
void on_communication_requested(uv_async_t *s)
@ Expired
A transition needs to be fullfilled ASAP.
@ NoTransition
No pending transitions.
@ Requested
A transition was notified to be requested.
RuntimeError & error_from_ref(RuntimeErrorRef)
void on_awake_main_thread(uv_async_t *handle)
@ Completed
The channel was signaled it will not receive any data.
@ Running
The channel is actively receiving data.
void on_signal_callback(uv_signal_t *handle, int signum)
@ Me
Only quit this data processor.
constexpr const char * channelName(int channel)
Definition Constants.h:318
a couple of static helper functions to create timestamp values for CCDB queries or override obsolete ...
static void run(AsyncQueue &queue, TimesliceId oldestPossibleTimeslice)
static void post(AsyncQueue &queue, AsyncTask const &task)
An actuatual task to be executed.
Definition AsyncQueue.h:32
static void demangled_backtrace_symbols(void **backtrace, unsigned int total, int fd)
static constexpr int INVALID
CompletionOp
Action to take with the InputRecord:
@ Retry
Like Wait but mark the cacheline as dirty.
int64_t timeslices
How many timeslices it can process without giving back control.
int64_t sharedMemory
How much shared memory it can allocate.
Statistics on the offers consumed, expired.
static bool hasOnlyGenerated(DeviceSpec const &spec)
check if spec is a source devide
static TransitionHandlingState updateStateTransition(ServiceRegistryRef const &ref, ProcessingPolicies const &policies)
starts the EoS timers and returns the new TransitionHandlingState in case as new state is requested
static void switchState(ServiceRegistryRef const &ref, StreamingState newState)
change the device StreamingState to newState
static void sendEndOfStream(ServiceRegistryRef const &ref, OutputChannelSpec const &channel)
static bool sendOldestPossibleTimeframe(ServiceRegistryRef const &ref, ForwardChannelInfo const &info, ForwardChannelState &state, size_t timeslice)
static void cleanForwardedMessages(std::span< fair::mq::MessagePtr > &currentSetOfInputs, bool consume)
static std::vector< fair::mq::Parts > routeForwardedMessageSet(FairMQDeviceProxy &proxy, std::vector< std::vector< fair::mq::MessagePtr > > &currentSetOfInputs, bool copy, bool consume)
Helper to route messages for forwarding.
static void routeForwardedMessages(FairMQDeviceProxy &proxy, std::span< fair::mq::MessagePtr > &currentSetOfInputs, std::vector< fair::mq::Parts > &forwardedParts, bool copy, bool consume)
Helper to route messages for forwarding.
Helper struct to hold statistics about the data processing happening.
@ CumulativeRate
Set the value to the specified value if it is positive.
@ Add
Update the rate of the metric given the amount since the last time.
std::function< void(o2::framework::RuntimeErrorRef e, InputRecord &record)> errorHandling
ForwardPolicy forwardPolicy
Wether or not the associated DataProcessor can forward things early.
AlgorithmSpec::InitErrorCallback initError
void preLoopCallbacks(ServiceRegistryRef)
Invoke callbacks before we enter the event loop.
void postStopCallbacks(ServiceRegistryRef)
Invoke callbacks on stop.
void preEOSCallbacks(EndOfStreamContext &)
Invoke callbacks to be executed before every EOS user callback invokation.
void preProcessingCallbacks(ProcessingContext &)
Invoke callbacks to be executed before every process method invokation.
void postEOSCallbacks(EndOfStreamContext &)
Invoke callbacks to be executed after every EOS user callback invokation.
void preStartCallbacks(ServiceRegistryRef)
Invoke callbacks to be executed in PreRun(), before the User Start callbacks.
AlgorithmSpec::ProcessCallback statefulProcess
const char * header
Definition DataRef.h:28
const InputSpec * spec
Definition DataRef.h:27
static std::vector< size_t > createDistinctRouteIndex(std::vector< InputRoute > const &)
@ Invalid
Ownership of the data has been taken.
@ Backpressured
The incoming data was not valid and has been dropped.
@ Dropped
The incoming data was not relayed, because we are backpressured.
static bool partialMatch(InputSpec const &spec, o2::header::DataOrigin const &origin)
static std::string describe(InputSpec const &spec)
static bool match(InputSpec const &spec, ConcreteDataMatcher const &target)
TimesliceIndex::OldestOutputInfo oldestTimeslice
static unsigned int pipelineLength(unsigned int minLength)
get max number of timeslices in the queue
static std::unique_ptr< ConfigParamStore > getConfiguration(ServiceRegistryRef registry, const char *name, std::vector< ConfigParamSpec > const &options)
ProcessingPolicies & processingPolicies
Running state information of a given device.
Definition DeviceState.h:34
std::atomic< int64_t > cleanupCount
Definition DeviceState.h:82
Forward channel information.
Definition ChannelInfo.h:88
fair::mq::Channel * channel
Definition ChannelInfo.h:51
enum Lifetime lifetime
Definition InputSpec.h:73
enum EarlyForwardPolicy earlyForward
Information about the running workflow.
static constexpr ServiceKind kind
static Salt streamSalt(short streamId, short dataProcessorId)
void lateBindStreamServices(DeviceState &state, fair::mq::ProgOptions &options, ServiceRegistry::Salt salt)
static Salt globalStreamSalt(short streamId)
void * get(ServiceTypeHash typeHash, Salt salt, ServiceKind kind, char const *name=nullptr) const
void finaliseOutputsCallbacks(ProcessingContext &)
Invoke callbacks to be executed after every process method invokation.
void preProcessingCallbacks(ProcessingContext &pcx)
Invoke callbacks to be executed before every process method invokation.
void postProcessingCallbacks(ProcessingContext &pcx)
Invoke callbacks to be executed after every process method invokation.
static int64_t getRealtimeSinceEpochStandalone()
bool keepAtEndOfStream
Wether this kind of data should be flushed during end of stream.
Definition TimingInfo.h:44
static bool timesliceIsTimer(size_t timeslice)
Definition TimingInfo.h:46
static TimesliceId getTimeslice(data_matcher::VariableContext const &variables)
void backpressure(InputChannelInfo const &)
locked_execution(ServiceRegistryRef &ref_)
the main header struct
Definition DataHeader.h:620
constexpr size_t min
constexpr size_t max
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"
vec clear()
const std::string str
uint64_t const void const *restrict const msg
Definition x9.h:153