32#if defined(__APPLE__) || defined(NDEBUG)
33#define O2_SIGNPOST_IMPLEMENTATION
57#include <fairmq/Parts.h>
58#include <fairmq/Socket.h>
59#include <fairmq/ProgOptions.h>
60#if __has_include(<fairmq/shmem/Message.h>)
61#include <fairmq/shmem/Message.h>
63#include <Configuration/ConfigurationInterface.h>
64#include <Configuration/ConfigurationFactory.h>
65#include <Monitoring/Monitoring.h>
67#include <TClonesArray.h>
69#include <fmt/ostream.h>
77#include <boost/property_tree/json_parser.hpp>
124 return std::all_of(spec.
inputs.cbegin(), spec.
inputs.cend(), [](
InputRoute const& route) ->
bool { return route.matcher.lifetime == Lifetime::Timer; });
129 return (spec.
inputChannels.size() == 1) && (spec.
inputs[0].matcher.lifetime == Lifetime::Timer || spec.
inputs[0].matcher.lifetime == Lifetime::Enumeration);
155 O2_SIGNPOST_START(device, dpid,
"state",
"Starting processing state %d", (
int)newState);
156 state.streaming = newState;
171 O2_SIGNPOST_EVENT_EMIT_INFO(calibration, cid,
"callback",
"Grace period for data processing expired. Switching to EndOfStreaming.");
174 O2_SIGNPOST_EVENT_EMIT_INFO(calibration, cid,
"callback",
"Grace period for data processing expired. Only calibrations from this point onwards.");
188 return devices[running.
index];
198 : mRunningDevice{running},
199 mConfigRegistry{nullptr},
200 mServiceRegistry{registry},
201 mProcessingPolicies{policies}
203 GetConfig()->Subscribe<std::string>(
"dpl", [®istry = mServiceRegistry](
const std::string&
key, std::string
value) {
204 if (
key ==
"cleanup") {
208 int64_t newCleanupCount = std::stoll(
value);
209 if (newCleanupCount <= cleanupCount) {
212 deviceState.cleanupCount.store(newCleanupCount);
213 for (
auto& info : deviceState.inputChannelInfos) {
214 fair::mq::Parts parts;
215 while (info.channel->Receive(parts, 0)) {
216 LOGP(
debug,
"Dropping {} parts", parts.Size());
217 if (parts.Size() == 0) {
225 std::function<
void(
const fair::mq::State)> stateWatcher = [
this, ®istry = mServiceRegistry](
const fair::mq::State
state) ->
void {
230 control.notifyDeviceState(fair::mq::GetStateName(
state));
233 if (deviceState.nextFairMQState.empty() ==
false) {
234 auto state = deviceState.nextFairMQState.back();
236 deviceState.nextFairMQState.pop_back();
241 this->SubscribeToStateChange(
"99-dpl", stateWatcher);
252 mAwakeHandle->data = &
state;
254 LOG(
error) <<
"Unable to initialise subscription";
258 SubscribeToNewTransition(
"dpl", [wakeHandle = mAwakeHandle](fair::mq::Transition t) {
259 int res = uv_async_send(wakeHandle);
261 LOG(
error) <<
"Unable to notify subscription";
263 LOG(
debug) <<
"State transition requested";
277 O2_SIGNPOST_START(device, sid,
"run_callback",
"Starting run callback on stream %d", task->id.index);
280 O2_SIGNPOST_END(device, sid,
"run_callback",
"Done processing data for stream %d", task->id.index);
293 using o2::monitoring::Metric;
294 using o2::monitoring::Monitoring;
295 using o2::monitoring::tags::Key;
296 using o2::monitoring::tags::Value;
300 stats.totalConsumedBytes += accumulatedConsumed.
sharedMemory;
303 dpStats.processCommandQueue();
311 dpStats.processCommandQueue();
314 for (
auto& consumer :
state.offerConsumers) {
315 quotaEvaluator.consume(task->id.index, consumer, reportConsumedOffer);
317 state.offerConsumers.clear();
318 quotaEvaluator.handleExpired(reportExpiredOffer);
319 quotaEvaluator.dispose(task->id.index);
320 task->running =
false;
348 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"Data pending on socket for channel %{public}s", context->name);
352 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"Socket connected for channel %{public}s", context->name);
354 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"Socket connected for read in context %{public}s", context->name);
355 uv_poll_start(poller, UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED, &
on_socket_polled);
358 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"Socket connected for write for channel %{public}s", context->name);
366 case UV_DISCONNECT: {
367 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"Socket disconnected in context %{public}s", context->name);
369 case UV_PRIORITIZED: {
370 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"Socket prioritized for context %{public}s", context->name);
382 LOGP(fatal,
"Error while polling {}: {}", context->name, status);
387 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"Data pending on socket for channel %{public}s", context->name);
389 assert(context->channelInfo);
390 context->channelInfo->readPolled =
true;
393 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"OOB socket connected for channel %{public}s", context->name);
395 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"OOB socket connected for read in context %{public}s", context->name);
398 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"OOB socket connected for write for channel %{public}s", context->name);
402 case UV_DISCONNECT: {
403 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"OOB socket disconnected in context %{public}s", context->name);
406 case UV_PRIORITIZED: {
407 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"OOB socket prioritized for context %{public}s", context->name);
428 context.statelessProcess = spec.algorithm.onProcess;
430 context.error = spec.algorithm.onError;
431 context.
initError = spec.algorithm.onInitError;
434 if (configStore ==
nullptr) {
435 std::vector<std::unique_ptr<ParamRetriever>> retrievers;
436 retrievers.emplace_back(std::make_unique<FairOptionsRetriever>(GetConfig()));
437 configStore = std::make_unique<ConfigParamStore>(spec.options, std::move(retrievers));
438 configStore->preload();
439 configStore->activate();
442 using boost::property_tree::ptree;
445 for (
auto&
entry : configStore->store()) {
446 std::stringstream ss;
448 if (
entry.second.empty() ==
false) {
449 boost::property_tree::json_parser::write_json(ss,
entry.second,
false);
453 str =
entry.second.get_value<std::string>();
455 std::string configString = fmt::format(
"[CONFIG] {}={} 1 {}",
entry.first,
str, configStore->provenance(
entry.first.c_str())).c_str();
459 mConfigRegistry = std::make_unique<ConfigParamRegistry>(std::move(configStore));
462 if (context.initError) {
463 context.initErrorHandling = [&errorCallback = context.initError,
476 errorCallback(errorContext);
479 context.initErrorHandling = [&serviceRegistry = mServiceRegistry](
RuntimeErrorRef e) {
494 context.expirationHandlers.clear();
495 context.init = spec.algorithm.onInit;
497 static bool noCatch = getenv(
"O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv(
"O2_NO_CATCHALL_EXCEPTIONS"),
"0");
498 InitContext initContext{*mConfigRegistry, mServiceRegistry};
502 context.statefulProcess = context.init(initContext);
504 if (context.initErrorHandling) {
505 (context.initErrorHandling)(e);
510 context.statefulProcess = context.init(initContext);
511 }
catch (std::exception& ex) {
516 (context.initErrorHandling)(e);
518 (context.initErrorHandling)(e);
523 state.inputChannelInfos.resize(spec.inputChannels.size());
527 int validChannelId = 0;
528 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
529 auto&
name = spec.inputChannels[ci].name;
530 if (
name.find(spec.channelPrefix +
"from_internal-dpl-clock") == 0) {
535 state.inputChannelInfos[ci].id = {validChannelId++};
540 if (spec.callbacksPolicy.policy !=
nullptr) {
541 InitContext initContext{*mConfigRegistry, mServiceRegistry};
546 auto* options = GetConfig();
547 for (
size_t si = 0; si < mStreams.size(); ++si) {
561 O2_SIGNPOST_END(device, sid,
"signal_state",
"No registry active. Ignoring signal.");
570 while (ri != quotaEvaluator.mOffers.size()) {
571 auto& offer = quotaEvaluator.mOffers[ri];
577 if (offer.valid && offer.sharedMemory != 0) {
578 O2_SIGNPOST_END(device, sid,
"signal_state",
"Memory already offered.");
584 for (
auto& offer : quotaEvaluator.mOffers) {
585 if (offer.valid ==
false) {
588 offer.sharedMemory = 1000000000;
595 O2_SIGNPOST_END(device, sid,
"signal_state",
"Done processing signals.");
598static auto toBeForwardedHeader = [](
void* header) ->
bool {
603 if (header ==
nullptr) {
606 auto sih = o2::header::get<SourceInfoHeader*>(header);
611 auto dih = o2::header::get<DomainInfoHeader*>(header);
616 auto dh = o2::header::get<DataHeader*>(header);
620 auto dph = o2::header::get<DataProcessingHeader*>(header);
627static auto toBeforwardedMessageSet = [](std::vector<ChannelIndex>& cachedForwardingChoices,
629 std::unique_ptr<fair::mq::Message>& header,
630 std::unique_ptr<fair::mq::Message>& payload,
633 if (header.get() ==
nullptr) {
640 if (payload.get() ==
nullptr && consume ==
true) {
644 header.reset(
nullptr);
648 auto fdph = o2::header::get<DataProcessingHeader*>(header->GetData());
649 if (fdph ==
nullptr) {
650 LOG(error) <<
"Data is missing DataProcessingHeader";
653 auto fdh = o2::header::get<DataHeader*>(header->GetData());
654 if (fdh ==
nullptr) {
655 LOG(error) <<
"Data is missing DataHeader";
662 if (fdh->splitPayloadIndex == 0 || fdh->splitPayloadParts <= 1 || total > 1) {
663 proxy.getMatchingForwardChannelIndexes(cachedForwardingChoices, *fdh, fdph->startTime);
665 return cachedForwardingChoices.empty() ==
false;
679 if (oldestTimeslice.timeslice.value <= decongestion.lastTimeslice) {
680 LOG(
debug) <<
"Not sending already sent oldest possible timeslice " << oldestTimeslice.timeslice.value;
683 for (
int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
684 auto& info = proxy.getForwardChannelInfo(
ChannelIndex{fi});
689 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputsCallback",
"Skipping channel %{public}s because it's not a DPL channel",
695 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputsCallback",
"Forwarding to channel %{public}s oldest possible timeslice %zu, prio 20",
696 info.name.c_str(), oldestTimeslice.timeslice.value);
709 std::vector<fair::mq::Parts> forwardedParts;
710 forwardedParts.resize(proxy.getNumForwards());
711 std::vector<ChannelIndex> cachedForwardingChoices{};
713 O2_SIGNPOST_START(forwarding, sid,
"forwardInputs",
"Starting forwarding for slot %zu with oldestTimeslice %zu %{public}s%{public}s%{public}s",
714 slot.index, oldestTimeslice.timeslice.value, copy ?
"with copy" :
"", copy && consume ?
" and " :
"", consume ?
"with consume" :
"");
716 for (
size_t ii = 0, ie = currentSetOfInputs.size(); ii < ie; ++ii) {
717 auto& messageSet = currentSetOfInputs[ii];
719 if (messageSet.size() == 0) {
722 if (!toBeForwardedHeader(messageSet.header(0)->GetData())) {
725 cachedForwardingChoices.clear();
727 for (
size_t pi = 0; pi < currentSetOfInputs[ii].size(); ++pi) {
728 auto& messageSet = currentSetOfInputs[ii];
729 auto& header = messageSet.header(pi);
730 auto& payload = messageSet.payload(pi);
731 auto total = messageSet.getNumberOfPayloads(pi);
733 if (!toBeforwardedMessageSet(cachedForwardingChoices, proxy, header, payload, total, consume)) {
739 if (cachedForwardingChoices.size() > 1) {
742 auto* dh = o2::header::get<DataHeader*>(header->GetData());
743 auto* dph = o2::header::get<DataProcessingHeader*>(header->GetData());
746 for (
auto& cachedForwardingChoice : cachedForwardingChoices) {
747 auto&& newHeader = header->GetTransport()->CreateMessage();
749 fmt::format(
"{}/{}/{}@timeslice:{} tfCounter:{}", dh->dataOrigin, dh->dataDescription, dh->subSpecification, dph->startTime, dh->tfCounter).c_str(), cachedForwardingChoice.value);
750 newHeader->Copy(*header);
751 forwardedParts[cachedForwardingChoice.value].AddPart(std::move(newHeader));
753 for (
size_t payloadIndex = 0; payloadIndex < messageSet.getNumberOfPayloads(pi); ++payloadIndex) {
754 auto&& newPayload = header->GetTransport()->CreateMessage();
755 newPayload->Copy(*messageSet.payload(pi, payloadIndex));
756 forwardedParts[cachedForwardingChoice.value].AddPart(std::move(newPayload));
761 fmt::format(
"{}/{}/{}@timeslice:{} tfCounter:{}", dh->dataOrigin, dh->dataDescription, dh->subSpecification, dph->startTime, dh->tfCounter).c_str(), cachedForwardingChoices.back().value);
762 forwardedParts[cachedForwardingChoices.back().value].AddPart(std::move(messageSet.header(pi)));
763 for (
size_t payloadIndex = 0; payloadIndex < messageSet.getNumberOfPayloads(pi); ++payloadIndex) {
764 forwardedParts[cachedForwardingChoices.back().value].AddPart(std::move(messageSet.payload(pi, payloadIndex)));
769 O2_SIGNPOST_EVENT_EMIT(forwarding, sid,
"forwardInputs",
"Forwarding %zu messages", forwardedParts.size());
770 for (
int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
771 if (forwardedParts[fi].
Size() == 0) {
775 auto& parts = forwardedParts[fi];
776 if (info.
policy ==
nullptr) {
787 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputs",
"Queuing forwarding oldestPossible %zu", oldestTimeslice.timeslice.value);
799 if (infos.empty() ==
false) {
800 std::vector<fair::mq::RegionInfo> toBeNotified;
801 toBeNotified.swap(infos);
802 static bool dummyRead = getenv(
"DPL_DEBUG_MAP_ALL_SHM_REGIONS") && atoi(getenv(
"DPL_DEBUG_MAP_ALL_SHM_REGIONS"));
803 for (
auto const& info : toBeNotified) {
823void DataProcessingDevice::initPollers()
831 if ((context.statefulProcess !=
nullptr) || (context.statelessProcess !=
nullptr)) {
832 for (
auto& [channelName, channel] : GetChannels()) {
834 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
835 auto& channelSpec = spec.inputChannels[ci];
836 channelInfo = &
state.inputChannelInfos[ci];
837 if (channelSpec.name != channelName) {
840 channelInfo->
channel = &this->GetChannel(channelName, 0);
843 if ((
channelName.rfind(
"from_internal-dpl", 0) == 0) &&
844 (
channelName.rfind(
"from_internal-dpl-aod", 0) != 0) &&
845 (
channelName.rfind(
"from_internal-dpl-ccdb-backend", 0) != 0) &&
846 (
channelName.rfind(
"from_internal-dpl-injected", 0)) != 0) {
847 LOGP(detail,
"{} is an internal channel. Skipping as no input will come from there.", channelName);
851 if (
channelName.rfind(
"from_" + spec.name +
"_", 0) == 0) {
852 LOGP(detail,
"{} is to send data. Not polling.", channelName);
857 LOGP(detail,
"{} is not a DPL socket. Not polling.", channelName);
863 size_t zmq_fd_len =
sizeof(zmq_fd);
866 channel[0].GetSocket().GetOption(
"fd", &zmq_fd, &zmq_fd_len);
871 LOGP(detail,
"Polling socket for {}", channelName);
874 pCtx->loop =
state.loop;
876 pCtx->state = &
state;
878 assert(channelInfo !=
nullptr);
879 pCtx->channelInfo = channelInfo;
880 pCtx->socket = &channel[0].GetSocket();
883 uv_poll_init(
state.loop, poller, zmq_fd);
885 LOGP(detail,
"{} is an out of band channel.", channelName);
886 state.activeOutOfBandPollers.push_back(poller);
889 state.activeInputPollers.push_back(poller);
895 if (
state.activeInputPollers.empty() &&
896 state.activeOutOfBandPollers.empty() &&
897 state.activeTimers.empty() &&
898 state.activeSignals.empty()) {
902 if (
state.inputChannelInfos.empty()) {
903 LOGP(detail,
"No input channels. Setting exit transition timeout to 0.");
904 deviceContext.exitTransitionTimeout = 0;
906 for (
auto& [channelName, channel] : GetChannels()) {
907 if (
channelName.rfind(spec.channelPrefix +
"from_internal-dpl", 0) == 0) {
908 LOGP(detail,
"{} is an internal channel. Not polling.", channelName);
911 if (
channelName.rfind(spec.channelPrefix +
"from_" + spec.name +
"_", 0) == 0) {
912 LOGP(detail,
"{} is an out of band channel. Not polling for output.", channelName);
917 size_t zmq_fd_len =
sizeof(zmq_fd);
920 channel[0].GetSocket().GetOption(
"fd", &zmq_fd, &zmq_fd_len);
922 LOGP(
error,
"Cannot get file descriptor for channel {}", channelName);
925 LOG(detail) <<
"Polling socket for " << channel[0].GetName();
929 pCtx->loop =
state.loop;
931 pCtx->state = &
state;
935 uv_poll_init(
state.loop, poller, zmq_fd);
936 state.activeOutputPollers.push_back(poller);
940 LOGP(detail,
"This is a fake device so we exit after the first iteration.");
941 deviceContext.exitTransitionTimeout = 0;
947 uv_timer_init(
state.loop, timer);
948 timer->data = &
state;
949 uv_update_time(
state.loop);
951 state.activeTimers.push_back(timer);
955void DataProcessingDevice::startPollers()
961 for (
auto* poller :
state.activeInputPollers) {
963 O2_SIGNPOST_START(device, sid,
"socket_state",
"Input socket waiting for connection.");
967 for (
auto& poller :
state.activeOutOfBandPollers) {
971 for (
auto* poller :
state.activeOutputPollers) {
973 O2_SIGNPOST_START(device, sid,
"socket_state",
"Output socket waiting for connection.");
980 uv_timer_init(
state.loop, deviceContext.gracePeriodTimer);
983 deviceContext.dataProcessingGracePeriodTimer->data =
new ServiceRegistryRef(mServiceRegistry);
984 uv_timer_init(
state.loop, deviceContext.dataProcessingGracePeriodTimer);
987void DataProcessingDevice::stopPollers()
992 LOGP(detail,
"Stopping {} input pollers",
state.activeInputPollers.size());
993 for (
auto* poller :
state.activeInputPollers) {
996 uv_poll_stop(poller);
999 LOGP(detail,
"Stopping {} out of band pollers",
state.activeOutOfBandPollers.size());
1000 for (
auto* poller :
state.activeOutOfBandPollers) {
1001 uv_poll_stop(poller);
1004 LOGP(detail,
"Stopping {} output pollers",
state.activeOutOfBandPollers.size());
1005 for (
auto* poller :
state.activeOutputPollers) {
1007 O2_SIGNPOST_END(device, sid,
"socket_state",
"Output socket closed.");
1008 uv_poll_stop(poller);
1012 uv_timer_stop(deviceContext.gracePeriodTimer);
1014 free(deviceContext.gracePeriodTimer);
1015 deviceContext.gracePeriodTimer =
nullptr;
1017 uv_timer_stop(deviceContext.dataProcessingGracePeriodTimer);
1019 free(deviceContext.dataProcessingGracePeriodTimer);
1020 deviceContext.dataProcessingGracePeriodTimer =
nullptr;
1035 for (
auto&
di : distinct) {
1036 auto& route = spec.inputs[
di];
1037 if (route.configurator.has_value() ==
false) {
1042 .
name = route.configurator->name,
1044 .lifetime = route.matcher.lifetime,
1045 .creator = route.configurator->creatorConfigurator(
state, mServiceRegistry, *mConfigRegistry),
1046 .checker = route.configurator->danglingConfigurator(
state, *mConfigRegistry),
1047 .handler = route.configurator->expirationConfigurator(
state, *mConfigRegistry)};
1048 context.expirationHandlers.emplace_back(std::move(handler));
1051 if (
state.awakeMainThread ==
nullptr) {
1057 deviceContext.expectedRegionCallbacks = std::stoi(fConfig->GetValue<std::string>(
"expected-region-callbacks"));
1058 deviceContext.exitTransitionTimeout = std::stoi(fConfig->GetValue<std::string>(
"exit-transition-timeout"));
1059 deviceContext.dataProcessingTimeout = std::stoi(fConfig->GetValue<std::string>(
"data-processing-timeout"));
1061 for (
auto& channel : GetChannels()) {
1062 channel.second.at(0).Transport()->SubscribeToRegionEvents([&context = deviceContext,
1063 ®istry = mServiceRegistry,
1064 &pendingRegionInfos = mPendingRegionInfos,
1065 ®ionInfoMutex = mRegionInfoMutex](fair::mq::RegionInfo info) {
1066 std::lock_guard<std::mutex> lock(regionInfoMutex);
1067 LOG(detail) <<
">>> Region info event" << info.event;
1068 LOG(detail) <<
"id: " << info.id;
1069 LOG(detail) <<
"ptr: " << info.ptr;
1070 LOG(detail) <<
"size: " << info.size;
1071 LOG(detail) <<
"flags: " << info.flags;
1074 pendingRegionInfos.push_back(info);
1087 if (deviceContext.sigusr1Handle ==
nullptr) {
1089 deviceContext.sigusr1Handle->data = &mServiceRegistry;
1090 uv_signal_init(
state.loop, deviceContext.sigusr1Handle);
1094 for (
auto& handle :
state.activeSignals) {
1095 handle->data = &
state;
1098 deviceContext.sigusr1Handle->data = &mServiceRegistry;
1101 DataProcessingDevice::initPollers();
1109 LOG(
error) <<
"DataProcessor " <<
state.lastActiveDataProcessor.load()->spec->name <<
" was unexpectedly active";
1121 O2_SIGNPOST_END(device, cid,
"InitTask",
"Exiting InitTask callback waiting for the remaining region callbacks.");
1123 auto hasPendingEvents = [&mutex = mRegionInfoMutex, &pendingRegionInfos = mPendingRegionInfos](
DeviceContext& deviceContext) {
1124 std::lock_guard<std::mutex> lock(mutex);
1125 return (pendingRegionInfos.empty() ==
false) || deviceContext.expectedRegionCallbacks > 0;
1132 while (hasPendingEvents(deviceContext)) {
1134 uv_run(
state.loop, UV_RUN_ONCE);
1138 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1142 O2_SIGNPOST_END(device, cid,
"InitTask",
"Done waiting for registration events.");
1149 bool enableRateLimiting = std::stoi(fConfig->GetValue<std::string>(
"timeframes-rate-limit"));
1158 if (enableRateLimiting ==
false && spec.name.find(
"internal-dpl-injected-dummy-sink") != std::string::npos) {
1161 if (enableRateLimiting) {
1162 for (
auto& spec : spec.outputs) {
1163 if (spec.matcher.binding.value ==
"dpl-summary") {
1170 context.
registry = &mServiceRegistry;
1173 if (context.
error !=
nullptr) {
1187 errorCallback(errorContext);
1201 switch (errorPolicy) {
1212 auto decideEarlyForward = [&context, &spec,
this]() ->
bool {
1216 bool onlyConditions =
true;
1217 bool overriddenEarlyForward =
false;
1218 for (
auto& forwarded : spec.forwards) {
1219 if (forwarded.matcher.lifetime != Lifetime::Condition) {
1220 onlyConditions =
false;
1222#if !__has_include(<fairmq/shmem/Message.h>)
1225 overriddenEarlyForward =
true;
1232 overriddenEarlyForward =
true;
1236 if (forwarded.matcher.lifetime == Lifetime::Optional) {
1238 overriddenEarlyForward =
true;
1243 if (!overriddenEarlyForward && onlyConditions) {
1245 LOG(detail) <<
"Enabling early forwarding because only conditions to be forwarded";
1247 return canForwardEarly;
1259 state.quitRequested =
false;
1262 for (
auto& info :
state.inputChannelInfos) {
1274 for (
size_t i = 0;
i < mStreams.size(); ++
i) {
1277 context.preStartStreamCallbacks(streamRef);
1279 }
catch (std::exception& e) {
1280 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"PreRun",
"Exception of type std::exception caught in PreRun: %{public}s. Rethrowing.", e.what());
1281 O2_SIGNPOST_END(device, cid,
"PreRun",
"Exiting PreRun due to exception thrown.");
1285 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"PreRun",
"Exception of type o2::framework::RuntimeErrorRef caught in PreRun: %{public}s. Rethrowing.", err.what);
1286 O2_SIGNPOST_END(device, cid,
"PreRun",
"Exiting PreRun due to exception thrown.");
1289 O2_SIGNPOST_END(device, cid,
"PreRun",
"Unknown exception being thrown. Rethrowing.");
1297 using o2::monitoring::Metric;
1298 using o2::monitoring::Monitoring;
1299 using o2::monitoring::tags::Key;
1300 using o2::monitoring::tags::Value;
1303 monitoring.send(
Metric{(uint64_t)1,
"device_state"}.addTag(Key::Subsystem, Value::DPL));
1311 using o2::monitoring::Metric;
1312 using o2::monitoring::Monitoring;
1313 using o2::monitoring::tags::Key;
1314 using o2::monitoring::tags::Value;
1317 monitoring.send(
Metric{(uint64_t)0,
"device_state"}.addTag(Key::Subsystem, Value::DPL));
1336 bool firstLoop =
true;
1338 O2_SIGNPOST_START(device, lid,
"device_state",
"First iteration of the device loop");
1340 bool dplEnableMultithreding = getenv(
"DPL_THREADPOOL_SIZE") !=
nullptr;
1341 if (dplEnableMultithreding) {
1342 setenv(
"UV_THREADPOOL_SIZE",
"1", 1);
1346 if (
state.nextFairMQState.empty() ==
false) {
1347 (
void)this->ChangeState(
state.nextFairMQState.back());
1348 state.nextFairMQState.pop_back();
1353 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1366 state.lastActiveDataProcessor.compare_exchange_strong(lastActive,
nullptr);
1368 auto shouldNotWait = (lastActive !=
nullptr &&
1372 shouldNotWait =
true;
1375 if (lastActive !=
nullptr) {
1378 if (NewStatePending()) {
1380 shouldNotWait =
true;
1393 if (deviceContext.dataProcessingTimeout > 0 && deviceContext.dataProcessingTimeout < deviceContext.exitTransitionTimeout) {
1394 uv_update_time(
state.loop);
1395 O2_SIGNPOST_EVENT_EMIT(calibration, lid,
"timer_setup",
"Starting %d s timer for dataProcessingTimeout.", deviceContext.dataProcessingTimeout);
1396 uv_timer_start(deviceContext.dataProcessingGracePeriodTimer,
on_data_processing_expired, deviceContext.dataProcessingTimeout * 1000, 0);
1401 uv_update_time(
state.loop);
1402 O2_SIGNPOST_EVENT_EMIT(calibration, lid,
"timer_setup",
"Starting %d s timer for exitTransitionTimeout.",
1403 deviceContext.exitTransitionTimeout);
1406 int timeout = onlyGenerated ? deviceContext.dataProcessingTimeout : deviceContext.exitTransitionTimeout;
1411 "New state requested. Waiting for %d seconds before %{public}s",
1413 onlyGenerated ?
"dropping remaining input and switching to READY state." :
"switching to READY state.");
1418 O2_SIGNPOST_EVENT_EMIT_INFO(device, lid,
"run_loop",
"New state requested. No timeout set, quitting immediately as per --completion-policy");
1420 O2_SIGNPOST_EVENT_EMIT_INFO(device, lid,
"run_loop",
"New state requested. No timeout set, switching to READY state immediately");
1422 O2_SIGNPOST_EVENT_EMIT_INFO(device, lid,
"run_loop",
"New state pending and we are already idle, quitting immediately as per --completion-policy");
1424 O2_SIGNPOST_EVENT_EMIT_INFO(device, lid,
"run_loop",
"New state pending and we are already idle, switching to READY immediately.");
1430 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"State transition requested and we are now in Idle. We can consider it to be completed.");
1433 if (
state.severityStack.empty() ==
false) {
1434 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
1435 state.severityStack.pop_back();
1441 state.firedTimers.clear();
1443 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
1444 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
1451 O2_SIGNPOST_START(device, lid,
"run_loop",
"Dropping message from slot %" PRIu64
". Forwarding as needed.", (uint64_t)slot.index);
1459 forwardInputs(registry, slot, dropped, oldestOutputInfo,
false,
true);
1464 auto oldestPossibleTimeslice = relayer.getOldestPossibleOutput();
1466 if (shouldNotWait ==
false) {
1470 O2_SIGNPOST_END(device, lid,
"run_loop",
"Run loop completed. %{}s", shouldNotWait ?
"Will immediately schedule a new one" :
"Waiting for next event.");
1471 uv_run(
state.loop, shouldNotWait ? UV_RUN_NOWAIT : UV_RUN_ONCE);
1473 if ((
state.loopReason &
state.tracingFlags) != 0) {
1474 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
1475 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
1476 }
else if (
state.severityStack.empty() ==
false) {
1477 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
1478 state.severityStack.pop_back();
1483 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"Out of band activity detected. Rescanning everything.");
1487 if (!
state.pendingOffers.empty()) {
1488 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"Pending %" PRIu64
" offers. updating the ComputingQuotaEvaluator.", (uint64_t)
state.pendingOffers.size());
1500 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1504 assert(mStreams.size() == mHandles.size());
1507 for (
size_t ti = 0; ti < mStreams.size(); ti++) {
1508 auto& taskInfo = mStreams[ti];
1509 if (taskInfo.running) {
1513 streamRef.index = ti;
1515 using o2::monitoring::Metric;
1516 using o2::monitoring::Monitoring;
1517 using o2::monitoring::tags::Key;
1518 using o2::monitoring::tags::Value;
1521 if (streamRef.index != -1) {
1524 uv_work_t& handle = mHandles[streamRef.index];
1526 handle.data = &mStreams[streamRef.index];
1533 dpStats.processCommandQueue();
1546 stream.registry = &mServiceRegistry;
1547 if (dplEnableMultithreding) [[unlikely]] {
1561 O2_SIGNPOST_END(device, lid,
"run_loop",
"Run loop completed. Transition handling state %d.",
state.transitionHandling);
1564 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
1565 auto& info =
state.inputChannelInfos[ci];
1566 info.parts.fParts.clear();
1577 O2_SIGNPOST_START(device, dpid,
"do_prepare",
"Starting DataProcessorContext::doPrepare.");
1595 context.allDone = std::any_of(
state.inputChannelInfos.begin(),
state.inputChannelInfos.end(), [cid](
const auto& info) {
1597 O2_SIGNPOST_EVENT_EMIT(device, cid,
"do_prepare",
"Input channel %{public}s%{public}s has %zu parts left and is in state %d.",
1598 info.channel->GetName().c_str(), (info.id.value == ChannelIndex::INVALID ?
" (non DPL)" :
""), info.parts.fParts.size(), (int)info.state);
1600 O2_SIGNPOST_EVENT_EMIT(device, cid,
"do_prepare",
"External channel %d is in state %d.", info.id.value, (int)info.state);
1605 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"do_prepare",
"Processing %zu input channels.", spec.inputChannels.size());
1608 static std::vector<int> pollOrder;
1609 pollOrder.resize(
state.inputChannelInfos.size());
1610 std::iota(pollOrder.begin(), pollOrder.end(), 0);
1611 std::sort(pollOrder.begin(), pollOrder.end(), [&infos =
state.inputChannelInfos](
int a,
int b) {
1612 return infos[a].oldestForChannel.value < infos[b].oldestForChannel.value;
1616 if (pollOrder.empty()) {
1617 O2_SIGNPOST_END(device, dpid,
"do_prepare",
"Nothing to poll. Waiting for next iteration.");
1620 auto currentOldest =
state.inputChannelInfos[pollOrder.front()].oldestForChannel;
1621 auto currentNewest =
state.inputChannelInfos[pollOrder.back()].oldestForChannel;
1622 auto delta = currentNewest.value - currentOldest.value;
1623 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"do_prepare",
"Oldest possible timeframe range %" PRIu64
" => %" PRIu64
" delta %" PRIu64,
1624 (int64_t)currentOldest.value, (int64_t)currentNewest.value, (int64_t)delta);
1625 auto& infos =
state.inputChannelInfos;
1627 if (context.balancingInputs) {
1629 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));
1630 auto newEnd = std::remove_if(pollOrder.begin(), pollOrder.end(), [&infos, limitNew = currentOldest.value + ahead](
int a) ->
bool {
1631 return infos[a].oldestForChannel.value > limitNew;
1633 for (
auto it = pollOrder.begin(); it < pollOrder.end(); it++) {
1634 const auto& channelInfo =
state.inputChannelInfos[*it];
1640 bool shouldBeRunning = it < newEnd;
1641 if (running != shouldBeRunning) {
1642 uv_poll_start(poller, shouldBeRunning ? UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED : 0, &
on_socket_polled);
1648 pollOrder.erase(newEnd, pollOrder.end());
1650 O2_SIGNPOST_END(device, dpid,
"do_prepare",
"%zu channels pass the channel inbalance balance check.", pollOrder.size());
1652 for (
auto sci : pollOrder) {
1653 auto& info =
state.inputChannelInfos[sci];
1654 auto& channelSpec = spec.inputChannels[sci];
1656 O2_SIGNPOST_START(device, cid,
"channels",
"Processing channel %s", channelSpec.name.c_str());
1659 context.allDone =
false;
1664 if (info.parts.Size()) {
1667 O2_SIGNPOST_END(device, cid,
"channels",
"Flushing channel %s which is in state %d and has %zu parts still pending.",
1668 channelSpec.name.c_str(), (
int)info.state, info.parts.Size());
1671 if (info.
channel ==
nullptr) {
1672 O2_SIGNPOST_END(device, cid,
"channels",
"Channel %s which is in state %d is nullptr and has %zu parts still pending.",
1673 channelSpec.name.c_str(), (
int)info.state, info.parts.Size());
1678 O2_SIGNPOST_END(device, cid,
"channels",
"Channel %s which is in state %d is not a DPL channel and has %zu parts still pending.",
1679 channelSpec.name.c_str(), (
int)info.state, info.parts.Size());
1682 auto& socket = info.
channel->GetSocket();
1687 if (info.hasPendingEvents == 0) {
1688 socket.Events(&info.hasPendingEvents);
1690 if ((info.hasPendingEvents & 1) == 0 && (info.parts.Size() == 0)) {
1691 O2_SIGNPOST_END(device, cid,
"channels",
"No pending events and no remaining parts to process for channel %{public}s", channelSpec.name.c_str());
1697 info.readPolled =
false;
1706 bool newMessages =
false;
1708 O2_SIGNPOST_EVENT_EMIT(device, cid,
"channels",
"Receiving loop called for channel %{public}s (%d) with oldest possible timeslice %zu",
1709 channelSpec.name.c_str(), info.id.value, info.oldestForChannel.value);
1710 if (info.parts.Size() < 64) {
1711 fair::mq::Parts parts;
1712 info.
channel->Receive(parts, 0);
1714 O2_SIGNPOST_EVENT_EMIT(device, cid,
"channels",
"Received %zu parts from channel %{public}s (%d).", parts.Size(), channelSpec.name.c_str(), info.id.value);
1716 for (
auto&& part : parts) {
1717 info.parts.fParts.emplace_back(std::move(part));
1719 newMessages |=
true;
1722 if (info.parts.Size() >= 0) {
1734 socket.Events(&info.hasPendingEvents);
1735 if (info.hasPendingEvents) {
1736 info.readPolled =
false;
1739 state.lastActiveDataProcessor.store(&context);
1742 O2_SIGNPOST_END(device, cid,
"channels",
"Done processing channel %{public}s (%d).",
1743 channelSpec.name.c_str(), info.id.value);
1758 context.completed.clear();
1759 context.completed.reserve(16);
1761 state.lastActiveDataProcessor.store(&context);
1765 context.preDanglingCallbacks(danglingContext);
1766 if (
state.lastActiveDataProcessor.load() ==
nullptr) {
1769 auto activity =
ref.get<
DataRelayer>().processDanglingInputs(context.expirationHandlers, *context.registry,
true);
1770 if (activity.expiredSlots > 0) {
1771 state.lastActiveDataProcessor = &context;
1774 context.completed.clear();
1776 state.lastActiveDataProcessor = &context;
1779 context.postDanglingCallbacks(danglingContext);
1787 state.lastActiveDataProcessor = &context;
1810 timingInfo.timeslice = relayer.getOldestPossibleOutput().timeslice.value;
1811 timingInfo.tfCounter = -1;
1812 timingInfo.firstTForbit = -1;
1814 timingInfo.creation = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count();
1815 O2_SIGNPOST_EVENT_EMIT(calibration, dpid,
"calibration",
"TimingInfo.keepAtEndOfStream %d", timingInfo.keepAtEndOfStream);
1819 context.preEOSCallbacks(eosContext);
1823 streamContext.postEOSCallbacks(eosContext);
1824 context.postEOSCallbacks(eosContext);
1826 for (
auto& channel : spec.outputChannels) {
1827 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"state",
"Sending end of stream to %{public}s.", channel.name.c_str());
1834 if (shouldProcess) {
1835 state.lastActiveDataProcessor = &context;
1839 for (
auto& poller :
state.activeOutputPollers) {
1840 uv_poll_stop(poller);
1848 for (
auto& poller :
state.activeOutputPollers) {
1849 uv_poll_stop(poller);
1865 if (deviceContext.sigusr1Handle) {
1871 handle->data =
nullptr;
1900 auto getInputTypes = [&info, &context]() -> std::optional<std::vector<InputInfo>> {
1905 auto& parts = info.
parts;
1908 std::vector<InputInfo> results;
1910 results.reserve(parts.Size() / 2);
1911 size_t nTotalPayloads = 0;
1915 if (
type != InputType::Invalid &&
length > 1) {
1916 nTotalPayloads +=
length - 1;
1920 for (
size_t pi = 0; pi < parts.Size(); pi += 2) {
1921 auto* headerData = parts.At(pi)->GetData();
1922 auto sih = o2::header::get<SourceInfoHeader*>(headerData);
1924 O2_SIGNPOST_EVENT_EMIT(device, cid,
"handle_data",
"Got SourceInfoHeader with state %d", (
int)sih->state);
1925 info.
state = sih->state;
1926 insertInputInfo(pi, 2, InputType::SourceInfo, info.
id);
1927 state.lastActiveDataProcessor = &context;
1930 auto dih = o2::header::get<DomainInfoHeader*>(headerData);
1932 O2_SIGNPOST_EVENT_EMIT(device, cid,
"handle_data",
"Got DomainInfoHeader with oldestPossibleTimeslice %d", (
int)dih->oldestPossibleTimeslice);
1933 insertInputInfo(pi, 2, InputType::DomainInfo, info.
id);
1934 state.lastActiveDataProcessor = &context;
1937 auto dh = o2::header::get<DataHeader*>(headerData);
1939 insertInputInfo(pi, 0, InputType::Invalid, info.
id);
1943 if (dh->payloadSize > parts.At(pi + 1)->GetSize()) {
1944 insertInputInfo(pi, 0, InputType::Invalid, info.
id);
1948 auto dph = o2::header::get<DataProcessingHeader*>(headerData);
1953 O2_SIGNPOST_START(parts,
pid,
"parts",
"Processing DataHeader %{public}-4s/%{public}-16s/%d with splitPayloadParts %d and splitPayloadIndex %d",
1954 dh->dataOrigin.str, dh->dataDescription.str, dh->subSpecification, dh->splitPayloadParts, dh->splitPayloadIndex);
1956 insertInputInfo(pi, 2, InputType::Invalid, info.
id);
1960 if (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) {
1963 insertInputInfo(pi, dh->splitPayloadParts + 1, InputType::Data, info.
id);
1964 pi += dh->splitPayloadParts - 1;
1970 size_t finalSplitPayloadIndex = pi + (dh->splitPayloadParts > 0 ? dh->splitPayloadParts : 1) * 2;
1971 if (finalSplitPayloadIndex > parts.Size()) {
1973 insertInputInfo(pi, 0, InputType::Invalid, info.
id);
1976 insertInputInfo(pi, 2, InputType::Data, info.
id);
1977 for (; pi + 2 < finalSplitPayloadIndex; pi += 2) {
1978 insertInputInfo(pi + 2, 2, InputType::Data, info.
id);
1982 if (results.size() + nTotalPayloads != parts.Size()) {
1983 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"handle_data",
"inconsistent number of inputs extracted. %zu vs parts (%zu)", results.size() + nTotalPayloads, parts.Size());
1984 return std::nullopt;
1989 auto reportError = [
ref](
const char*
message) {
1994 auto handleValidMessages = [&info,
ref, &reportError](std::vector<InputInfo>
const& inputInfos) {
1998 auto& parts = info.
parts;
2001 bool hasBackpressure =
false;
2002 size_t minBackpressureTimeslice = -1;
2004 size_t oldestPossibleTimeslice = -1;
2005 static std::vector<int> ordering;
2007 ordering.resize(inputInfos.size());
2008 std::iota(ordering.begin(), ordering.end(), 0);
2010 std::stable_sort(ordering.begin(), ordering.end(), [&inputInfos](
int const&
a,
int const&
b) {
2011 auto const& ai = inputInfos[a];
2012 auto const& bi = inputInfos[b];
2013 if (ai.type != bi.type) {
2014 return ai.type < bi.type;
2016 return ai.position < bi.position;
2018 for (
size_t ii = 0; ii < inputInfos.size(); ++ii) {
2019 auto const& input = inputInfos[ordering[ii]];
2020 switch (input.type) {
2021 case InputType::Data: {
2023 auto headerIndex = input.position;
2025 auto nPayloadsPerHeader = 0;
2026 if (input.size > 2) {
2028 nMessages = input.size;
2029 nPayloadsPerHeader = nMessages - 1;
2032 auto dh = o2::header::get<DataHeader*>(parts.At(headerIndex)->GetData());
2033 nMessages = dh->splitPayloadParts > 0 ? dh->splitPayloadParts * 2 : 2;
2034 nPayloadsPerHeader = 1;
2035 ii += (nMessages / 2) - 1;
2039 O2_SIGNPOST_EVENT_EMIT(async_queue, cid,
"onDrop",
"Dropping message from slot %zu. Forwarding as needed. Timeslice %zu",
2040 slot.
index, oldestOutputInfo.timeslice.value);
2047 forwardInputs(
ref, slot, dropped, oldestOutputInfo,
false,
true);
2049 auto relayed = relayer.relay(parts.At(headerIndex)->GetData(),
2050 &parts.At(headerIndex),
2055 switch (relayed.type) {
2058 LOGP(alarm,
"Backpressure on channel {}. Waiting.", info.
channel->GetName());
2059 auto& monitoring =
ref.get<o2::monitoring::Monitoring>();
2060 monitoring.send(o2::monitoring::Metric{1, fmt::format(
"backpressure_{}", info.
channel->GetName())});
2064 policy.backpressure(info);
2065 hasBackpressure =
true;
2066 minBackpressureTimeslice = std::min<size_t>(minBackpressureTimeslice, relayed.timeslice.value);
2072 LOGP(info,
"Back to normal on channel {}.", info.
channel->GetName());
2073 auto& monitoring =
ref.get<o2::monitoring::Monitoring>();
2074 monitoring.send(o2::monitoring::Metric{0, fmt::format(
"backpressure_{}", info.
channel->GetName())});
2081 case InputType::SourceInfo: {
2082 LOGP(detail,
"Received SourceInfo");
2084 state.lastActiveDataProcessor = &context;
2085 auto headerIndex = input.position;
2086 auto payloadIndex = input.position + 1;
2087 assert(payloadIndex < parts.Size());
2090 parts.At(headerIndex).reset(
nullptr);
2091 parts.At(payloadIndex).reset(
nullptr);
2098 case InputType::DomainInfo: {
2102 state.lastActiveDataProcessor = &context;
2103 auto headerIndex = input.position;
2104 auto payloadIndex = input.position + 1;
2105 assert(payloadIndex < parts.Size());
2109 auto dih = o2::header::get<DomainInfoHeader*>(parts.At(headerIndex)->GetData());
2110 if (hasBackpressure && dih->oldestPossibleTimeslice >= minBackpressureTimeslice) {
2113 oldestPossibleTimeslice = std::min(oldestPossibleTimeslice, dih->oldestPossibleTimeslice);
2114 LOGP(
debug,
"Got DomainInfoHeader, new oldestPossibleTimeslice {} on channel {}", oldestPossibleTimeslice, info.
id.
value);
2115 parts.At(headerIndex).reset(
nullptr);
2116 parts.At(payloadIndex).reset(
nullptr);
2118 case InputType::Invalid: {
2119 reportError(
"Invalid part found.");
2125 if (oldestPossibleTimeslice != (
size_t)-1) {
2128 context.domainInfoUpdatedCallback(*context.registry, oldestPossibleTimeslice, info.
id);
2130 state.lastActiveDataProcessor = &context;
2132 auto it = std::remove_if(parts.fParts.begin(), parts.fParts.end(), [](
auto&
msg) ->
bool { return msg.get() == nullptr; });
2133 parts.fParts.erase(it, parts.end());
2134 if (parts.fParts.size()) {
2135 LOG(
debug) << parts.fParts.size() <<
" messages backpressured";
2147 auto inputTypes = getInputTypes();
2148 if (
bool(inputTypes) ==
false) {
2149 reportError(
"Parts should come in couples. Dropping it.");
2152 handleValidMessages(*inputTypes);
2158struct InputLatency {
2163auto calculateInputRecordLatency(
InputRecord const& record, uint64_t currentTime) -> InputLatency
2167 for (
auto& item : record) {
2168 auto* header = o2::header::get<DataProcessingHeader*>(item.header);
2169 if (header ==
nullptr) {
2172 int64_t partLatency = (0x7fffffffffffffff & currentTime) - (0x7fffffffffffffff & header->creation);
2173 if (partLatency < 0) {
2176 result.minLatency = std::min(
result.minLatency, (uint64_t)partLatency);
2177 result.maxLatency = std::max(
result.maxLatency, (uint64_t)partLatency);
2182auto calculateTotalInputRecordSize(
InputRecord const& record) ->
int
2184 size_t totalInputSize = 0;
2185 for (
auto& item : record) {
2186 auto* header = o2::header::get<DataHeader*>(item.header);
2187 if (header ==
nullptr) {
2190 totalInputSize += header->payloadSize;
2192 return totalInputSize;
2195template <
typename T>
2196void update_maximum(std::atomic<T>& maximum_value, T
const&
value)
noexcept
2198 T prev_value = maximum_value;
2199 while (prev_value <
value &&
2200 !maximum_value.compare_exchange_weak(prev_value,
value)) {
2208 LOGP(
debug,
"DataProcessingDevice::tryDispatchComputation");
2213 std::vector<MessageSet> currentSetOfInputs;
2216 auto getInputSpan = [
ref, ¤tSetOfInputs](
TimesliceSlot slot,
bool consume =
true) {
2221 currentSetOfInputs = relayer.consumeExistingInputsForTimeslice(slot);
2223 auto getter = [¤tSetOfInputs](
size_t i,
size_t partindex) ->
DataRef {
2224 if (currentSetOfInputs[
i].getNumberOfPairs() > partindex) {
2225 const char* headerptr =
nullptr;
2226 const char* payloadptr =
nullptr;
2227 size_t payloadSize = 0;
2233 auto const& headerMsg = currentSetOfInputs[
i].associatedHeader(partindex);
2234 auto const& payloadMsg = currentSetOfInputs[
i].associatedPayload(partindex);
2235 headerptr =
static_cast<char const*
>(headerMsg->GetData());
2236 payloadptr = payloadMsg ?
static_cast<char const*
>(payloadMsg->GetData()) :
nullptr;
2237 payloadSize = payloadMsg ? payloadMsg->GetSize() : 0;
2238 return DataRef{
nullptr, headerptr, payloadptr, payloadSize};
2242 auto nofPartsGetter = [¤tSetOfInputs](
size_t i) ->
size_t {
2243 return currentSetOfInputs[
i].getNumberOfPairs();
2245#if __has_include(<fairmq/shmem/Message.h>)
2246 auto refCountGetter = [¤tSetOfInputs](
size_t idx) ->
int {
2247 auto& header =
static_cast<const fair::mq::shmem::Message&
>(*currentSetOfInputs[idx].header(0));
2248 return header.GetRefCount();
2251 std::function<
int(
size_t)> refCountGetter =
nullptr;
2253 return InputSpan{getter, nofPartsGetter, refCountGetter, currentSetOfInputs.
size()};
2268 auto timeslice = relayer.getTimesliceForSlot(
i);
2270 timingInfo.timeslice = timeslice.value;
2280 auto timeslice = relayer.getTimesliceForSlot(
i);
2282 timingInfo.globalRunNumberChanged = !
TimingInfo::timesliceIsTimer(timeslice.value) && dataProcessorContext.lastRunNumberProcessed != timingInfo.runNumber;
2284 timingInfo.globalRunNumberChanged &= (dataProcessorContext.lastRunNumberProcessed == -1 || timingInfo.runNumber != 0);
2288 timingInfo.streamRunNumberChanged = timingInfo.globalRunNumberChanged;
2296 assert(record.size() == currentSetOfInputs.size());
2297 for (
size_t ii = 0, ie = record.size(); ii < ie; ++ii) {
2301 DataRef input = record.getByPos(ii);
2305 if (input.
header ==
nullptr) {
2309 currentSetOfInputs[ii].clear();
2320 for (
size_t pi = 0, pe = record.size(); pi < pe; ++pi) {
2321 DataRef input = record.getByPos(pi);
2322 if (input.
header ==
nullptr) {
2325 auto sih = o2::header::get<SourceInfoHeader*>(input.
header);
2330 auto dh = o2::header::get<DataHeader*>(input.
header);
2340 if (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) {
2343 pi += dh->splitPayloadParts - 1;
2345 size_t pi = pi + (dh->splitPayloadParts > 0 ? dh->splitPayloadParts : 1) * 2;
2351 if (completed.empty() ==
true) {
2352 LOGP(
debug,
"No computations available for dispatching.");
2359 std::atomic_thread_fence(std::memory_order_release);
2360 char relayerSlotState[1024];
2362 char*
buffer = relayerSlotState + written;
2363 for (
size_t ai = 0; ai != record.size(); ai++) {
2364 buffer[ai] = record.isValid(ai) ?
'3' :
'0';
2366 buffer[record.size()] = 0;
2368 .size = (
int)(record.size() +
buffer - relayerSlotState),
2369 .
data = relayerSlotState});
2370 uint64_t tEnd = uv_hrtime();
2372 int64_t wallTimeMs = (tEnd - tStart) / 1000000;
2380 auto latency = calculateInputRecordLatency(record, tStartMilli);
2383 static int count = 0;
2390 std::atomic_thread_fence(std::memory_order_release);
2391 char relayerSlotState[1024];
2393 char*
buffer = strchr(relayerSlotState,
' ') + 1;
2394 for (
size_t ai = 0; ai != record.size(); ai++) {
2395 buffer[ai] = record.isValid(ai) ?
'2' :
'0';
2397 buffer[record.size()] = 0;
2415 switch (spec.completionPolicy.order) {
2417 std::sort(completed.begin(), completed.end(), [](
auto const&
a,
auto const&
b) { return a.timeslice.value < b.timeslice.value; });
2420 std::sort(completed.begin(), completed.end(), [](
auto const&
a,
auto const&
b) { return a.slot.index < b.slot.index; });
2427 for (
auto action : completed) {
2429 O2_SIGNPOST_START(device, aid,
"device",
"Processing action on slot %lu for action %{public}s", action.
slot.
index, fmt::format(
"{}", action.
op).c_str());
2453 dpContext.preProcessingCallbacks(processContext);
2456 context.postDispatchingCallbacks(processContext);
2457 if (spec.forwards.empty() ==
false) {
2459 forwardInputs(
ref, action.
slot, currentSetOfInputs, timesliceIndex.getOldestPossibleOutput(),
false);
2460 O2_SIGNPOST_END(device, aid,
"device",
"Forwarding inputs consume: %d.",
false);
2468 bool hasForwards = spec.forwards.empty() ==
false;
2471 if (context.canForwardEarly && hasForwards && consumeSomething) {
2472 O2_SIGNPOST_EVENT_EMIT(device, aid,
"device",
"Early forwainding: %{public}s.", fmt::format(
"{}", action.
op).c_str());
2476 markInputsAsDone(action.
slot);
2478 uint64_t tStart = uv_hrtime();
2480 preUpdateStats(action, record, tStart);
2482 static bool noCatch = getenv(
"O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv(
"O2_NO_CATCHALL_EXCEPTIONS"),
"0");
2490 switch (action.
op) {
2501 if (
state.quitRequested ==
false) {
2505 streamContext.preProcessingCallbacks(processContext);
2511 if (context.statefulProcess && shouldProcess(action)) {
2515 (context.statefulProcess)(processContext);
2517 }
else if (context.statelessProcess && shouldProcess(action)) {
2519 (context.statelessProcess)(processContext);
2521 }
else if (context.statelessProcess || context.statefulProcess) {
2524 O2_SIGNPOST_EVENT_EMIT(device, pcid,
"device",
"No processing callback provided. Switching to %{public}s.",
"Idle");
2527 if (shouldProcess(action)) {
2529 if (timingInfo.globalRunNumberChanged) {
2530 context.lastRunNumberProcessed = timingInfo.runNumber;
2547 streamContext.finaliseOutputsCallbacks(processContext);
2553 streamContext.postProcessingCallbacks(processContext);
2559 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
2560 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
2566 (context.errorHandling)(e, record);
2571 }
catch (std::exception& ex) {
2576 (context.errorHandling)(e, record);
2578 (context.errorHandling)(e, record);
2581 if (
state.severityStack.empty() ==
false) {
2582 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
2583 state.severityStack.pop_back();
2586 postUpdateStats(action, record, tStart, tStartMilli);
2590 cleanupRecord(record);
2591 context.postDispatchingCallbacks(processContext);
2594 if ((context.canForwardEarly ==
false) && hasForwards && consumeSomething) {
2599 context.postForwardingCallbacks(processContext);
2601 cleanTimers(action.
slot, record);
2603 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());
2605 O2_SIGNPOST_END(device, sid,
"device",
"Start processing ready actions");
2609 LOGP(detail,
"Broadcasting end of stream");
2610 for (
auto& channel : spec.outputChannels) {
2633 cfg.getRecursive(
name);
2634 std::vector<std::unique_ptr<ParamRetriever>> retrievers;
2635 retrievers.emplace_back(std::make_unique<ConfigurationOptionsRetriever>(&cfg,
name));
2636 auto configStore = std::make_unique<ConfigParamStore>(options, std::move(retrievers));
2637 configStore->preload();
2638 configStore->activate();
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
o2::configuration::ConfigurationInterface ConfigurationInterface
constexpr int DEFAULT_MAX_CHANNEL_AHEAD
std::enable_if_t< std::is_signed< T >::value, bool > hasData(const CalArray< T > &cal)
#define O2_SIGNPOST_EVENT_EMIT_ERROR(log, id, name, format,...)
#define O2_DECLARE_DYNAMIC_LOG(name)
#define O2_SIGNPOST_ID_FROM_POINTER(name, log, pointer)
#define O2_SIGNPOST_EVENT_EMIT_INFO(log, id, name, format,...)
#define O2_SIGNPOST_END(log, id, name, format,...)
#define O2_LOG_ENABLED(log)
#define O2_SIGNPOST_ID_GENERATE(name, log)
#define O2_SIGNPOST_EVENT_EMIT(log, id, name, format,...)
#define O2_SIGNPOST_START(log, id, name, format,...)
constexpr uint32_t runtime_hash(char const *str)
o2::monitoring::Monitoring Monitoring
@ 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)
void error(const char *msg)
static void doPrepare(ServiceRegistryRef)
static bool tryDispatchComputation(ServiceRegistryRef ref, std::vector< DataRelayer::RecordAction > &completed)
static void handleData(ServiceRegistryRef, InputChannelInfo &)
DataProcessingDevice(RunningDeviceRef ref, ServiceRegistry &, ProcessingPolicies &policies)
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< MessageSet > 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.
bool active() const
Check if service of type T is currently active.
GLuint const GLchar * name
GLboolean GLboolean GLboolean b
GLsizei const GLfloat * value
GLint GLint GLsizei GLint GLenum GLenum type
GLuint GLsizei GLsizei * length
typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode)
GLuint GLsizei const GLchar * message
GLboolean GLboolean GLboolean GLboolean a
GLbitfield GLuint64 timeout
Defining PrimaryVertex explicitly as messageable.
auto decongestionCallbackLate
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)
bool hasOnlyGenerated(DeviceSpec const &spec)
void on_socket_polled(uv_poll_t *poller, int status, int events)
void on_transition_requested_expired(uv_timer_t *handle)
void run_callback(uv_work_t *handle)
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)
auto switchState(ServiceRegistryRef &ref, StreamingState newState) -> void
void on_awake_main_thread(uv_async_t *handle)
@ SHM_OFFER_BYTES_CONSUMED
@ 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.
void on_data_processing_expired(uv_timer_t *handle)
bool hasOnlyTimers(DeviceSpec const &spec)
constexpr const char * channelName(int channel)
a couple of static helper functions to create timestamp values for CCDB queries or override obsolete ...
Defining DataPointCompositeObject explicitly as copiable.
static void run(AsyncQueue &queue, TimesliceId oldestPossibleTimeslice)
static void post(AsyncQueue &queue, AsyncTask const &task)
An actuatual task to be executed.
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 sharedMemory
How much shared memory it can allocate.
Statistics on the offers consumed, expired.
static void sendEndOfStream(ServiceRegistryRef const &ref, OutputChannelSpec const &channel)
static bool sendOldestPossibleTimeframe(ServiceRegistryRef const &ref, ForwardChannelInfo const &info, ForwardChannelState &state, size_t timeslice)
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.
void updateStats(CommandSpec cmd)
std::function< void(o2::framework::RuntimeErrorRef e, InputRecord &record)> errorHandling
AlgorithmSpec::InitErrorCallback initError
void preLoopCallbacks(ServiceRegistryRef)
Invoke callbacks before we enter the event loop.
void postStopCallbacks(ServiceRegistryRef)
Invoke callbacks on stop.
void preProcessingCallbacks(ProcessingContext &)
Invoke callbacks to be executed before every process method invokation.
ServiceRegistry * registry
bool canForwardEarly
Wether or not the associated DataProcessor can forward things early.
AlgorithmSpec::ErrorCallback error
void preStartCallbacks(ServiceRegistryRef)
Invoke callbacks to be executed in PreRun(), before the User Start callbacks.
AlgorithmSpec::ProcessCallback statefulProcess
static std::vector< size_t > createDistinctRouteIndex(std::vector< InputRoute > const &)
CompletionPolicy::CompletionOp op
@ 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 header::DataOrigin asConcreteOrigin(InputSpec const &spec)
TimesliceIndex::OldestOutputInfo oldestTimeslice
static unsigned int pipelineLength()
get max number of timeslices in the queue
static bool onlineDeploymentMode()
@true if running online
static std::unique_ptr< ConfigParamStore > getConfiguration(ServiceRegistryRef registry, const char *name, std::vector< ConfigParamSpec > const &options)
uv_signal_t * sigusr1Handle
int expectedRegionCallbacks
std::vector< InputRoute > inputs
std::vector< InputChannelSpec > inputChannels
Running state information of a given device.
uv_async_t * awakeMainThread
std::atomic< int64_t > cleanupCount
Forward channel information.
ChannelAccountingType channelType
Wether or not it's a DPL internal channel.
fair::mq::Channel & channel
std::string name
The name of the channel.
ForwardingPolicy const * policy
ForwardingCallback forward
InputChannelInfo * channelInfo
fair::mq::Socket * socket
DataProcessingDevice * device
enum TerminationPolicy termination
enum EarlyForwardPolicy earlyForward
enum TerminationPolicy error
Information about the running workflow.
static Salt streamSalt(short streamId, short dataProcessorId)
void lateBindStreamServices(DeviceState &state, fair::mq::ProgOptions &options, ServiceRegistry::Salt salt)
static Salt globalStreamSalt(short streamId)
static Salt globalDeviceSalt()
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 preEOSCallbacks(EndOfStreamContext &eosContext)
Invoke callbacks to be executed before every EOS user callback 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.
static bool timesliceIsTimer(size_t timeslice)
static TimesliceId getTimeslice(data_matcher::VariableContext const &variables)
void backpressure(InputChannelInfo const &)
locked_execution(ServiceRegistryRef &ref_)
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"
uint64_t const void const *restrict const msg