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#include <Configuration/ConfigurationInterface.h>
61#include <Configuration/ConfigurationFactory.h>
62#include <Monitoring/Monitoring.h>
64#include <TClonesArray.h>
66#include <fmt/ostream.h>
74#include <boost/property_tree/json_parser.hpp>
119 return std::all_of(spec.
inputs.cbegin(), spec.
inputs.cend(), [](
InputRoute const& route) ->
bool { return route.matcher.lifetime == Lifetime::Timer; });
124 return (spec.
inputChannels.size() == 1) && (spec.
inputs[0].matcher.lifetime == Lifetime::Timer || spec.
inputs[0].matcher.lifetime == Lifetime::Enumeration);
156 O2_SIGNPOST_EVENT_EMIT_INFO(calibration, cid,
"callback",
"Grace period for data processing expired. Only calibrations from this point onwards.");
169 return devices[running.
index];
179 : mRunningDevice{running},
180 mConfigRegistry{nullptr},
181 mServiceRegistry{registry},
182 mProcessingPolicies{policies}
184 GetConfig()->Subscribe<std::string>(
"dpl", [®istry = mServiceRegistry](
const std::string&
key, std::string
value) {
185 if (
key ==
"cleanup") {
189 int64_t newCleanupCount = std::stoll(
value);
190 if (newCleanupCount <= cleanupCount) {
193 deviceState.cleanupCount.store(newCleanupCount);
194 for (
auto& info : deviceState.inputChannelInfos) {
195 fair::mq::Parts parts;
196 while (info.channel->Receive(parts, 0)) {
197 LOGP(
debug,
"Dropping {} parts", parts.Size());
198 if (parts.Size() == 0) {
206 std::function<
void(
const fair::mq::State)> stateWatcher = [
this, ®istry = mServiceRegistry](
const fair::mq::State
state) ->
void {
211 control.notifyDeviceState(fair::mq::GetStateName(
state));
214 if (deviceState.nextFairMQState.empty() ==
false) {
215 auto state = deviceState.nextFairMQState.back();
217 deviceState.nextFairMQState.pop_back();
222 this->SubscribeToStateChange(
"99-dpl", stateWatcher);
233 mAwakeHandle->data = &
state;
235 LOG(
error) <<
"Unable to initialise subscription";
239 SubscribeToNewTransition(
"dpl", [wakeHandle = mAwakeHandle](fair::mq::Transition t) {
240 int res = uv_async_send(wakeHandle);
242 LOG(
error) <<
"Unable to notify subscription";
244 LOG(
debug) <<
"State transition requested";
258 O2_SIGNPOST_START(device, sid,
"run_callback",
"Starting run callback on stream %d", task->id.index);
261 O2_SIGNPOST_END(device, sid,
"run_callback",
"Done processing data for stream %d", task->id.index);
274 using o2::monitoring::Metric;
275 using o2::monitoring::Monitoring;
276 using o2::monitoring::tags::Key;
277 using o2::monitoring::tags::Value;
281 stats.totalConsumedBytes += accumulatedConsumed.
sharedMemory;
284 dpStats.processCommandQueue();
292 dpStats.processCommandQueue();
295 for (
auto& consumer :
state.offerConsumers) {
296 quotaEvaluator.consume(task->id.index, consumer, reportConsumedOffer);
298 state.offerConsumers.clear();
299 quotaEvaluator.handleExpired(reportExpiredOffer);
300 quotaEvaluator.dispose(task->id.index);
301 task->running =
false;
329 O2_SIGNPOST_EVENT_EMIT(device, sid,
"socket_state",
"Data pending on socket for channel %{public}s", context->name);
333 O2_SIGNPOST_END(device, sid,
"socket_state",
"Socket connected for channel %{public}s", context->name);
335 O2_SIGNPOST_START(device, sid,
"socket_state",
"Socket connected for read in context %{public}s", context->name);
336 uv_poll_start(poller, UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED, &
on_socket_polled);
339 O2_SIGNPOST_START(device, sid,
"socket_state",
"Socket connected for write for channel %{public}s", context->name);
347 case UV_DISCONNECT: {
348 O2_SIGNPOST_END(device, sid,
"socket_state",
"Socket disconnected in context %{public}s", context->name);
350 case UV_PRIORITIZED: {
351 O2_SIGNPOST_EVENT_EMIT(device, sid,
"socket_state",
"Socket prioritized for context %{public}s", context->name);
363 LOGP(fatal,
"Error while polling {}: {}", context->name, status);
368 O2_SIGNPOST_EVENT_EMIT(device, sid,
"socket_state",
"Data pending on socket for channel %{public}s", context->name);
370 assert(context->channelInfo);
371 context->channelInfo->readPolled =
true;
374 O2_SIGNPOST_END(device, sid,
"socket_state",
"OOB socket connected for channel %{public}s", context->name);
376 O2_SIGNPOST_START(device, sid,
"socket_state",
"OOB socket connected for read in context %{public}s", context->name);
379 O2_SIGNPOST_START(device, sid,
"socket_state",
"OOB socket connected for write for channel %{public}s", context->name);
383 case UV_DISCONNECT: {
384 O2_SIGNPOST_END(device, sid,
"socket_state",
"OOB socket disconnected in context %{public}s", context->name);
387 case UV_PRIORITIZED: {
388 O2_SIGNPOST_EVENT_EMIT(device, sid,
"socket_state",
"OOB socket prioritized for context %{public}s", context->name);
409 context.statelessProcess = spec.algorithm.onProcess;
411 context.error = spec.algorithm.onError;
412 context.
initError = spec.algorithm.onInitError;
415 if (configStore ==
nullptr) {
416 std::vector<std::unique_ptr<ParamRetriever>> retrievers;
417 retrievers.emplace_back(std::make_unique<FairOptionsRetriever>(GetConfig()));
418 configStore = std::make_unique<ConfigParamStore>(spec.options, std::move(retrievers));
419 configStore->preload();
420 configStore->activate();
423 using boost::property_tree::ptree;
426 for (
auto&
entry : configStore->store()) {
427 std::stringstream ss;
429 if (
entry.second.empty() ==
false) {
430 boost::property_tree::json_parser::write_json(ss,
entry.second,
false);
434 str =
entry.second.get_value<std::string>();
436 std::string configString = fmt::format(
"[CONFIG] {}={} 1 {}",
entry.first,
str, configStore->provenance(
entry.first.c_str())).c_str();
440 mConfigRegistry = std::make_unique<ConfigParamRegistry>(std::move(configStore));
443 if (context.initError) {
444 context.initErrorHandling = [&errorCallback = context.initError,
457 errorCallback(errorContext);
460 context.initErrorHandling = [&serviceRegistry = mServiceRegistry](
RuntimeErrorRef e) {
475 context.expirationHandlers.clear();
476 context.init = spec.algorithm.onInit;
478 static bool noCatch = getenv(
"O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv(
"O2_NO_CATCHALL_EXCEPTIONS"),
"0");
479 InitContext initContext{*mConfigRegistry, mServiceRegistry};
483 context.statefulProcess = context.init(initContext);
485 if (context.initErrorHandling) {
486 (context.initErrorHandling)(e);
491 context.statefulProcess = context.init(initContext);
492 }
catch (std::exception& ex) {
497 (context.initErrorHandling)(e);
499 (context.initErrorHandling)(e);
504 state.inputChannelInfos.resize(spec.inputChannels.size());
508 int validChannelId = 0;
509 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
510 auto&
name = spec.inputChannels[ci].name;
511 if (
name.find(spec.channelPrefix +
"from_internal-dpl-clock") == 0) {
516 state.inputChannelInfos[ci].id = {validChannelId++};
521 if (spec.callbacksPolicy.policy !=
nullptr) {
522 InitContext initContext{*mConfigRegistry, mServiceRegistry};
527 auto* options = GetConfig();
528 for (
size_t si = 0; si < mStreams.size(); ++si) {
542 O2_SIGNPOST_END(device, sid,
"signal_state",
"No registry active. Ignoring signal.");
551 while (ri != quotaEvaluator.mOffers.size()) {
552 auto& offer = quotaEvaluator.mOffers[ri];
558 if (offer.valid && offer.sharedMemory != 0) {
559 O2_SIGNPOST_END(device, sid,
"signal_state",
"Memory already offered.");
565 for (
auto& offer : quotaEvaluator.mOffers) {
566 if (offer.valid ==
false) {
569 offer.sharedMemory = 1000000000;
576 O2_SIGNPOST_END(device, sid,
"signal_state",
"Done processing signals.");
579static auto toBeForwardedHeader = [](
void* header) ->
bool {
584 if (header ==
nullptr) {
587 auto sih = o2::header::get<SourceInfoHeader*>(header);
592 auto dih = o2::header::get<DomainInfoHeader*>(header);
597 auto dh = o2::header::get<DataHeader*>(header);
601 auto dph = o2::header::get<DataProcessingHeader*>(header);
608static auto toBeforwardedMessageSet = [](std::vector<ChannelIndex>& cachedForwardingChoices,
610 std::unique_ptr<fair::mq::Message>& header,
611 std::unique_ptr<fair::mq::Message>& payload,
614 if (header.get() ==
nullptr) {
621 if (payload.get() ==
nullptr && consume ==
true) {
625 header.reset(
nullptr);
629 auto fdph = o2::header::get<DataProcessingHeader*>(header->GetData());
630 if (fdph ==
nullptr) {
631 LOG(error) <<
"Data is missing DataProcessingHeader";
634 auto fdh = o2::header::get<DataHeader*>(header->GetData());
635 if (fdh ==
nullptr) {
636 LOG(error) <<
"Data is missing DataHeader";
643 if (fdh->splitPayloadIndex == 0 || fdh->splitPayloadParts <= 1 || total > 1) {
644 proxy.getMatchingForwardChannelIndexes(cachedForwardingChoices, *fdh, fdph->startTime);
646 return cachedForwardingChoices.empty() ==
false;
660 if (oldestTimeslice.timeslice.value <= decongestion.lastTimeslice) {
661 LOG(
debug) <<
"Not sending already sent oldest possible timeslice " << oldestTimeslice.timeslice.value;
664 for (
int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
665 auto& info = proxy.getForwardChannelInfo(
ChannelIndex{fi});
670 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputsCallback",
"Skipping channel %{public}s because it's not a DPL channel",
676 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputsCallback",
"Forwarding to channel %{public}s oldest possible timeslice %zu, prio 20",
677 info.name.c_str(), oldestTimeslice.timeslice.value);
690 std::vector<fair::mq::Parts> forwardedParts;
691 forwardedParts.resize(proxy.getNumForwards());
692 std::vector<ChannelIndex> cachedForwardingChoices{};
694 O2_SIGNPOST_START(forwarding, sid,
"forwardInputs",
"Starting forwarding for slot %zu with oldestTimeslice %zu %{public}s%{public}s%{public}s",
695 slot.index, oldestTimeslice.timeslice.value, copy ?
"with copy" :
"", copy && consume ?
" and " :
"", consume ?
"with consume" :
"");
697 for (
size_t ii = 0, ie = currentSetOfInputs.size(); ii < ie; ++ii) {
698 auto& messageSet = currentSetOfInputs[ii];
700 if (messageSet.size() == 0) {
703 if (!toBeForwardedHeader(messageSet.header(0)->GetData())) {
706 cachedForwardingChoices.clear();
708 for (
size_t pi = 0; pi < currentSetOfInputs[ii].size(); ++pi) {
709 auto& messageSet = currentSetOfInputs[ii];
710 auto& header = messageSet.header(pi);
711 auto& payload = messageSet.payload(pi);
712 auto total = messageSet.getNumberOfPayloads(pi);
714 if (!toBeforwardedMessageSet(cachedForwardingChoices, proxy, header, payload, total, consume)) {
720 if (cachedForwardingChoices.size() > 1) {
723 auto* dh = o2::header::get<DataHeader*>(header->GetData());
724 auto* dph = o2::header::get<DataProcessingHeader*>(header->GetData());
727 for (
auto& cachedForwardingChoice : cachedForwardingChoices) {
728 auto&& newHeader = header->GetTransport()->CreateMessage();
730 fmt::format(
"{}/{}/{}@timeslice:{} tfCounter:{}", dh->dataOrigin, dh->dataDescription, dh->subSpecification, dph->startTime, dh->tfCounter).c_str(), cachedForwardingChoice.value);
731 newHeader->Copy(*header);
732 forwardedParts[cachedForwardingChoice.value].AddPart(std::move(newHeader));
734 for (
size_t payloadIndex = 0; payloadIndex < messageSet.getNumberOfPayloads(pi); ++payloadIndex) {
735 auto&& newPayload = header->GetTransport()->CreateMessage();
736 newPayload->Copy(*messageSet.payload(pi, payloadIndex));
737 forwardedParts[cachedForwardingChoice.value].AddPart(std::move(newPayload));
742 fmt::format(
"{}/{}/{}@timeslice:{} tfCounter:{}", dh->dataOrigin, dh->dataDescription, dh->subSpecification, dph->startTime, dh->tfCounter).c_str(), cachedForwardingChoices.back().value);
743 forwardedParts[cachedForwardingChoices.back().value].AddPart(std::move(messageSet.header(pi)));
744 for (
size_t payloadIndex = 0; payloadIndex < messageSet.getNumberOfPayloads(pi); ++payloadIndex) {
745 forwardedParts[cachedForwardingChoices.back().value].AddPart(std::move(messageSet.payload(pi, payloadIndex)));
750 O2_SIGNPOST_EVENT_EMIT(forwarding, sid,
"forwardInputs",
"Forwarding %zu messages", forwardedParts.size());
751 for (
int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
752 if (forwardedParts[fi].
Size() == 0) {
756 auto& parts = forwardedParts[fi];
757 if (info.
policy ==
nullptr) {
768 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputs",
"Queuing forwarding oldestPossible %zu", oldestTimeslice.timeslice.value);
780 if (infos.empty() ==
false) {
781 std::vector<fair::mq::RegionInfo> toBeNotified;
782 toBeNotified.swap(infos);
783 static bool dummyRead = getenv(
"DPL_DEBUG_MAP_ALL_SHM_REGIONS") && atoi(getenv(
"DPL_DEBUG_MAP_ALL_SHM_REGIONS"));
784 for (
auto const& info : toBeNotified) {
804void DataProcessingDevice::initPollers()
812 if ((context.statefulProcess !=
nullptr) || (context.statelessProcess !=
nullptr)) {
813 for (
auto& [channelName, channel] : GetChannels()) {
815 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
816 auto& channelSpec = spec.inputChannels[ci];
817 channelInfo = &
state.inputChannelInfos[ci];
818 if (channelSpec.name != channelName) {
821 channelInfo->
channel = &this->GetChannel(channelName, 0);
824 if ((
channelName.rfind(
"from_internal-dpl", 0) == 0) &&
825 (
channelName.rfind(
"from_internal-dpl-aod", 0) != 0) &&
826 (
channelName.rfind(
"from_internal-dpl-ccdb-backend", 0) != 0) &&
827 (
channelName.rfind(
"from_internal-dpl-injected", 0)) != 0) {
828 LOGP(detail,
"{} is an internal channel. Skipping as no input will come from there.", channelName);
832 if (
channelName.rfind(
"from_" + spec.name +
"_", 0) == 0) {
833 LOGP(detail,
"{} is to send data. Not polling.", channelName);
838 LOGP(detail,
"{} is not a DPL socket. Not polling.", channelName);
844 size_t zmq_fd_len =
sizeof(zmq_fd);
847 channel[0].GetSocket().GetOption(
"fd", &zmq_fd, &zmq_fd_len);
852 LOGP(detail,
"Polling socket for {}", channelName);
855 pCtx->loop =
state.loop;
857 pCtx->state = &
state;
859 assert(channelInfo !=
nullptr);
860 pCtx->channelInfo = channelInfo;
861 pCtx->socket = &channel[0].GetSocket();
864 uv_poll_init(
state.loop, poller, zmq_fd);
866 LOGP(detail,
"{} is an out of band channel.", channelName);
867 state.activeOutOfBandPollers.push_back(poller);
870 state.activeInputPollers.push_back(poller);
876 if (
state.activeInputPollers.empty() &&
877 state.activeOutOfBandPollers.empty() &&
878 state.activeTimers.empty() &&
879 state.activeSignals.empty()) {
883 if (
state.inputChannelInfos.empty()) {
884 LOGP(detail,
"No input channels. Setting exit transition timeout to 0.");
885 deviceContext.exitTransitionTimeout = 0;
887 for (
auto& [channelName, channel] : GetChannels()) {
888 if (
channelName.rfind(spec.channelPrefix +
"from_internal-dpl", 0) == 0) {
889 LOGP(detail,
"{} is an internal channel. Not polling.", channelName);
892 if (
channelName.rfind(spec.channelPrefix +
"from_" + spec.name +
"_", 0) == 0) {
893 LOGP(detail,
"{} is an out of band channel. Not polling for output.", channelName);
898 size_t zmq_fd_len =
sizeof(zmq_fd);
901 channel[0].GetSocket().GetOption(
"fd", &zmq_fd, &zmq_fd_len);
903 LOGP(
error,
"Cannot get file descriptor for channel {}", channelName);
906 LOG(detail) <<
"Polling socket for " << channel[0].GetName();
910 pCtx->loop =
state.loop;
912 pCtx->state = &
state;
916 uv_poll_init(
state.loop, poller, zmq_fd);
917 state.activeOutputPollers.push_back(poller);
921 LOGP(detail,
"This is a fake device so we exit after the first iteration.");
922 deviceContext.exitTransitionTimeout = 0;
928 uv_timer_init(
state.loop, timer);
929 timer->data = &
state;
930 uv_update_time(
state.loop);
932 state.activeTimers.push_back(timer);
936void DataProcessingDevice::startPollers()
942 for (
auto* poller :
state.activeInputPollers) {
944 O2_SIGNPOST_START(device, sid,
"socket_state",
"Input socket waiting for connection.");
948 for (
auto& poller :
state.activeOutOfBandPollers) {
952 for (
auto* poller :
state.activeOutputPollers) {
954 O2_SIGNPOST_START(device, sid,
"socket_state",
"Output socket waiting for connection.");
961 uv_timer_init(
state.loop, deviceContext.gracePeriodTimer);
964 deviceContext.dataProcessingGracePeriodTimer->data =
new ServiceRegistryRef(mServiceRegistry);
965 uv_timer_init(
state.loop, deviceContext.dataProcessingGracePeriodTimer);
968void DataProcessingDevice::stopPollers()
973 LOGP(detail,
"Stopping {} input pollers",
state.activeInputPollers.size());
974 for (
auto* poller :
state.activeInputPollers) {
977 uv_poll_stop(poller);
980 LOGP(detail,
"Stopping {} out of band pollers",
state.activeOutOfBandPollers.size());
981 for (
auto* poller :
state.activeOutOfBandPollers) {
982 uv_poll_stop(poller);
985 LOGP(detail,
"Stopping {} output pollers",
state.activeOutOfBandPollers.size());
986 for (
auto* poller :
state.activeOutputPollers) {
989 uv_poll_stop(poller);
993 uv_timer_stop(deviceContext.gracePeriodTimer);
995 free(deviceContext.gracePeriodTimer);
996 deviceContext.gracePeriodTimer =
nullptr;
998 uv_timer_stop(deviceContext.dataProcessingGracePeriodTimer);
1000 free(deviceContext.dataProcessingGracePeriodTimer);
1001 deviceContext.dataProcessingGracePeriodTimer =
nullptr;
1016 for (
auto&
di : distinct) {
1017 auto& route = spec.inputs[
di];
1018 if (route.configurator.has_value() ==
false) {
1023 .
name = route.configurator->name,
1025 .lifetime = route.matcher.lifetime,
1026 .creator = route.configurator->creatorConfigurator(
state, mServiceRegistry, *mConfigRegistry),
1027 .checker = route.configurator->danglingConfigurator(
state, *mConfigRegistry),
1028 .handler = route.configurator->expirationConfigurator(
state, *mConfigRegistry)};
1029 context.expirationHandlers.emplace_back(std::move(handler));
1032 if (
state.awakeMainThread ==
nullptr) {
1038 deviceContext.expectedRegionCallbacks = std::stoi(fConfig->GetValue<std::string>(
"expected-region-callbacks"));
1039 deviceContext.exitTransitionTimeout = std::stoi(fConfig->GetValue<std::string>(
"exit-transition-timeout"));
1040 deviceContext.dataProcessingTimeout = std::stoi(fConfig->GetValue<std::string>(
"data-processing-timeout"));
1042 for (
auto& channel : GetChannels()) {
1043 channel.second.at(0).Transport()->SubscribeToRegionEvents([&context = deviceContext,
1044 ®istry = mServiceRegistry,
1045 &pendingRegionInfos = mPendingRegionInfos,
1046 ®ionInfoMutex = mRegionInfoMutex](fair::mq::RegionInfo info) {
1047 std::lock_guard<std::mutex> lock(regionInfoMutex);
1048 LOG(detail) <<
">>> Region info event" << info.event;
1049 LOG(detail) <<
"id: " << info.id;
1050 LOG(detail) <<
"ptr: " << info.ptr;
1051 LOG(detail) <<
"size: " << info.size;
1052 LOG(detail) <<
"flags: " << info.flags;
1055 pendingRegionInfos.push_back(info);
1068 if (deviceContext.sigusr1Handle ==
nullptr) {
1070 deviceContext.sigusr1Handle->data = &mServiceRegistry;
1071 uv_signal_init(
state.loop, deviceContext.sigusr1Handle);
1075 for (
auto& handle :
state.activeSignals) {
1076 handle->data = &
state;
1079 deviceContext.sigusr1Handle->data = &mServiceRegistry;
1082 DataProcessingDevice::initPollers();
1090 LOG(
error) <<
"DataProcessor " <<
state.lastActiveDataProcessor.load()->spec->name <<
" was unexpectedly active";
1102 O2_SIGNPOST_END(device, cid,
"InitTask",
"Exiting InitTask callback waiting for the remaining region callbacks.");
1104 auto hasPendingEvents = [&mutex = mRegionInfoMutex, &pendingRegionInfos = mPendingRegionInfos](
DeviceContext& deviceContext) {
1105 std::lock_guard<std::mutex> lock(mutex);
1106 return (pendingRegionInfos.empty() ==
false) || deviceContext.expectedRegionCallbacks > 0;
1113 while (hasPendingEvents(deviceContext)) {
1115 uv_run(
state.loop, UV_RUN_ONCE);
1119 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1123 O2_SIGNPOST_END(device, cid,
"InitTask",
"Done waiting for registration events.");
1130 bool enableRateLimiting = std::stoi(fConfig->GetValue<std::string>(
"timeframes-rate-limit"));
1139 if (enableRateLimiting ==
false && spec.name.find(
"internal-dpl-injected-dummy-sink") != std::string::npos) {
1142 if (enableRateLimiting) {
1143 for (
auto& spec : spec.outputs) {
1144 if (spec.matcher.binding.value ==
"dpl-summary") {
1151 context.
registry = &mServiceRegistry;
1154 if (context.
error !=
nullptr) {
1168 errorCallback(errorContext);
1182 switch (errorPolicy) {
1193 auto decideEarlyForward = [&context, &spec,
this]() ->
bool {
1197 bool onlyConditions =
true;
1198 bool overriddenEarlyForward =
false;
1199 for (
auto& forwarded : spec.forwards) {
1200 if (forwarded.matcher.lifetime != Lifetime::Condition) {
1201 onlyConditions =
false;
1205 overriddenEarlyForward =
true;
1211 overriddenEarlyForward =
true;
1215 if (forwarded.matcher.lifetime == Lifetime::Optional) {
1217 overriddenEarlyForward =
true;
1222 if (!overriddenEarlyForward && onlyConditions) {
1224 LOG(detail) <<
"Enabling early forwarding because only conditions to be forwarded";
1226 return canForwardEarly;
1238 state.quitRequested =
false;
1241 for (
auto& info :
state.inputChannelInfos) {
1253 for (
size_t i = 0;
i < mStreams.size(); ++
i) {
1256 context.preStartStreamCallbacks(streamRef);
1258 }
catch (std::exception& e) {
1259 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"PreRun",
"Exception of type std::exception caught in PreRun: %{public}s. Rethrowing.", e.what());
1260 O2_SIGNPOST_END(device, cid,
"PreRun",
"Exiting PreRun due to exception thrown.");
1264 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"PreRun",
"Exception of type o2::framework::RuntimeErrorRef caught in PreRun: %{public}s. Rethrowing.", err.what);
1265 O2_SIGNPOST_END(device, cid,
"PreRun",
"Exiting PreRun due to exception thrown.");
1268 O2_SIGNPOST_END(device, cid,
"PreRun",
"Unknown exception being thrown. Rethrowing.");
1276 using o2::monitoring::Metric;
1277 using o2::monitoring::Monitoring;
1278 using o2::monitoring::tags::Key;
1279 using o2::monitoring::tags::Value;
1282 monitoring.send(
Metric{(uint64_t)1,
"device_state"}.addTag(Key::Subsystem, Value::DPL));
1290 using o2::monitoring::Metric;
1291 using o2::monitoring::Monitoring;
1292 using o2::monitoring::tags::Key;
1293 using o2::monitoring::tags::Value;
1296 monitoring.send(
Metric{(uint64_t)0,
"device_state"}.addTag(Key::Subsystem, Value::DPL));
1315 bool firstLoop =
true;
1317 O2_SIGNPOST_START(device, lid,
"device_state",
"First iteration of the device loop");
1319 bool dplEnableMultithreding = getenv(
"DPL_THREADPOOL_SIZE") !=
nullptr;
1320 if (dplEnableMultithreding) {
1321 setenv(
"UV_THREADPOOL_SIZE",
"1", 1);
1325 if (
state.nextFairMQState.empty() ==
false) {
1326 (
void)this->ChangeState(
state.nextFairMQState.back());
1327 state.nextFairMQState.pop_back();
1332 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1345 state.lastActiveDataProcessor.compare_exchange_strong(lastActive,
nullptr);
1347 auto shouldNotWait = (lastActive !=
nullptr &&
1351 shouldNotWait =
true;
1354 if (lastActive !=
nullptr) {
1357 if (NewStatePending()) {
1359 shouldNotWait =
true;
1375 deviceContext.exitTransitionTimeout = deviceContext.dataProcessingTimeout;
1379 if (deviceContext.dataProcessingTimeout > 0 && deviceContext.dataProcessingTimeout < deviceContext.exitTransitionTimeout) {
1380 uv_update_time(
state.loop);
1381 O2_SIGNPOST_EVENT_EMIT(calibration, lid,
"timer_setup",
"Starting %d s timer for dataProcessingTimeout.", deviceContext.dataProcessingTimeout);
1382 uv_timer_start(deviceContext.dataProcessingGracePeriodTimer,
on_data_processing_expired, deviceContext.dataProcessingTimeout * 1000, 0);
1387 uv_update_time(
state.loop);
1388 O2_SIGNPOST_EVENT_EMIT(calibration, lid,
"timer_setup",
"Starting %d s timer for exitTransitionTimeout.", deviceContext.exitTransitionTimeout);
1391 O2_SIGNPOST_EVENT_EMIT_INFO(device, lid,
"run_loop",
"New state requested. Waiting for %d seconds before quitting.", (
int)deviceContext.exitTransitionTimeout);
1393 O2_SIGNPOST_EVENT_EMIT_INFO(device, lid,
"run_loop",
"New state requested. Waiting for %d seconds before switching to READY state.", (
int)deviceContext.exitTransitionTimeout);
1398 O2_SIGNPOST_EVENT_EMIT_INFO(device, lid,
"run_loop",
"New state requested. No timeout set, quitting immediately as per --completion-policy");
1400 O2_SIGNPOST_EVENT_EMIT_INFO(device, lid,
"run_loop",
"New state requested. No timeout set, switching to READY state immediately");
1402 O2_SIGNPOST_EVENT_EMIT_INFO(device, lid,
"run_loop",
"New state pending and we are already idle, quitting immediately as per --completion-policy");
1404 O2_SIGNPOST_EVENT_EMIT_INFO(device, lid,
"run_loop",
"New state pending and we are already idle, switching to READY immediately.");
1410 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"State transition requested and we are now in Idle. We can consider it to be completed.");
1413 if (
state.severityStack.empty() ==
false) {
1414 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
1415 state.severityStack.pop_back();
1421 state.firedTimers.clear();
1423 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
1424 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
1431 O2_SIGNPOST_START(device, lid,
"run_loop",
"Dropping message from slot %" PRIu64
". Forwarding as needed.", (uint64_t)slot.index);
1439 forwardInputs(registry, slot, dropped, oldestOutputInfo,
false,
true);
1444 auto oldestPossibleTimeslice = relayer.getOldestPossibleOutput();
1446 if (shouldNotWait ==
false) {
1450 O2_SIGNPOST_END(device, lid,
"run_loop",
"Run loop completed. %{}s", shouldNotWait ?
"Will immediately schedule a new one" :
"Waiting for next event.");
1451 uv_run(
state.loop, shouldNotWait ? UV_RUN_NOWAIT : UV_RUN_ONCE);
1453 if ((
state.loopReason &
state.tracingFlags) != 0) {
1454 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
1455 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
1456 }
else if (
state.severityStack.empty() ==
false) {
1457 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
1458 state.severityStack.pop_back();
1463 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"Out of band activity detected. Rescanning everything.");
1467 if (!
state.pendingOffers.empty()) {
1468 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"Pending %" PRIu64
" offers. updating the ComputingQuotaEvaluator.", (uint64_t)
state.pendingOffers.size());
1480 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1484 assert(mStreams.size() == mHandles.size());
1487 for (
size_t ti = 0; ti < mStreams.size(); ti++) {
1488 auto& taskInfo = mStreams[ti];
1489 if (taskInfo.running) {
1493 streamRef.index = ti;
1495 using o2::monitoring::Metric;
1496 using o2::monitoring::Monitoring;
1497 using o2::monitoring::tags::Key;
1498 using o2::monitoring::tags::Value;
1501 if (streamRef.index != -1) {
1504 uv_work_t& handle = mHandles[streamRef.index];
1506 handle.data = &mStreams[streamRef.index];
1513 dpStats.processCommandQueue();
1526 stream.registry = &mServiceRegistry;
1527 if (dplEnableMultithreding) [[unlikely]] {
1541 O2_SIGNPOST_END(device, lid,
"run_loop",
"Run loop completed. Transition handling state %d.",
state.transitionHandling);
1544 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
1545 auto& info =
state.inputChannelInfos[ci];
1546 info.parts.fParts.clear();
1557 O2_SIGNPOST_START(device, dpid,
"do_prepare",
"Starting DataProcessorContext::doPrepare.");
1575 context.allDone = std::any_of(
state.inputChannelInfos.begin(),
state.inputChannelInfos.end(), [cid](
const auto& info) {
1577 O2_SIGNPOST_EVENT_EMIT(device, cid,
"do_prepare",
"Input channel %{public}s%{public}s has %zu parts left and is in state %d.",
1578 info.channel->GetName().c_str(), (info.id.value == ChannelIndex::INVALID ?
" (non DPL)" :
""), info.parts.fParts.size(), (int)info.state);
1580 O2_SIGNPOST_EVENT_EMIT(device, cid,
"do_prepare",
"External channel %d is in state %d.", info.id.value, (int)info.state);
1585 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"do_prepare",
"Processing %zu input channels.", spec.inputChannels.size());
1588 static std::vector<int> pollOrder;
1589 pollOrder.resize(
state.inputChannelInfos.size());
1590 std::iota(pollOrder.begin(), pollOrder.end(), 0);
1591 std::sort(pollOrder.begin(), pollOrder.end(), [&infos =
state.inputChannelInfos](
int a,
int b) {
1592 return infos[a].oldestForChannel.value < infos[b].oldestForChannel.value;
1596 if (pollOrder.empty()) {
1597 O2_SIGNPOST_END(device, dpid,
"do_prepare",
"Nothing to poll. Waiting for next iteration.");
1600 auto currentOldest =
state.inputChannelInfos[pollOrder.front()].oldestForChannel;
1601 auto currentNewest =
state.inputChannelInfos[pollOrder.back()].oldestForChannel;
1602 auto delta = currentNewest.value - currentOldest.value;
1603 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"do_prepare",
"Oldest possible timeframe range %" PRIu64
" => %" PRIu64
" delta %" PRIu64,
1604 (int64_t)currentOldest.value, (int64_t)currentNewest.value, (int64_t)delta);
1605 auto& infos =
state.inputChannelInfos;
1607 if (context.balancingInputs) {
1609 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));
1610 auto newEnd = std::remove_if(pollOrder.begin(), pollOrder.end(), [&infos, limitNew = currentOldest.value + ahead](
int a) ->
bool {
1611 return infos[a].oldestForChannel.value > limitNew;
1613 for (
auto it = pollOrder.begin(); it < pollOrder.end(); it++) {
1614 const auto& channelInfo =
state.inputChannelInfos[*it];
1620 bool shouldBeRunning = it < newEnd;
1621 if (running != shouldBeRunning) {
1622 uv_poll_start(poller, shouldBeRunning ? UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED : 0, &
on_socket_polled);
1628 pollOrder.erase(newEnd, pollOrder.end());
1630 O2_SIGNPOST_END(device, dpid,
"do_prepare",
"%zu channels pass the channel inbalance balance check.", pollOrder.size());
1632 for (
auto sci : pollOrder) {
1633 auto& info =
state.inputChannelInfos[sci];
1634 auto& channelSpec = spec.inputChannels[sci];
1636 O2_SIGNPOST_START(device, cid,
"channels",
"Processing channel %s", channelSpec.name.c_str());
1639 context.allDone =
false;
1644 if (info.parts.Size()) {
1647 O2_SIGNPOST_END(device, cid,
"channels",
"Flushing channel %s which is in state %d and has %zu parts still pending.",
1648 channelSpec.name.c_str(), (
int)info.state, info.parts.Size());
1651 if (info.
channel ==
nullptr) {
1652 O2_SIGNPOST_END(device, cid,
"channels",
"Channel %s which is in state %d is nullptr and has %zu parts still pending.",
1653 channelSpec.name.c_str(), (
int)info.state, info.parts.Size());
1658 O2_SIGNPOST_END(device, cid,
"channels",
"Channel %s which is in state %d is not a DPL channel and has %zu parts still pending.",
1659 channelSpec.name.c_str(), (
int)info.state, info.parts.Size());
1662 auto& socket = info.
channel->GetSocket();
1667 if (info.hasPendingEvents == 0) {
1668 socket.Events(&info.hasPendingEvents);
1670 if ((info.hasPendingEvents & 1) == 0 && (info.parts.Size() == 0)) {
1671 O2_SIGNPOST_END(device, cid,
"channels",
"No pending events and no remaining parts to process for channel %{public}s", channelSpec.name.c_str());
1677 info.readPolled =
false;
1686 bool newMessages =
false;
1688 O2_SIGNPOST_EVENT_EMIT(device, cid,
"channels",
"Receiving loop called for channel %{public}s (%d) with oldest possible timeslice %zu",
1689 channelSpec.name.c_str(), info.id.value, info.oldestForChannel.value);
1690 if (info.parts.Size() < 64) {
1691 fair::mq::Parts parts;
1692 info.
channel->Receive(parts, 0);
1694 O2_SIGNPOST_EVENT_EMIT(device, cid,
"channels",
"Received %zu parts from channel %{public}s (%d).", parts.Size(), channelSpec.name.c_str(), info.id.value);
1696 for (
auto&& part : parts) {
1697 info.parts.fParts.emplace_back(std::move(part));
1699 newMessages |=
true;
1702 if (info.parts.Size() >= 0) {
1714 socket.Events(&info.hasPendingEvents);
1715 if (info.hasPendingEvents) {
1716 info.readPolled =
false;
1719 state.lastActiveDataProcessor.store(&context);
1722 O2_SIGNPOST_END(device, cid,
"channels",
"Done processing channel %{public}s (%d).",
1723 channelSpec.name.c_str(), info.id.value);
1736 O2_SIGNPOST_START(device, dpid,
"state",
"Starting processing state %d", (
int)newState);
1737 state.streaming = newState;
1747 context.completed.clear();
1748 context.completed.reserve(16);
1750 state.lastActiveDataProcessor.store(&context);
1754 context.preDanglingCallbacks(danglingContext);
1755 if (
state.lastActiveDataProcessor.load() ==
nullptr) {
1758 auto activity =
ref.get<
DataRelayer>().processDanglingInputs(context.expirationHandlers, *context.registry,
true);
1759 if (activity.expiredSlots > 0) {
1760 state.lastActiveDataProcessor = &context;
1763 context.completed.clear();
1765 state.lastActiveDataProcessor = &context;
1768 context.postDanglingCallbacks(danglingContext);
1776 state.lastActiveDataProcessor = &context;
1799 timingInfo.timeslice = relayer.getOldestPossibleOutput().timeslice.value;
1800 timingInfo.tfCounter = -1;
1801 timingInfo.firstTForbit = -1;
1803 timingInfo.creation = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count();
1804 O2_SIGNPOST_EVENT_EMIT(calibration, dpid,
"calibration",
"TimingInfo.keepAtEndOfStream %d", timingInfo.keepAtEndOfStream);
1808 context.preEOSCallbacks(eosContext);
1812 streamContext.postEOSCallbacks(eosContext);
1813 context.postEOSCallbacks(eosContext);
1815 for (
auto& channel : spec.outputChannels) {
1816 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"state",
"Sending end of stream to %{public}s.", channel.name.c_str());
1823 if (shouldProcess) {
1824 state.lastActiveDataProcessor = &context;
1828 for (
auto& poller :
state.activeOutputPollers) {
1829 uv_poll_stop(poller);
1837 for (
auto& poller :
state.activeOutputPollers) {
1838 uv_poll_stop(poller);
1854 if (deviceContext.sigusr1Handle) {
1860 handle->data =
nullptr;
1889 auto getInputTypes = [&info, &context]() -> std::optional<std::vector<InputInfo>> {
1894 auto& parts = info.
parts;
1897 std::vector<InputInfo> results;
1899 results.reserve(parts.Size() / 2);
1900 size_t nTotalPayloads = 0;
1904 if (
type != InputType::Invalid &&
length > 1) {
1905 nTotalPayloads +=
length - 1;
1909 for (
size_t pi = 0; pi < parts.Size(); pi += 2) {
1910 auto* headerData = parts.At(pi)->GetData();
1911 auto sih = o2::header::get<SourceInfoHeader*>(headerData);
1913 O2_SIGNPOST_EVENT_EMIT(device, cid,
"handle_data",
"Got SourceInfoHeader with state %d", (
int)sih->state);
1914 info.
state = sih->state;
1915 insertInputInfo(pi, 2, InputType::SourceInfo, info.
id);
1916 state.lastActiveDataProcessor = &context;
1919 auto dih = o2::header::get<DomainInfoHeader*>(headerData);
1921 O2_SIGNPOST_EVENT_EMIT(device, cid,
"handle_data",
"Got DomainInfoHeader with oldestPossibleTimeslice %d", (
int)dih->oldestPossibleTimeslice);
1922 insertInputInfo(pi, 2, InputType::DomainInfo, info.
id);
1923 state.lastActiveDataProcessor = &context;
1926 auto dh = o2::header::get<DataHeader*>(headerData);
1928 insertInputInfo(pi, 0, InputType::Invalid, info.
id);
1932 if (dh->payloadSize > parts.At(pi + 1)->GetSize()) {
1933 insertInputInfo(pi, 0, InputType::Invalid, info.
id);
1937 auto dph = o2::header::get<DataProcessingHeader*>(headerData);
1942 O2_SIGNPOST_START(parts,
pid,
"parts",
"Processing DataHeader %{public}-4s/%{public}-16s/%d with splitPayloadParts %d and splitPayloadIndex %d",
1943 dh->dataOrigin.str, dh->dataDescription.str, dh->subSpecification, dh->splitPayloadParts, dh->splitPayloadIndex);
1945 insertInputInfo(pi, 2, InputType::Invalid, info.
id);
1949 if (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) {
1952 insertInputInfo(pi, dh->splitPayloadParts + 1, InputType::Data, info.
id);
1953 pi += dh->splitPayloadParts - 1;
1959 size_t finalSplitPayloadIndex = pi + (dh->splitPayloadParts > 0 ? dh->splitPayloadParts : 1) * 2;
1960 if (finalSplitPayloadIndex > parts.Size()) {
1962 insertInputInfo(pi, 0, InputType::Invalid, info.
id);
1965 insertInputInfo(pi, 2, InputType::Data, info.
id);
1966 for (; pi + 2 < finalSplitPayloadIndex; pi += 2) {
1967 insertInputInfo(pi + 2, 2, InputType::Data, info.
id);
1971 if (results.size() + nTotalPayloads != parts.Size()) {
1972 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"handle_data",
"inconsistent number of inputs extracted. %zu vs parts (%zu)", results.size() + nTotalPayloads, parts.Size());
1973 return std::nullopt;
1978 auto reportError = [
ref](
const char*
message) {
1983 auto handleValidMessages = [&info,
ref, &reportError](std::vector<InputInfo>
const& inputInfos) {
1987 auto& parts = info.
parts;
1990 bool hasBackpressure =
false;
1991 size_t minBackpressureTimeslice = -1;
1993 size_t oldestPossibleTimeslice = -1;
1994 static std::vector<int> ordering;
1996 ordering.resize(inputInfos.size());
1997 std::iota(ordering.begin(), ordering.end(), 0);
1999 std::stable_sort(ordering.begin(), ordering.end(), [&inputInfos](
int const&
a,
int const&
b) {
2000 auto const& ai = inputInfos[a];
2001 auto const& bi = inputInfos[b];
2002 if (ai.type != bi.type) {
2003 return ai.type < bi.type;
2005 return ai.position < bi.position;
2007 for (
size_t ii = 0; ii < inputInfos.size(); ++ii) {
2008 auto const& input = inputInfos[ordering[ii]];
2009 switch (input.type) {
2010 case InputType::Data: {
2012 auto headerIndex = input.position;
2014 auto nPayloadsPerHeader = 0;
2015 if (input.size > 2) {
2017 nMessages = input.size;
2018 nPayloadsPerHeader = nMessages - 1;
2021 auto dh = o2::header::get<DataHeader*>(parts.At(headerIndex)->GetData());
2022 nMessages = dh->splitPayloadParts > 0 ? dh->splitPayloadParts * 2 : 2;
2023 nPayloadsPerHeader = 1;
2024 ii += (nMessages / 2) - 1;
2028 O2_SIGNPOST_EVENT_EMIT(async_queue, cid,
"onDrop",
"Dropping message from slot %zu. Forwarding as needed. Timeslice %zu",
2029 slot.
index, oldestOutputInfo.timeslice.value);
2036 forwardInputs(
ref, slot, dropped, oldestOutputInfo,
false,
true);
2038 auto relayed = relayer.relay(parts.At(headerIndex)->GetData(),
2039 &parts.At(headerIndex),
2044 switch (relayed.type) {
2047 LOGP(alarm,
"Backpressure on channel {}. Waiting.", info.
channel->GetName());
2048 auto& monitoring =
ref.get<o2::monitoring::Monitoring>();
2049 monitoring.send(o2::monitoring::Metric{1, fmt::format(
"backpressure_{}", info.
channel->GetName())});
2053 policy.backpressure(info);
2054 hasBackpressure =
true;
2055 minBackpressureTimeslice = std::min<size_t>(minBackpressureTimeslice, relayed.timeslice.value);
2061 LOGP(info,
"Back to normal on channel {}.", info.
channel->GetName());
2062 auto& monitoring =
ref.get<o2::monitoring::Monitoring>();
2063 monitoring.send(o2::monitoring::Metric{0, fmt::format(
"backpressure_{}", info.
channel->GetName())});
2070 case InputType::SourceInfo: {
2071 LOGP(detail,
"Received SourceInfo");
2073 state.lastActiveDataProcessor = &context;
2074 auto headerIndex = input.position;
2075 auto payloadIndex = input.position + 1;
2076 assert(payloadIndex < parts.Size());
2079 parts.At(headerIndex).reset(
nullptr);
2080 parts.At(payloadIndex).reset(
nullptr);
2087 case InputType::DomainInfo: {
2091 state.lastActiveDataProcessor = &context;
2092 auto headerIndex = input.position;
2093 auto payloadIndex = input.position + 1;
2094 assert(payloadIndex < parts.Size());
2098 auto dih = o2::header::get<DomainInfoHeader*>(parts.At(headerIndex)->GetData());
2099 if (hasBackpressure && dih->oldestPossibleTimeslice >= minBackpressureTimeslice) {
2102 oldestPossibleTimeslice = std::min(oldestPossibleTimeslice, dih->oldestPossibleTimeslice);
2103 LOGP(
debug,
"Got DomainInfoHeader, new oldestPossibleTimeslice {} on channel {}", oldestPossibleTimeslice, info.
id.
value);
2104 parts.At(headerIndex).reset(
nullptr);
2105 parts.At(payloadIndex).reset(
nullptr);
2107 case InputType::Invalid: {
2108 reportError(
"Invalid part found.");
2114 if (oldestPossibleTimeslice != (
size_t)-1) {
2117 context.domainInfoUpdatedCallback(*context.registry, oldestPossibleTimeslice, info.
id);
2119 state.lastActiveDataProcessor = &context;
2121 auto it = std::remove_if(parts.fParts.begin(), parts.fParts.end(), [](
auto&
msg) ->
bool { return msg.get() == nullptr; });
2122 parts.fParts.erase(it, parts.end());
2123 if (parts.fParts.size()) {
2124 LOG(
debug) << parts.fParts.size() <<
" messages backpressured";
2136 auto inputTypes = getInputTypes();
2137 if (
bool(inputTypes) ==
false) {
2138 reportError(
"Parts should come in couples. Dropping it.");
2141 handleValidMessages(*inputTypes);
2147struct InputLatency {
2152auto calculateInputRecordLatency(
InputRecord const& record, uint64_t currentTime) -> InputLatency
2156 for (
auto& item : record) {
2157 auto* header = o2::header::get<DataProcessingHeader*>(item.header);
2158 if (header ==
nullptr) {
2161 int64_t partLatency = (0x7fffffffffffffff & currentTime) - (0x7fffffffffffffff & header->creation);
2162 if (partLatency < 0) {
2165 result.minLatency = std::min(
result.minLatency, (uint64_t)partLatency);
2166 result.maxLatency = std::max(
result.maxLatency, (uint64_t)partLatency);
2171auto calculateTotalInputRecordSize(
InputRecord const& record) ->
int
2173 size_t totalInputSize = 0;
2174 for (
auto& item : record) {
2175 auto* header = o2::header::get<DataHeader*>(item.header);
2176 if (header ==
nullptr) {
2179 totalInputSize += header->payloadSize;
2181 return totalInputSize;
2184template <
typename T>
2185void update_maximum(std::atomic<T>& maximum_value, T
const&
value)
noexcept
2187 T prev_value = maximum_value;
2188 while (prev_value <
value &&
2189 !maximum_value.compare_exchange_weak(prev_value,
value)) {
2197 LOGP(
debug,
"DataProcessingDevice::tryDispatchComputation");
2202 std::vector<MessageSet> currentSetOfInputs;
2205 auto getInputSpan = [
ref, ¤tSetOfInputs](
TimesliceSlot slot,
bool consume =
true) {
2210 currentSetOfInputs = relayer.consumeExistingInputsForTimeslice(slot);
2212 auto getter = [¤tSetOfInputs](
size_t i,
size_t partindex) ->
DataRef {
2213 if (currentSetOfInputs[
i].getNumberOfPairs() > partindex) {
2214 const char* headerptr =
nullptr;
2215 const char* payloadptr =
nullptr;
2216 size_t payloadSize = 0;
2222 auto const& headerMsg = currentSetOfInputs[
i].associatedHeader(partindex);
2223 auto const& payloadMsg = currentSetOfInputs[
i].associatedPayload(partindex);
2224 headerptr =
static_cast<char const*
>(headerMsg->GetData());
2225 payloadptr = payloadMsg ?
static_cast<char const*
>(payloadMsg->GetData()) :
nullptr;
2226 payloadSize = payloadMsg ? payloadMsg->GetSize() : 0;
2227 return DataRef{
nullptr, headerptr, payloadptr, payloadSize};
2231 auto nofPartsGetter = [¤tSetOfInputs](
size_t i) ->
size_t {
2232 return currentSetOfInputs[
i].getNumberOfPairs();
2234 return InputSpan{getter, nofPartsGetter, currentSetOfInputs.
size()};
2249 auto timeslice = relayer.getTimesliceForSlot(
i);
2251 timingInfo.timeslice = timeslice.value;
2261 auto timeslice = relayer.getTimesliceForSlot(
i);
2263 timingInfo.globalRunNumberChanged = !
TimingInfo::timesliceIsTimer(timeslice.value) && dataProcessorContext.lastRunNumberProcessed != timingInfo.runNumber;
2265 timingInfo.globalRunNumberChanged &= (dataProcessorContext.lastRunNumberProcessed == -1 || timingInfo.runNumber != 0);
2269 timingInfo.streamRunNumberChanged = timingInfo.globalRunNumberChanged;
2277 assert(record.size() == currentSetOfInputs.size());
2278 for (
size_t ii = 0, ie = record.size(); ii < ie; ++ii) {
2282 DataRef input = record.getByPos(ii);
2286 if (input.
header ==
nullptr) {
2290 currentSetOfInputs[ii].clear();
2301 for (
size_t pi = 0, pe = record.size(); pi < pe; ++pi) {
2302 DataRef input = record.getByPos(pi);
2303 if (input.
header ==
nullptr) {
2306 auto sih = o2::header::get<SourceInfoHeader*>(input.
header);
2311 auto dh = o2::header::get<DataHeader*>(input.
header);
2321 if (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) {
2324 pi += dh->splitPayloadParts - 1;
2326 size_t pi = pi + (dh->splitPayloadParts > 0 ? dh->splitPayloadParts : 1) * 2;
2334 state.streaming = newState;
2335 control.notifyStreamingState(
state.streaming);
2339 if (completed.empty() ==
true) {
2340 LOGP(
debug,
"No computations available for dispatching.");
2347 std::atomic_thread_fence(std::memory_order_release);
2348 char relayerSlotState[1024];
2350 char*
buffer = relayerSlotState + written;
2351 for (
size_t ai = 0; ai != record.size(); ai++) {
2352 buffer[ai] = record.isValid(ai) ?
'3' :
'0';
2354 buffer[record.size()] = 0;
2356 .size = (
int)(record.size() +
buffer - relayerSlotState),
2357 .
data = relayerSlotState});
2358 uint64_t tEnd = uv_hrtime();
2360 int64_t wallTimeMs = (tEnd - tStart) / 1000000;
2368 auto latency = calculateInputRecordLatency(record, tStartMilli);
2371 static int count = 0;
2378 std::atomic_thread_fence(std::memory_order_release);
2379 char relayerSlotState[1024];
2381 char*
buffer = strchr(relayerSlotState,
' ') + 1;
2382 for (
size_t ai = 0; ai != record.size(); ai++) {
2383 buffer[ai] = record.isValid(ai) ?
'2' :
'0';
2385 buffer[record.size()] = 0;
2403 switch (spec.completionPolicy.order) {
2405 std::sort(completed.begin(), completed.end(), [](
auto const&
a,
auto const&
b) { return a.timeslice.value < b.timeslice.value; });
2408 std::sort(completed.begin(), completed.end(), [](
auto const&
a,
auto const&
b) { return a.slot.index < b.slot.index; });
2415 for (
auto action : completed) {
2417 O2_SIGNPOST_START(device, aid,
"device",
"Processing action on slot %lu for action %{public}s", action.
slot.
index, fmt::format(
"{}", action.
op).c_str());
2441 dpContext.preProcessingCallbacks(processContext);
2444 context.postDispatchingCallbacks(processContext);
2445 if (spec.forwards.empty() ==
false) {
2447 forwardInputs(
ref, action.
slot, currentSetOfInputs, timesliceIndex.getOldestPossibleOutput(),
false);
2448 O2_SIGNPOST_END(device, aid,
"device",
"Forwarding inputs consume: %d.",
false);
2456 bool hasForwards = spec.forwards.empty() ==
false;
2459 if (context.canForwardEarly && hasForwards && consumeSomething) {
2460 O2_SIGNPOST_EVENT_EMIT(device, aid,
"device",
"Early forwainding: %{public}s.", fmt::format(
"{}", action.
op).c_str());
2464 markInputsAsDone(action.
slot);
2466 uint64_t tStart = uv_hrtime();
2468 preUpdateStats(action, record, tStart);
2470 static bool noCatch = getenv(
"O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv(
"O2_NO_CATCHALL_EXCEPTIONS"),
"0");
2478 switch (action.
op) {
2489 if (
state.quitRequested ==
false) {
2493 streamContext.preProcessingCallbacks(processContext);
2499 if (context.statefulProcess && shouldProcess(action)) {
2503 (context.statefulProcess)(processContext);
2505 }
else if (context.statelessProcess && shouldProcess(action)) {
2507 (context.statelessProcess)(processContext);
2509 }
else if (context.statelessProcess || context.statefulProcess) {
2512 O2_SIGNPOST_EVENT_EMIT(device, pcid,
"device",
"No processing callback provided. Switching to %{public}s.",
"Idle");
2515 if (shouldProcess(action)) {
2517 if (timingInfo.globalRunNumberChanged) {
2518 context.lastRunNumberProcessed = timingInfo.runNumber;
2535 streamContext.finaliseOutputsCallbacks(processContext);
2541 streamContext.postProcessingCallbacks(processContext);
2547 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
2548 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
2554 (context.errorHandling)(e, record);
2559 }
catch (std::exception& ex) {
2564 (context.errorHandling)(e, record);
2566 (context.errorHandling)(e, record);
2569 if (
state.severityStack.empty() ==
false) {
2570 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
2571 state.severityStack.pop_back();
2574 postUpdateStats(action, record, tStart, tStartMilli);
2578 cleanupRecord(record);
2579 context.postDispatchingCallbacks(processContext);
2582 if ((context.canForwardEarly ==
false) && hasForwards && consumeSomething) {
2587 context.postForwardingCallbacks(processContext);
2589 cleanTimers(action.
slot, record);
2591 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());
2593 O2_SIGNPOST_END(device, sid,
"device",
"Start processing ready actions");
2597 LOGP(detail,
"Broadcasting end of stream");
2598 for (
auto& channel : spec.outputChannels) {
2621 cfg.getRecursive(
name);
2622 std::vector<std::unique_ptr<ParamRetriever>> retrievers;
2623 retrievers.emplace_back(std::make_unique<ConfigurationOptionsRetriever>(&cfg,
name));
2624 auto configStore = std::make_unique<ConfigParamStore>(options, std::move(retrievers));
2625 configStore->preload();
2626 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
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)
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 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