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>
126 return std::all_of(spec.
inputs.cbegin(), spec.
inputs.cend(), [](
InputRoute const& route) ->
bool { return route.matcher.lifetime == Lifetime::Timer; });
131 return (spec.
inputChannels.size() == 1) && (spec.
inputs[0].matcher.lifetime == Lifetime::Timer || spec.
inputs[0].matcher.lifetime == Lifetime::Enumeration);
142 std::string messageOnExpire =
hasOnlyGenerated(spec) ?
"DPL exit transition grace period for source expired. Exiting." : fmt::format(
"DPL exit transition grace period for {} expired. Exiting.",
state.allowedProcessing ==
DeviceState::CalibrationOnly ?
"calibration" :
"data & calibration").c_str();
157 O2_SIGNPOST_START(device, dpid,
"state",
"Starting processing state %d", (
int)newState);
158 state.streaming = newState;
173 O2_SIGNPOST_EVENT_EMIT_INFO(calibration, cid,
"callback",
"Grace period for data processing expired. Switching to EndOfStreaming.");
176 O2_SIGNPOST_EVENT_EMIT_INFO(calibration, cid,
"callback",
"Grace period for data processing expired. Only calibrations from this point onwards.");
190 return devices[running.
index];
200 : mRunningDevice{running},
201 mConfigRegistry{nullptr},
202 mServiceRegistry{registry},
203 mProcessingPolicies{policies}
205 GetConfig()->Subscribe<std::string>(
"dpl", [®istry = mServiceRegistry](
const std::string&
key, std::string
value) {
206 if (
key ==
"cleanup") {
210 int64_t newCleanupCount = std::stoll(
value);
211 if (newCleanupCount <= cleanupCount) {
214 deviceState.cleanupCount.store(newCleanupCount);
215 for (
auto& info : deviceState.inputChannelInfos) {
216 fair::mq::Parts parts;
217 while (info.channel->Receive(parts, 0)) {
218 LOGP(
debug,
"Dropping {} parts", parts.Size());
219 if (parts.Size() == 0) {
227 std::function<
void(
const fair::mq::State)> stateWatcher = [
this, ®istry = mServiceRegistry](
const fair::mq::State
state) ->
void {
232 control.notifyDeviceState(fair::mq::GetStateName(
state));
235 if (deviceState.nextFairMQState.empty() ==
false) {
236 auto state = deviceState.nextFairMQState.back();
238 deviceState.nextFairMQState.pop_back();
243 this->SubscribeToStateChange(
"99-dpl", stateWatcher);
254 mAwakeHandle->data = &
state;
256 LOG(
error) <<
"Unable to initialise subscription";
260 SubscribeToNewTransition(
"dpl", [wakeHandle = mAwakeHandle](fair::mq::Transition t) {
261 int res = uv_async_send(wakeHandle);
263 LOG(
error) <<
"Unable to notify subscription";
265 LOG(
debug) <<
"State transition requested";
279 O2_SIGNPOST_START(device, sid,
"run_callback",
"Starting run callback on stream %d", task->id.index);
282 O2_SIGNPOST_END(device, sid,
"run_callback",
"Done processing data for stream %d", task->id.index);
295 using o2::monitoring::Metric;
296 using o2::monitoring::Monitoring;
297 using o2::monitoring::tags::Key;
298 using o2::monitoring::tags::Value;
302 stats.totalConsumedBytes += accumulatedConsumed.
sharedMemory;
305 dpStats.processCommandQueue();
313 dpStats.processCommandQueue();
316 for (
auto& consumer :
state.offerConsumers) {
317 quotaEvaluator.consume(task->id.index, consumer, reportConsumedOffer);
319 state.offerConsumers.clear();
320 quotaEvaluator.handleExpired(reportExpiredOffer);
321 quotaEvaluator.dispose(task->id.index);
322 task->running =
false;
350 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"Data pending on socket for channel %{public}s", context->name);
354 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"Socket connected for channel %{public}s", context->name);
356 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"Socket connected for read in context %{public}s", context->name);
357 uv_poll_start(poller, UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED, &
on_socket_polled);
360 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"Socket connected for write for channel %{public}s", context->name);
368 case UV_DISCONNECT: {
369 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"Socket disconnected in context %{public}s", context->name);
371 case UV_PRIORITIZED: {
372 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"Socket prioritized for context %{public}s", context->name);
384 LOGP(fatal,
"Error while polling {}: {}", context->name, status);
389 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"Data pending on socket for channel %{public}s", context->name);
391 assert(context->channelInfo);
392 context->channelInfo->readPolled =
true;
395 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"OOB socket connected for channel %{public}s", context->name);
397 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"OOB socket connected for read in context %{public}s", context->name);
400 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"OOB socket connected for write for channel %{public}s", context->name);
404 case UV_DISCONNECT: {
405 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"OOB socket disconnected in context %{public}s", context->name);
408 case UV_PRIORITIZED: {
409 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"OOB socket prioritized for context %{public}s", context->name);
430 context.statelessProcess = spec.algorithm.onProcess;
432 context.error = spec.algorithm.onError;
433 context.
initError = spec.algorithm.onInitError;
436 if (configStore ==
nullptr) {
437 std::vector<std::unique_ptr<ParamRetriever>> retrievers;
438 retrievers.emplace_back(std::make_unique<FairOptionsRetriever>(GetConfig()));
439 configStore = std::make_unique<ConfigParamStore>(spec.options, std::move(retrievers));
440 configStore->preload();
441 configStore->activate();
444 using boost::property_tree::ptree;
447 for (
auto&
entry : configStore->store()) {
448 std::stringstream ss;
450 if (
entry.second.empty() ==
false) {
451 boost::property_tree::json_parser::write_json(ss,
entry.second,
false);
455 str =
entry.second.get_value<std::string>();
457 std::string configString = fmt::format(
"[CONFIG] {}={} 1 {}",
entry.first,
str, configStore->provenance(
entry.first.c_str())).c_str();
461 mConfigRegistry = std::make_unique<ConfigParamRegistry>(std::move(configStore));
464 if (context.initError) {
465 context.initErrorHandling = [&errorCallback = context.initError,
478 errorCallback(errorContext);
481 context.initErrorHandling = [&serviceRegistry = mServiceRegistry](
RuntimeErrorRef e) {
496 context.expirationHandlers.clear();
497 context.init = spec.algorithm.onInit;
499 static bool noCatch = getenv(
"O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv(
"O2_NO_CATCHALL_EXCEPTIONS"),
"0");
500 InitContext initContext{*mConfigRegistry, mServiceRegistry};
504 context.statefulProcess = context.init(initContext);
506 if (context.initErrorHandling) {
507 (context.initErrorHandling)(e);
512 context.statefulProcess = context.init(initContext);
513 }
catch (std::exception& ex) {
518 (context.initErrorHandling)(e);
520 (context.initErrorHandling)(e);
525 state.inputChannelInfos.resize(spec.inputChannels.size());
529 int validChannelId = 0;
530 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
531 auto&
name = spec.inputChannels[ci].name;
532 if (
name.find(spec.channelPrefix +
"from_internal-dpl-clock") == 0) {
537 state.inputChannelInfos[ci].id = {validChannelId++};
542 if (spec.callbacksPolicy.policy !=
nullptr) {
543 InitContext initContext{*mConfigRegistry, mServiceRegistry};
548 auto* options = GetConfig();
549 for (
size_t si = 0; si < mStreams.size(); ++si) {
563 O2_SIGNPOST_END(device, sid,
"signal_state",
"No registry active. Ignoring signal.");
572 while (ri != quotaEvaluator.mOffers.size()) {
573 auto& offer = quotaEvaluator.mOffers[ri];
579 if (offer.valid && offer.sharedMemory != 0) {
580 O2_SIGNPOST_END(device, sid,
"signal_state",
"Memory already offered.");
586 for (
auto& offer : quotaEvaluator.mOffers) {
587 if (offer.valid ==
false) {
590 offer.sharedMemory = 1000000000;
597 O2_SIGNPOST_END(device, sid,
"signal_state",
"Done processing signals.");
600static auto toBeForwardedHeader = [](
void* header) ->
bool {
605 if (header ==
nullptr) {
608 auto sih = o2::header::get<SourceInfoHeader*>(header);
613 auto dih = o2::header::get<DomainInfoHeader*>(header);
618 auto dh = o2::header::get<DataHeader*>(header);
622 auto dph = o2::header::get<DataProcessingHeader*>(header);
629static auto toBeforwardedMessageSet = [](std::vector<ChannelIndex>& cachedForwardingChoices,
631 std::unique_ptr<fair::mq::Message>& header,
632 std::unique_ptr<fair::mq::Message>& payload,
635 if (header.get() ==
nullptr) {
642 if (payload.get() ==
nullptr && consume ==
true) {
646 header.reset(
nullptr);
650 auto fdph = o2::header::get<DataProcessingHeader*>(header->GetData());
651 if (fdph ==
nullptr) {
652 LOG(error) <<
"Data is missing DataProcessingHeader";
655 auto fdh = o2::header::get<DataHeader*>(header->GetData());
656 if (fdh ==
nullptr) {
657 LOG(error) <<
"Data is missing DataHeader";
664 if (fdh->splitPayloadIndex == 0 || fdh->splitPayloadParts <= 1 || total > 1) {
665 proxy.getMatchingForwardChannelIndexes(cachedForwardingChoices, *fdh, fdph->startTime);
667 return cachedForwardingChoices.empty() ==
false;
681 if (oldestTimeslice.timeslice.value <= decongestion.lastTimeslice) {
682 LOG(
debug) <<
"Not sending already sent oldest possible timeslice " << oldestTimeslice.timeslice.value;
685 for (
int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
686 auto& info = proxy.getForwardChannelInfo(
ChannelIndex{fi});
691 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputsCallback",
"Skipping channel %{public}s because it's not a DPL channel",
697 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputsCallback",
"Forwarding to channel %{public}s oldest possible timeslice %zu, prio 20",
698 info.name.c_str(), oldestTimeslice.timeslice.value);
711 std::vector<fair::mq::Parts> forwardedParts;
712 forwardedParts.resize(proxy.getNumForwards());
713 std::vector<ChannelIndex> cachedForwardingChoices{};
715 O2_SIGNPOST_START(forwarding, sid,
"forwardInputs",
"Starting forwarding for slot %zu with oldestTimeslice %zu %{public}s%{public}s%{public}s",
716 slot.index, oldestTimeslice.timeslice.value, copy ?
"with copy" :
"", copy && consume ?
" and " :
"", consume ?
"with consume" :
"");
718 for (
size_t ii = 0, ie = currentSetOfInputs.size(); ii < ie; ++ii) {
719 auto& messageSet = currentSetOfInputs[ii];
721 if (messageSet.size() == 0) {
724 if (!toBeForwardedHeader(messageSet.header(0)->GetData())) {
727 cachedForwardingChoices.clear();
729 for (
size_t pi = 0; pi < currentSetOfInputs[ii].size(); ++pi) {
730 auto& messageSet = currentSetOfInputs[ii];
731 auto& header = messageSet.header(pi);
732 auto& payload = messageSet.payload(pi);
733 auto total = messageSet.getNumberOfPayloads(pi);
735 if (!toBeforwardedMessageSet(cachedForwardingChoices, proxy, header, payload, total, consume)) {
741 if (cachedForwardingChoices.size() > 1) {
744 auto* dh = o2::header::get<DataHeader*>(header->GetData());
745 auto* dph = o2::header::get<DataProcessingHeader*>(header->GetData());
748 for (
auto& cachedForwardingChoice : cachedForwardingChoices) {
749 auto&& newHeader = header->GetTransport()->CreateMessage();
751 fmt::format(
"{}/{}/{}@timeslice:{} tfCounter:{}", dh->dataOrigin, dh->dataDescription, dh->subSpecification, dph->startTime, dh->tfCounter).c_str(), cachedForwardingChoice.value);
752 newHeader->Copy(*header);
753 forwardedParts[cachedForwardingChoice.value].AddPart(std::move(newHeader));
755 for (
size_t payloadIndex = 0; payloadIndex < messageSet.getNumberOfPayloads(pi); ++payloadIndex) {
756 auto&& newPayload = header->GetTransport()->CreateMessage();
757 newPayload->Copy(*messageSet.payload(pi, payloadIndex));
758 forwardedParts[cachedForwardingChoice.value].AddPart(std::move(newPayload));
763 fmt::format(
"{}/{}/{}@timeslice:{} tfCounter:{}", dh->dataOrigin, dh->dataDescription, dh->subSpecification, dph->startTime, dh->tfCounter).c_str(), cachedForwardingChoices.back().value);
764 forwardedParts[cachedForwardingChoices.back().value].AddPart(std::move(messageSet.header(pi)));
765 for (
size_t payloadIndex = 0; payloadIndex < messageSet.getNumberOfPayloads(pi); ++payloadIndex) {
766 forwardedParts[cachedForwardingChoices.back().value].AddPart(std::move(messageSet.payload(pi, payloadIndex)));
771 O2_SIGNPOST_EVENT_EMIT(forwarding, sid,
"forwardInputs",
"Forwarding %zu messages", forwardedParts.size());
772 for (
int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
773 if (forwardedParts[fi].
Size() == 0) {
777 auto& parts = forwardedParts[fi];
778 if (info.
policy ==
nullptr) {
789 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputs",
"Queuing forwarding oldestPossible %zu", oldestTimeslice.timeslice.value);
801 if (infos.empty() ==
false) {
802 std::vector<fair::mq::RegionInfo> toBeNotified;
803 toBeNotified.swap(infos);
804 static bool dummyRead = getenv(
"DPL_DEBUG_MAP_ALL_SHM_REGIONS") && atoi(getenv(
"DPL_DEBUG_MAP_ALL_SHM_REGIONS"));
805 for (
auto const& info : toBeNotified) {
825void DataProcessingDevice::initPollers()
833 if ((context.statefulProcess !=
nullptr) || (context.statelessProcess !=
nullptr)) {
834 for (
auto& [channelName, channel] : GetChannels()) {
836 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
837 auto& channelSpec = spec.inputChannels[ci];
838 channelInfo = &
state.inputChannelInfos[ci];
839 if (channelSpec.name != channelName) {
842 channelInfo->
channel = &this->GetChannel(channelName, 0);
845 if ((
channelName.rfind(
"from_internal-dpl", 0) == 0) &&
846 (
channelName.rfind(
"from_internal-dpl-aod", 0) != 0) &&
847 (
channelName.rfind(
"from_internal-dpl-ccdb-backend", 0) != 0) &&
848 (
channelName.rfind(
"from_internal-dpl-injected", 0)) != 0) {
849 LOGP(detail,
"{} is an internal channel. Skipping as no input will come from there.", channelName);
853 if (
channelName.rfind(
"from_" + spec.name +
"_", 0) == 0) {
854 LOGP(detail,
"{} is to send data. Not polling.", channelName);
859 LOGP(detail,
"{} is not a DPL socket. Not polling.", channelName);
865 size_t zmq_fd_len =
sizeof(zmq_fd);
868 channel[0].GetSocket().GetOption(
"fd", &zmq_fd, &zmq_fd_len);
873 LOGP(detail,
"Polling socket for {}", channelName);
876 pCtx->loop =
state.loop;
878 pCtx->state = &
state;
880 assert(channelInfo !=
nullptr);
881 pCtx->channelInfo = channelInfo;
882 pCtx->socket = &channel[0].GetSocket();
885 uv_poll_init(
state.loop, poller, zmq_fd);
887 LOGP(detail,
"{} is an out of band channel.", channelName);
888 state.activeOutOfBandPollers.push_back(poller);
891 state.activeInputPollers.push_back(poller);
897 if (
state.activeInputPollers.empty() &&
898 state.activeOutOfBandPollers.empty() &&
899 state.activeTimers.empty() &&
900 state.activeSignals.empty()) {
904 if (
state.inputChannelInfos.empty()) {
905 LOGP(detail,
"No input channels. Setting exit transition timeout to 0.");
906 deviceContext.exitTransitionTimeout = 0;
908 for (
auto& [channelName, channel] : GetChannels()) {
909 if (
channelName.rfind(spec.channelPrefix +
"from_internal-dpl", 0) == 0) {
910 LOGP(detail,
"{} is an internal channel. Not polling.", channelName);
913 if (
channelName.rfind(spec.channelPrefix +
"from_" + spec.name +
"_", 0) == 0) {
914 LOGP(detail,
"{} is an out of band channel. Not polling for output.", channelName);
919 size_t zmq_fd_len =
sizeof(zmq_fd);
922 channel[0].GetSocket().GetOption(
"fd", &zmq_fd, &zmq_fd_len);
924 LOGP(
error,
"Cannot get file descriptor for channel {}", channelName);
927 LOG(detail) <<
"Polling socket for " << channel[0].GetName();
931 pCtx->loop =
state.loop;
933 pCtx->state = &
state;
937 uv_poll_init(
state.loop, poller, zmq_fd);
938 state.activeOutputPollers.push_back(poller);
942 LOGP(detail,
"This is a fake device so we exit after the first iteration.");
943 deviceContext.exitTransitionTimeout = 0;
949 uv_timer_init(
state.loop, timer);
950 timer->data = &
state;
951 uv_update_time(
state.loop);
953 state.activeTimers.push_back(timer);
957void DataProcessingDevice::startPollers()
963 for (
auto* poller :
state.activeInputPollers) {
965 O2_SIGNPOST_START(device, sid,
"socket_state",
"Input socket waiting for connection.");
969 for (
auto& poller :
state.activeOutOfBandPollers) {
973 for (
auto* poller :
state.activeOutputPollers) {
975 O2_SIGNPOST_START(device, sid,
"socket_state",
"Output socket waiting for connection.");
982 uv_timer_init(
state.loop, deviceContext.gracePeriodTimer);
985 deviceContext.dataProcessingGracePeriodTimer->data =
new ServiceRegistryRef(mServiceRegistry);
986 uv_timer_init(
state.loop, deviceContext.dataProcessingGracePeriodTimer);
989void DataProcessingDevice::stopPollers()
994 LOGP(detail,
"Stopping {} input pollers",
state.activeInputPollers.size());
995 for (
auto* poller :
state.activeInputPollers) {
998 uv_poll_stop(poller);
1001 LOGP(detail,
"Stopping {} out of band pollers",
state.activeOutOfBandPollers.size());
1002 for (
auto* poller :
state.activeOutOfBandPollers) {
1003 uv_poll_stop(poller);
1006 LOGP(detail,
"Stopping {} output pollers",
state.activeOutOfBandPollers.size());
1007 for (
auto* poller :
state.activeOutputPollers) {
1009 O2_SIGNPOST_END(device, sid,
"socket_state",
"Output socket closed.");
1010 uv_poll_stop(poller);
1014 uv_timer_stop(deviceContext.gracePeriodTimer);
1016 free(deviceContext.gracePeriodTimer);
1017 deviceContext.gracePeriodTimer =
nullptr;
1019 uv_timer_stop(deviceContext.dataProcessingGracePeriodTimer);
1021 free(deviceContext.dataProcessingGracePeriodTimer);
1022 deviceContext.dataProcessingGracePeriodTimer =
nullptr;
1037 for (
auto&
di : distinct) {
1038 auto& route = spec.inputs[
di];
1039 if (route.configurator.has_value() ==
false) {
1044 .
name = route.configurator->name,
1046 .lifetime = route.matcher.lifetime,
1047 .creator = route.configurator->creatorConfigurator(
state, mServiceRegistry, *mConfigRegistry),
1048 .checker = route.configurator->danglingConfigurator(
state, *mConfigRegistry),
1049 .handler = route.configurator->expirationConfigurator(
state, *mConfigRegistry)};
1050 context.expirationHandlers.emplace_back(std::move(handler));
1053 if (
state.awakeMainThread ==
nullptr) {
1059 deviceContext.expectedRegionCallbacks = std::stoi(fConfig->GetValue<std::string>(
"expected-region-callbacks"));
1060 deviceContext.exitTransitionTimeout = std::stoi(fConfig->GetValue<std::string>(
"exit-transition-timeout"));
1061 deviceContext.dataProcessingTimeout = std::stoi(fConfig->GetValue<std::string>(
"data-processing-timeout"));
1063 for (
auto& channel : GetChannels()) {
1064 channel.second.at(0).Transport()->SubscribeToRegionEvents([&context = deviceContext,
1065 ®istry = mServiceRegistry,
1066 &pendingRegionInfos = mPendingRegionInfos,
1067 ®ionInfoMutex = mRegionInfoMutex](fair::mq::RegionInfo info) {
1068 std::lock_guard<std::mutex> lock(regionInfoMutex);
1069 LOG(detail) <<
">>> Region info event" << info.event;
1070 LOG(detail) <<
"id: " << info.id;
1071 LOG(detail) <<
"ptr: " << info.ptr;
1072 LOG(detail) <<
"size: " << info.size;
1073 LOG(detail) <<
"flags: " << info.flags;
1076 pendingRegionInfos.push_back(info);
1089 if (deviceContext.sigusr1Handle ==
nullptr) {
1091 deviceContext.sigusr1Handle->data = &mServiceRegistry;
1092 uv_signal_init(
state.loop, deviceContext.sigusr1Handle);
1096 for (
auto& handle :
state.activeSignals) {
1097 handle->data = &
state;
1100 deviceContext.sigusr1Handle->data = &mServiceRegistry;
1103 DataProcessingDevice::initPollers();
1111 LOG(
error) <<
"DataProcessor " <<
state.lastActiveDataProcessor.load()->spec->name <<
" was unexpectedly active";
1123 O2_SIGNPOST_END(device, cid,
"InitTask",
"Exiting InitTask callback waiting for the remaining region callbacks.");
1125 auto hasPendingEvents = [&mutex = mRegionInfoMutex, &pendingRegionInfos = mPendingRegionInfos](
DeviceContext& deviceContext) {
1126 std::lock_guard<std::mutex> lock(mutex);
1127 return (pendingRegionInfos.empty() ==
false) || deviceContext.expectedRegionCallbacks > 0;
1134 while (hasPendingEvents(deviceContext)) {
1136 uv_run(
state.loop, UV_RUN_ONCE);
1140 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1144 O2_SIGNPOST_END(device, cid,
"InitTask",
"Done waiting for registration events.");
1151 bool enableRateLimiting = std::stoi(fConfig->GetValue<std::string>(
"timeframes-rate-limit"));
1160 if (enableRateLimiting ==
false && spec.name.find(
"internal-dpl-injected-dummy-sink") != std::string::npos) {
1163 if (enableRateLimiting) {
1164 for (
auto& spec : spec.outputs) {
1165 if (spec.matcher.binding.value ==
"dpl-summary") {
1172 context.
registry = &mServiceRegistry;
1175 if (context.
error !=
nullptr) {
1189 errorCallback(errorContext);
1203 switch (errorPolicy) {
1214 auto decideEarlyForward = [&context, &spec,
this]() ->
bool {
1218 bool onlyConditions =
true;
1219 bool overriddenEarlyForward =
false;
1220 for (
auto& forwarded : spec.forwards) {
1221 if (forwarded.matcher.lifetime != Lifetime::Condition) {
1222 onlyConditions =
false;
1224#if !__has_include(<fairmq/shmem/Message.h>)
1227 overriddenEarlyForward =
true;
1234 overriddenEarlyForward =
true;
1238 if (forwarded.matcher.lifetime == Lifetime::Optional) {
1240 overriddenEarlyForward =
true;
1245 if (!overriddenEarlyForward && onlyConditions) {
1247 LOG(detail) <<
"Enabling early forwarding because only conditions to be forwarded";
1249 return canForwardEarly;
1261 state.quitRequested =
false;
1264 for (
auto& info :
state.inputChannelInfos) {
1276 for (
size_t i = 0;
i < mStreams.size(); ++
i) {
1279 context.preStartStreamCallbacks(streamRef);
1281 }
catch (std::exception& e) {
1282 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"PreRun",
"Exception of type std::exception caught in PreRun: %{public}s. Rethrowing.", e.what());
1283 O2_SIGNPOST_END(device, cid,
"PreRun",
"Exiting PreRun due to exception thrown.");
1287 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"PreRun",
"Exception of type o2::framework::RuntimeErrorRef caught in PreRun: %{public}s. Rethrowing.", err.what);
1288 O2_SIGNPOST_END(device, cid,
"PreRun",
"Exiting PreRun due to exception thrown.");
1291 O2_SIGNPOST_END(device, cid,
"PreRun",
"Unknown exception being thrown. Rethrowing.");
1299 using o2::monitoring::Metric;
1300 using o2::monitoring::Monitoring;
1301 using o2::monitoring::tags::Key;
1302 using o2::monitoring::tags::Value;
1305 monitoring.send(
Metric{(uint64_t)1,
"device_state"}.addTag(Key::Subsystem, Value::DPL));
1313 using o2::monitoring::Metric;
1314 using o2::monitoring::Monitoring;
1315 using o2::monitoring::tags::Key;
1316 using o2::monitoring::tags::Value;
1319 monitoring.send(
Metric{(uint64_t)0,
"device_state"}.addTag(Key::Subsystem, Value::DPL));
1338 bool firstLoop =
true;
1340 O2_SIGNPOST_START(device, lid,
"device_state",
"First iteration of the device loop");
1342 bool dplEnableMultithreding = getenv(
"DPL_THREADPOOL_SIZE") !=
nullptr;
1343 if (dplEnableMultithreding) {
1344 setenv(
"UV_THREADPOOL_SIZE",
"1", 1);
1348 if (
state.nextFairMQState.empty() ==
false) {
1349 (
void)this->ChangeState(
state.nextFairMQState.back());
1350 state.nextFairMQState.pop_back();
1355 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1368 state.lastActiveDataProcessor.compare_exchange_strong(lastActive,
nullptr);
1370 auto shouldNotWait = (lastActive !=
nullptr &&
1374 shouldNotWait =
true;
1377 if (lastActive !=
nullptr) {
1380 if (NewStatePending()) {
1382 shouldNotWait =
true;
1395 if (deviceContext.dataProcessingTimeout > 0 && deviceContext.dataProcessingTimeout < deviceContext.exitTransitionTimeout) {
1396 uv_update_time(
state.loop);
1397 O2_SIGNPOST_EVENT_EMIT(calibration, lid,
"timer_setup",
"Starting %d s timer for dataProcessingTimeout.", deviceContext.dataProcessingTimeout);
1398 uv_timer_start(deviceContext.dataProcessingGracePeriodTimer,
on_data_processing_expired, deviceContext.dataProcessingTimeout * 1000, 0);
1403 uv_update_time(
state.loop);
1404 O2_SIGNPOST_EVENT_EMIT(calibration, lid,
"timer_setup",
"Starting %d s timer for exitTransitionTimeout.",
1405 deviceContext.exitTransitionTimeout);
1408 int timeout = onlyGenerated ? deviceContext.dataProcessingTimeout : deviceContext.exitTransitionTimeout;
1413 "New state requested. Waiting for %d seconds before %{public}s",
1415 onlyGenerated ?
"dropping remaining input and switching to READY state." :
"switching to READY state.");
1420 O2_SIGNPOST_EVENT_EMIT_INFO(device, lid,
"run_loop",
"New state requested. No timeout set, quitting immediately as per --completion-policy");
1422 O2_SIGNPOST_EVENT_EMIT_INFO(device, lid,
"run_loop",
"New state requested. No timeout set, switching to READY state immediately");
1424 O2_SIGNPOST_EVENT_EMIT_INFO(device, lid,
"run_loop",
"New state pending and we are already idle, quitting immediately as per --completion-policy");
1426 O2_SIGNPOST_EVENT_EMIT_INFO(device, lid,
"run_loop",
"New state pending and we are already idle, switching to READY immediately.");
1432 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"State transition requested and we are now in Idle. We can consider it to be completed.");
1435 if (
state.severityStack.empty() ==
false) {
1436 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
1437 state.severityStack.pop_back();
1443 state.firedTimers.clear();
1445 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
1446 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
1453 O2_SIGNPOST_START(device, lid,
"run_loop",
"Dropping message from slot %" PRIu64
". Forwarding as needed.", (uint64_t)slot.index);
1461 forwardInputs(registry, slot, dropped, oldestOutputInfo,
false,
true);
1466 auto oldestPossibleTimeslice = relayer.getOldestPossibleOutput();
1468 if (shouldNotWait ==
false) {
1472 O2_SIGNPOST_END(device, lid,
"run_loop",
"Run loop completed. %{}s", shouldNotWait ?
"Will immediately schedule a new one" :
"Waiting for next event.");
1473 uv_run(
state.loop, shouldNotWait ? UV_RUN_NOWAIT : UV_RUN_ONCE);
1475 if ((
state.loopReason &
state.tracingFlags) != 0) {
1476 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
1477 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
1478 }
else if (
state.severityStack.empty() ==
false) {
1479 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
1480 state.severityStack.pop_back();
1485 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"Out of band activity detected. Rescanning everything.");
1489 if (!
state.pendingOffers.empty()) {
1490 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"Pending %" PRIu64
" offers. updating the ComputingQuotaEvaluator.", (uint64_t)
state.pendingOffers.size());
1502 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1506 assert(mStreams.size() == mHandles.size());
1509 for (
size_t ti = 0; ti < mStreams.size(); ti++) {
1510 auto& taskInfo = mStreams[ti];
1511 if (taskInfo.running) {
1515 streamRef.index = ti;
1517 using o2::monitoring::Metric;
1518 using o2::monitoring::Monitoring;
1519 using o2::monitoring::tags::Key;
1520 using o2::monitoring::tags::Value;
1523 if (streamRef.index != -1) {
1526 uv_work_t& handle = mHandles[streamRef.index];
1528 handle.data = &mStreams[streamRef.index];
1535 dpStats.processCommandQueue();
1548 stream.registry = &mServiceRegistry;
1549 if (dplEnableMultithreding) [[unlikely]] {
1563 O2_SIGNPOST_END(device, lid,
"run_loop",
"Run loop completed. Transition handling state %d.",
state.transitionHandling);
1566 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
1567 auto& info =
state.inputChannelInfos[ci];
1568 info.parts.fParts.clear();
1579 O2_SIGNPOST_START(device, dpid,
"do_prepare",
"Starting DataProcessorContext::doPrepare.");
1597 context.allDone = std::any_of(
state.inputChannelInfos.begin(),
state.inputChannelInfos.end(), [cid](
const auto& info) {
1599 O2_SIGNPOST_EVENT_EMIT(device, cid,
"do_prepare",
"Input channel %{public}s%{public}s has %zu parts left and is in state %d.",
1600 info.channel->GetName().c_str(), (info.id.value == ChannelIndex::INVALID ?
" (non DPL)" :
""), info.parts.fParts.size(), (int)info.state);
1602 O2_SIGNPOST_EVENT_EMIT(device, cid,
"do_prepare",
"External channel %d is in state %d.", info.id.value, (int)info.state);
1607 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"do_prepare",
"Processing %zu input channels.", spec.inputChannels.size());
1610 static std::vector<int> pollOrder;
1611 pollOrder.resize(
state.inputChannelInfos.size());
1612 std::iota(pollOrder.begin(), pollOrder.end(), 0);
1613 std::sort(pollOrder.begin(), pollOrder.end(), [&infos =
state.inputChannelInfos](
int a,
int b) {
1614 return infos[a].oldestForChannel.value < infos[b].oldestForChannel.value;
1618 if (pollOrder.empty()) {
1619 O2_SIGNPOST_END(device, dpid,
"do_prepare",
"Nothing to poll. Waiting for next iteration.");
1622 auto currentOldest =
state.inputChannelInfos[pollOrder.front()].oldestForChannel;
1623 auto currentNewest =
state.inputChannelInfos[pollOrder.back()].oldestForChannel;
1624 auto delta = currentNewest.value - currentOldest.value;
1625 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"do_prepare",
"Oldest possible timeframe range %" PRIu64
" => %" PRIu64
" delta %" PRIu64,
1626 (int64_t)currentOldest.value, (int64_t)currentNewest.value, (int64_t)delta);
1627 auto& infos =
state.inputChannelInfos;
1629 if (context.balancingInputs) {
1631 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));
1632 auto newEnd = std::remove_if(pollOrder.begin(), pollOrder.end(), [&infos, limitNew = currentOldest.value + ahead](
int a) ->
bool {
1633 return infos[a].oldestForChannel.value > limitNew;
1635 for (
auto it = pollOrder.begin(); it < pollOrder.end(); it++) {
1636 const auto& channelInfo =
state.inputChannelInfos[*it];
1642 bool shouldBeRunning = it < newEnd;
1643 if (running != shouldBeRunning) {
1644 uv_poll_start(poller, shouldBeRunning ? UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED : 0, &
on_socket_polled);
1650 pollOrder.erase(newEnd, pollOrder.end());
1652 O2_SIGNPOST_END(device, dpid,
"do_prepare",
"%zu channels pass the channel inbalance balance check.", pollOrder.size());
1654 for (
auto sci : pollOrder) {
1655 auto& info =
state.inputChannelInfos[sci];
1656 auto& channelSpec = spec.inputChannels[sci];
1658 O2_SIGNPOST_START(device, cid,
"channels",
"Processing channel %s", channelSpec.name.c_str());
1661 context.allDone =
false;
1666 if (info.parts.Size()) {
1669 O2_SIGNPOST_END(device, cid,
"channels",
"Flushing channel %s which is in state %d and has %zu parts still pending.",
1670 channelSpec.name.c_str(), (
int)info.state, info.parts.Size());
1673 if (info.
channel ==
nullptr) {
1674 O2_SIGNPOST_END(device, cid,
"channels",
"Channel %s which is in state %d is nullptr and has %zu parts still pending.",
1675 channelSpec.name.c_str(), (
int)info.state, info.parts.Size());
1680 O2_SIGNPOST_END(device, cid,
"channels",
"Channel %s which is in state %d is not a DPL channel and has %zu parts still pending.",
1681 channelSpec.name.c_str(), (
int)info.state, info.parts.Size());
1684 auto& socket = info.
channel->GetSocket();
1689 if (info.hasPendingEvents == 0) {
1690 socket.Events(&info.hasPendingEvents);
1692 if ((info.hasPendingEvents & 1) == 0 && (info.parts.Size() == 0)) {
1693 O2_SIGNPOST_END(device, cid,
"channels",
"No pending events and no remaining parts to process for channel %{public}s", channelSpec.name.c_str());
1699 info.readPolled =
false;
1708 bool newMessages =
false;
1710 O2_SIGNPOST_EVENT_EMIT(device, cid,
"channels",
"Receiving loop called for channel %{public}s (%d) with oldest possible timeslice %zu",
1711 channelSpec.name.c_str(), info.id.value, info.oldestForChannel.value);
1712 if (info.parts.Size() < 64) {
1713 fair::mq::Parts parts;
1714 info.
channel->Receive(parts, 0);
1716 O2_SIGNPOST_EVENT_EMIT(device, cid,
"channels",
"Received %zu parts from channel %{public}s (%d).", parts.Size(), channelSpec.name.c_str(), info.id.value);
1718 for (
auto&& part : parts) {
1719 info.parts.fParts.emplace_back(std::move(part));
1721 newMessages |=
true;
1724 if (info.parts.Size() >= 0) {
1736 socket.Events(&info.hasPendingEvents);
1737 if (info.hasPendingEvents) {
1738 info.readPolled =
false;
1741 state.lastActiveDataProcessor.store(&context);
1744 O2_SIGNPOST_END(device, cid,
"channels",
"Done processing channel %{public}s (%d).",
1745 channelSpec.name.c_str(), info.id.value);
1760 context.completed.clear();
1761 context.completed.reserve(16);
1763 state.lastActiveDataProcessor.store(&context);
1767 context.preDanglingCallbacks(danglingContext);
1768 if (
state.lastActiveDataProcessor.load() ==
nullptr) {
1771 auto activity =
ref.get<
DataRelayer>().processDanglingInputs(context.expirationHandlers, *context.registry,
true);
1772 if (activity.expiredSlots > 0) {
1773 state.lastActiveDataProcessor = &context;
1776 context.completed.clear();
1778 state.lastActiveDataProcessor = &context;
1781 context.postDanglingCallbacks(danglingContext);
1789 state.lastActiveDataProcessor = &context;
1812 timingInfo.timeslice = relayer.getOldestPossibleOutput().timeslice.value;
1813 timingInfo.tfCounter = -1;
1814 timingInfo.firstTForbit = -1;
1816 timingInfo.creation = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count();
1817 O2_SIGNPOST_EVENT_EMIT(calibration, dpid,
"calibration",
"TimingInfo.keepAtEndOfStream %d", timingInfo.keepAtEndOfStream);
1821 context.preEOSCallbacks(eosContext);
1825 streamContext.postEOSCallbacks(eosContext);
1826 context.postEOSCallbacks(eosContext);
1828 for (
auto& channel : spec.outputChannels) {
1829 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"state",
"Sending end of stream to %{public}s.", channel.name.c_str());
1836 if (shouldProcess) {
1837 state.lastActiveDataProcessor = &context;
1841 for (
auto& poller :
state.activeOutputPollers) {
1842 uv_poll_stop(poller);
1850 for (
auto& poller :
state.activeOutputPollers) {
1851 uv_poll_stop(poller);
1867 if (deviceContext.sigusr1Handle) {
1873 handle->data =
nullptr;
1902 auto getInputTypes = [&info, &context]() -> std::optional<std::vector<InputInfo>> {
1907 auto& parts = info.
parts;
1910 std::vector<InputInfo> results;
1912 results.reserve(parts.Size() / 2);
1913 size_t nTotalPayloads = 0;
1917 if (
type != InputType::Invalid &&
length > 1) {
1918 nTotalPayloads +=
length - 1;
1922 for (
size_t pi = 0; pi < parts.Size(); pi += 2) {
1923 auto* headerData = parts.At(pi)->GetData();
1924 auto sih = o2::header::get<SourceInfoHeader*>(headerData);
1926 O2_SIGNPOST_EVENT_EMIT(device, cid,
"handle_data",
"Got SourceInfoHeader with state %d", (
int)sih->state);
1927 info.
state = sih->state;
1928 insertInputInfo(pi, 2, InputType::SourceInfo, info.
id);
1929 state.lastActiveDataProcessor = &context;
1932 auto dih = o2::header::get<DomainInfoHeader*>(headerData);
1934 O2_SIGNPOST_EVENT_EMIT(device, cid,
"handle_data",
"Got DomainInfoHeader with oldestPossibleTimeslice %d", (
int)dih->oldestPossibleTimeslice);
1935 insertInputInfo(pi, 2, InputType::DomainInfo, info.
id);
1936 state.lastActiveDataProcessor = &context;
1939 auto dh = o2::header::get<DataHeader*>(headerData);
1941 insertInputInfo(pi, 0, InputType::Invalid, info.
id);
1945 if (dh->payloadSize > parts.At(pi + 1)->GetSize()) {
1946 insertInputInfo(pi, 0, InputType::Invalid, info.
id);
1950 auto dph = o2::header::get<DataProcessingHeader*>(headerData);
1955 O2_SIGNPOST_START(parts,
pid,
"parts",
"Processing DataHeader %{public}-4s/%{public}-16s/%d with splitPayloadParts %d and splitPayloadIndex %d",
1956 dh->dataOrigin.str, dh->dataDescription.str, dh->subSpecification, dh->splitPayloadParts, dh->splitPayloadIndex);
1958 insertInputInfo(pi, 2, InputType::Invalid, info.
id);
1962 if (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) {
1965 insertInputInfo(pi, dh->splitPayloadParts + 1, InputType::Data, info.
id);
1966 pi += dh->splitPayloadParts - 1;
1972 size_t finalSplitPayloadIndex = pi + (dh->splitPayloadParts > 0 ? dh->splitPayloadParts : 1) * 2;
1973 if (finalSplitPayloadIndex > parts.Size()) {
1975 insertInputInfo(pi, 0, InputType::Invalid, info.
id);
1978 insertInputInfo(pi, 2, InputType::Data, info.
id);
1979 for (; pi + 2 < finalSplitPayloadIndex; pi += 2) {
1980 insertInputInfo(pi + 2, 2, InputType::Data, info.
id);
1984 if (results.size() + nTotalPayloads != parts.Size()) {
1985 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"handle_data",
"inconsistent number of inputs extracted. %zu vs parts (%zu)", results.size() + nTotalPayloads, parts.Size());
1986 return std::nullopt;
1991 auto reportError = [
ref](
const char*
message) {
1996 auto handleValidMessages = [&info,
ref, &reportError](std::vector<InputInfo>
const& inputInfos) {
2000 auto& parts = info.
parts;
2003 bool hasBackpressure =
false;
2004 size_t minBackpressureTimeslice = -1;
2006 size_t oldestPossibleTimeslice = -1;
2007 static std::vector<int> ordering;
2009 ordering.resize(inputInfos.size());
2010 std::iota(ordering.begin(), ordering.end(), 0);
2012 std::stable_sort(ordering.begin(), ordering.end(), [&inputInfos](
int const&
a,
int const&
b) {
2013 auto const& ai = inputInfos[a];
2014 auto const& bi = inputInfos[b];
2015 if (ai.type != bi.type) {
2016 return ai.type < bi.type;
2018 return ai.position < bi.position;
2020 for (
size_t ii = 0; ii < inputInfos.size(); ++ii) {
2021 auto const& input = inputInfos[ordering[ii]];
2022 switch (input.type) {
2023 case InputType::Data: {
2025 auto headerIndex = input.position;
2027 auto nPayloadsPerHeader = 0;
2028 if (input.size > 2) {
2030 nMessages = input.size;
2031 nPayloadsPerHeader = nMessages - 1;
2034 auto dh = o2::header::get<DataHeader*>(parts.At(headerIndex)->GetData());
2035 nMessages = dh->splitPayloadParts > 0 ? dh->splitPayloadParts * 2 : 2;
2036 nPayloadsPerHeader = 1;
2037 ii += (nMessages / 2) - 1;
2041 O2_SIGNPOST_EVENT_EMIT(async_queue, cid,
"onDrop",
"Dropping message from slot %zu. Forwarding as needed. Timeslice %zu",
2042 slot.
index, oldestOutputInfo.timeslice.value);
2049 forwardInputs(
ref, slot, dropped, oldestOutputInfo,
false,
true);
2051 auto relayed = relayer.relay(parts.At(headerIndex)->GetData(),
2052 &parts.At(headerIndex),
2057 switch (relayed.type) {
2060 LOGP(alarm,
"Backpressure on channel {}. Waiting.", info.
channel->GetName());
2061 auto& monitoring =
ref.get<o2::monitoring::Monitoring>();
2062 monitoring.send(o2::monitoring::Metric{1, fmt::format(
"backpressure_{}", info.
channel->GetName())});
2066 policy.backpressure(info);
2067 hasBackpressure =
true;
2068 minBackpressureTimeslice = std::min<size_t>(minBackpressureTimeslice, relayed.timeslice.value);
2074 LOGP(info,
"Back to normal on channel {}.", info.
channel->GetName());
2075 auto& monitoring =
ref.get<o2::monitoring::Monitoring>();
2076 monitoring.send(o2::monitoring::Metric{0, fmt::format(
"backpressure_{}", info.
channel->GetName())});
2083 case InputType::SourceInfo: {
2084 LOGP(detail,
"Received SourceInfo");
2086 state.lastActiveDataProcessor = &context;
2087 auto headerIndex = input.position;
2088 auto payloadIndex = input.position + 1;
2089 assert(payloadIndex < parts.Size());
2092 parts.At(headerIndex).reset(
nullptr);
2093 parts.At(payloadIndex).reset(
nullptr);
2100 case InputType::DomainInfo: {
2104 state.lastActiveDataProcessor = &context;
2105 auto headerIndex = input.position;
2106 auto payloadIndex = input.position + 1;
2107 assert(payloadIndex < parts.Size());
2111 auto dih = o2::header::get<DomainInfoHeader*>(parts.At(headerIndex)->GetData());
2112 if (hasBackpressure && dih->oldestPossibleTimeslice >= minBackpressureTimeslice) {
2115 oldestPossibleTimeslice = std::min(oldestPossibleTimeslice, dih->oldestPossibleTimeslice);
2116 LOGP(
debug,
"Got DomainInfoHeader, new oldestPossibleTimeslice {} on channel {}", oldestPossibleTimeslice, info.
id.
value);
2117 parts.At(headerIndex).reset(
nullptr);
2118 parts.At(payloadIndex).reset(
nullptr);
2120 case InputType::Invalid: {
2121 reportError(
"Invalid part found.");
2127 if (oldestPossibleTimeslice != (
size_t)-1) {
2130 context.domainInfoUpdatedCallback(*context.registry, oldestPossibleTimeslice, info.
id);
2132 state.lastActiveDataProcessor = &context;
2134 auto it = std::remove_if(parts.fParts.begin(), parts.fParts.end(), [](
auto&
msg) ->
bool { return msg.get() == nullptr; });
2135 parts.fParts.erase(it, parts.end());
2136 if (parts.fParts.size()) {
2137 LOG(
debug) << parts.fParts.size() <<
" messages backpressured";
2149 auto inputTypes = getInputTypes();
2150 if (
bool(inputTypes) ==
false) {
2151 reportError(
"Parts should come in couples. Dropping it.");
2154 handleValidMessages(*inputTypes);
2160struct InputLatency {
2165auto calculateInputRecordLatency(
InputRecord const& record, uint64_t currentTime) -> InputLatency
2169 for (
auto& item : record) {
2170 auto* header = o2::header::get<DataProcessingHeader*>(item.header);
2171 if (header ==
nullptr) {
2174 int64_t partLatency = (0x7fffffffffffffff & currentTime) - (0x7fffffffffffffff & header->creation);
2175 if (partLatency < 0) {
2178 result.minLatency = std::min(
result.minLatency, (uint64_t)partLatency);
2179 result.maxLatency = std::max(
result.maxLatency, (uint64_t)partLatency);
2184auto calculateTotalInputRecordSize(
InputRecord const& record) ->
int
2186 size_t totalInputSize = 0;
2187 for (
auto& item : record) {
2188 auto* header = o2::header::get<DataHeader*>(item.header);
2189 if (header ==
nullptr) {
2192 totalInputSize += header->payloadSize;
2194 return totalInputSize;
2197template <
typename T>
2198void update_maximum(std::atomic<T>& maximum_value, T
const&
value)
noexcept
2200 T prev_value = maximum_value;
2201 while (prev_value <
value &&
2202 !maximum_value.compare_exchange_weak(prev_value,
value)) {
2210 LOGP(
debug,
"DataProcessingDevice::tryDispatchComputation");
2215 std::vector<MessageSet> currentSetOfInputs;
2218 auto getInputSpan = [
ref, ¤tSetOfInputs](
TimesliceSlot slot,
bool consume =
true) {
2223 currentSetOfInputs = relayer.consumeExistingInputsForTimeslice(slot);
2225 auto getter = [¤tSetOfInputs](
size_t i,
size_t partindex) ->
DataRef {
2226 if (currentSetOfInputs[
i].getNumberOfPairs() > partindex) {
2227 const char* headerptr =
nullptr;
2228 const char* payloadptr =
nullptr;
2229 size_t payloadSize = 0;
2235 auto const& headerMsg = currentSetOfInputs[
i].associatedHeader(partindex);
2236 auto const& payloadMsg = currentSetOfInputs[
i].associatedPayload(partindex);
2237 headerptr =
static_cast<char const*
>(headerMsg->GetData());
2238 payloadptr = payloadMsg ?
static_cast<char const*
>(payloadMsg->GetData()) :
nullptr;
2239 payloadSize = payloadMsg ? payloadMsg->GetSize() : 0;
2240 return DataRef{
nullptr, headerptr, payloadptr, payloadSize};
2244 auto nofPartsGetter = [¤tSetOfInputs](
size_t i) ->
size_t {
2245 return currentSetOfInputs[
i].getNumberOfPairs();
2247#if __has_include(<fairmq/shmem/Message.h>)
2248 auto refCountGetter = [¤tSetOfInputs](
size_t idx) ->
int {
2249 auto& header =
static_cast<const fair::mq::shmem::Message&
>(*currentSetOfInputs[idx].header(0));
2250 return header.GetRefCount();
2253 std::function<
int(
size_t)> refCountGetter =
nullptr;
2255 return InputSpan{getter, nofPartsGetter, refCountGetter, currentSetOfInputs.
size()};
2270 auto timeslice = relayer.getTimesliceForSlot(
i);
2272 timingInfo.timeslice = timeslice.value;
2282 auto timeslice = relayer.getTimesliceForSlot(
i);
2284 timingInfo.globalRunNumberChanged = !
TimingInfo::timesliceIsTimer(timeslice.value) && dataProcessorContext.lastRunNumberProcessed != timingInfo.runNumber;
2286 timingInfo.globalRunNumberChanged &= (dataProcessorContext.lastRunNumberProcessed == -1 || timingInfo.runNumber != 0);
2290 timingInfo.streamRunNumberChanged = timingInfo.globalRunNumberChanged;
2298 assert(record.size() == currentSetOfInputs.size());
2299 for (
size_t ii = 0, ie = record.size(); ii < ie; ++ii) {
2303 DataRef input = record.getByPos(ii);
2307 if (input.
header ==
nullptr) {
2311 currentSetOfInputs[ii].clear();
2322 for (
size_t pi = 0, pe = record.size(); pi < pe; ++pi) {
2323 DataRef input = record.getByPos(pi);
2324 if (input.
header ==
nullptr) {
2327 auto sih = o2::header::get<SourceInfoHeader*>(input.
header);
2332 auto dh = o2::header::get<DataHeader*>(input.
header);
2342 if (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) {
2345 pi += dh->splitPayloadParts - 1;
2347 size_t pi = pi + (dh->splitPayloadParts > 0 ? dh->splitPayloadParts : 1) * 2;
2353 if (completed.empty() ==
true) {
2354 LOGP(
debug,
"No computations available for dispatching.");
2361 std::atomic_thread_fence(std::memory_order_release);
2362 char relayerSlotState[1024];
2364 char*
buffer = relayerSlotState + written;
2365 for (
size_t ai = 0; ai != record.size(); ai++) {
2366 buffer[ai] = record.isValid(ai) ?
'3' :
'0';
2368 buffer[record.size()] = 0;
2370 .size = (
int)(record.size() +
buffer - relayerSlotState),
2371 .
data = relayerSlotState});
2372 uint64_t tEnd = uv_hrtime();
2374 int64_t wallTimeMs = (tEnd - tStart) / 1000000;
2382 auto latency = calculateInputRecordLatency(record, tStartMilli);
2385 static int count = 0;
2392 std::atomic_thread_fence(std::memory_order_release);
2393 char relayerSlotState[1024];
2395 char*
buffer = strchr(relayerSlotState,
' ') + 1;
2396 for (
size_t ai = 0; ai != record.size(); ai++) {
2397 buffer[ai] = record.isValid(ai) ?
'2' :
'0';
2399 buffer[record.size()] = 0;
2417 switch (spec.completionPolicy.order) {
2419 std::sort(completed.begin(), completed.end(), [](
auto const&
a,
auto const&
b) { return a.timeslice.value < b.timeslice.value; });
2422 std::sort(completed.begin(), completed.end(), [](
auto const&
a,
auto const&
b) { return a.slot.index < b.slot.index; });
2429 for (
auto action : completed) {
2431 O2_SIGNPOST_START(device, aid,
"device",
"Processing action on slot %lu for action %{public}s", action.
slot.
index, fmt::format(
"{}", action.
op).c_str());
2455 dpContext.preProcessingCallbacks(processContext);
2458 context.postDispatchingCallbacks(processContext);
2459 if (spec.forwards.empty() ==
false) {
2461 forwardInputs(
ref, action.
slot, currentSetOfInputs, timesliceIndex.getOldestPossibleOutput(),
false);
2462 O2_SIGNPOST_END(device, aid,
"device",
"Forwarding inputs consume: %d.",
false);
2470 bool hasForwards = spec.forwards.empty() ==
false;
2473 if (context.canForwardEarly && hasForwards && consumeSomething) {
2474 O2_SIGNPOST_EVENT_EMIT(device, aid,
"device",
"Early forwainding: %{public}s.", fmt::format(
"{}", action.
op).c_str());
2478 markInputsAsDone(action.
slot);
2480 uint64_t tStart = uv_hrtime();
2482 preUpdateStats(action, record, tStart);
2484 static bool noCatch = getenv(
"O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv(
"O2_NO_CATCHALL_EXCEPTIONS"),
"0");
2492 switch (action.
op) {
2503 if (
state.quitRequested ==
false) {
2507 streamContext.preProcessingCallbacks(processContext);
2513 if (context.statefulProcess && shouldProcess(action)) {
2517 (context.statefulProcess)(processContext);
2519 }
else if (context.statelessProcess && shouldProcess(action)) {
2521 (context.statelessProcess)(processContext);
2523 }
else if (context.statelessProcess || context.statefulProcess) {
2526 O2_SIGNPOST_EVENT_EMIT(device, pcid,
"device",
"No processing callback provided. Switching to %{public}s.",
"Idle");
2529 if (shouldProcess(action)) {
2531 if (timingInfo.globalRunNumberChanged) {
2532 context.lastRunNumberProcessed = timingInfo.runNumber;
2549 streamContext.finaliseOutputsCallbacks(processContext);
2555 streamContext.postProcessingCallbacks(processContext);
2561 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
2562 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
2568 (context.errorHandling)(e, record);
2573 }
catch (std::exception& ex) {
2578 (context.errorHandling)(e, record);
2580 (context.errorHandling)(e, record);
2583 if (
state.severityStack.empty() ==
false) {
2584 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
2585 state.severityStack.pop_back();
2588 postUpdateStats(action, record, tStart, tStartMilli);
2592 cleanupRecord(record);
2593 context.postDispatchingCallbacks(processContext);
2596 if ((context.canForwardEarly ==
false) && hasForwards && consumeSomething) {
2601 context.postForwardingCallbacks(processContext);
2603 cleanTimers(action.
slot, record);
2605 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());
2607 O2_SIGNPOST_END(device, sid,
"device",
"Start processing ready actions");
2611 LOGP(detail,
"Broadcasting end of stream");
2612 for (
auto& channel : spec.outputChannels) {
2635 cfg.getRecursive(
name);
2636 std::vector<std::unique_ptr<ParamRetriever>> retrievers;
2637 retrievers.emplace_back(std::make_unique<ConfigurationOptionsRetriever>(&cfg,
name));
2638 auto configStore = std::make_unique<ConfigParamStore>(options, std::move(retrievers));
2639 configStore->preload();
2640 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_WARN(log, id, name, format,...)
#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.
virtual fair::mq::Device * device()=0
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