34#if defined(__APPLE__) || defined(NDEBUG)
35#define O2_SIGNPOST_IMPLEMENTATION
60#include <fairmq/Parts.h>
61#include <fairmq/Socket.h>
62#include <fairmq/ProgOptions.h>
63#include <fairmq/shmem/Message.h>
64#include <Configuration/ConfigurationInterface.h>
65#include <Configuration/ConfigurationFactory.h>
66#include <Monitoring/Monitoring.h>
68#include <TClonesArray.h>
70#include <fmt/ostream.h>
78#include <boost/property_tree/json_parser.hpp>
136 return devices[running.
index];
146 : mRunningDevice{running},
147 mConfigRegistry{nullptr},
148 mServiceRegistry{registry}
150 GetConfig()->Subscribe<std::string>(
"dpl", [®istry = mServiceRegistry](
const std::string&
key, std::string
value) {
151 if (
key ==
"cleanup") {
155 int64_t newCleanupCount = std::stoll(
value);
156 if (newCleanupCount <= cleanupCount) {
159 deviceState.cleanupCount.store(newCleanupCount);
160 for (
auto& info : deviceState.inputChannelInfos) {
161 fair::mq::Parts parts;
162 while (info.channel->Receive(parts, 0)) {
163 LOGP(
debug,
"Dropping {} parts", parts.Size());
164 if (parts.Size() == 0) {
172 std::function<
void(
const fair::mq::State)> stateWatcher = [
this, ®istry = mServiceRegistry](
const fair::mq::State
state) ->
void {
177 control.notifyDeviceState(fair::mq::GetStateName(
state));
180 if (deviceState.nextFairMQState.empty() ==
false) {
181 auto state = deviceState.nextFairMQState.back();
183 deviceState.nextFairMQState.pop_back();
188 this->SubscribeToStateChange(
"99-dpl", stateWatcher);
200 mAwakeHandle->data = &
state;
202 LOG(
error) <<
"Unable to initialise subscription";
206 SubscribeToNewTransition(
"dpl", [wakeHandle = mAwakeHandle](fair::mq::Transition t) {
207 int res = uv_async_send(wakeHandle);
209 LOG(
error) <<
"Unable to notify subscription";
211 LOG(
debug) <<
"State transition requested";
224 O2_SIGNPOST_START(device, sid,
"run_callback",
"Starting run callback on stream %d", task->id.index);
226 O2_SIGNPOST_END(device, sid,
"run_callback",
"Done processing data for stream %d", task->id.index);
239 using o2::monitoring::Metric;
240 using o2::monitoring::Monitoring;
241 using o2::monitoring::tags::Key;
242 using o2::monitoring::tags::Value;
246 stats.totalConsumedBytes += accumulatedConsumed.
sharedMemory;
249 stats.totalConsumedTimeslices += std::min<int64_t>(accumulatedConsumed.
timeslices, 1);
253 dpStats.processCommandQueue();
263 dpStats.processCommandQueue();
266 for (
auto& consumer :
state.offerConsumers) {
267 quotaEvaluator.consume(task->id.index, consumer, reportConsumedOffer);
269 state.offerConsumers.clear();
270 quotaEvaluator.handleExpired(reportExpiredOffer);
271 quotaEvaluator.dispose(task->id.index);
272 task->running =
false;
300 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"Data pending on socket for channel %{public}s", context->name);
304 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"Socket connected for channel %{public}s", context->name);
306 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"Socket connected for read in context %{public}s", context->name);
307 uv_poll_start(poller, UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED, &
on_socket_polled);
310 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"Socket connected for write for channel %{public}s", context->name);
318 case UV_DISCONNECT: {
319 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"Socket disconnected in context %{public}s", context->name);
321 case UV_PRIORITIZED: {
322 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"Socket prioritized for context %{public}s", context->name);
334 LOGP(fatal,
"Error while polling {}: {}", context->name, status);
339 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"Data pending on socket for channel %{public}s", context->name);
341 assert(context->channelInfo);
342 context->channelInfo->readPolled =
true;
345 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"OOB socket connected for channel %{public}s", context->name);
347 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"OOB socket connected for read in context %{public}s", context->name);
350 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"OOB socket connected for write for channel %{public}s", context->name);
354 case UV_DISCONNECT: {
355 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"OOB socket disconnected in context %{public}s", context->name);
358 case UV_PRIORITIZED: {
359 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"OOB socket prioritized for context %{public}s", context->name);
380 context.statelessProcess = spec.algorithm.onProcess;
382 context.error = spec.algorithm.onError;
383 context.
initError = spec.algorithm.onInitError;
386 if (configStore ==
nullptr) {
387 std::vector<std::unique_ptr<ParamRetriever>> retrievers;
388 retrievers.emplace_back(std::make_unique<FairOptionsRetriever>(GetConfig()));
389 configStore = std::make_unique<ConfigParamStore>(spec.options, std::move(retrievers));
390 configStore->preload();
391 configStore->activate();
394 using boost::property_tree::ptree;
397 for (
auto&
entry : configStore->store()) {
398 std::stringstream ss;
400 if (
entry.second.empty() ==
false) {
401 boost::property_tree::json_parser::write_json(ss,
entry.second,
false);
404 str =
entry.second.get_value<std::string>();
406 std::string configString = fmt::format(
"[CONFIG] {}={} 1 {}",
entry.first,
str, configStore->provenance(
entry.first.c_str())).c_str();
410 mConfigRegistry = std::make_unique<ConfigParamRegistry>(std::move(configStore));
413 if (context.initError) {
414 context.initErrorHandling = [&errorCallback = context.initError,
427 errorCallback(errorContext);
430 context.initErrorHandling = [&serviceRegistry = mServiceRegistry](
RuntimeErrorRef e) {
445 context.expirationHandlers.clear();
446 context.init = spec.algorithm.onInit;
448 static bool noCatch = getenv(
"O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv(
"O2_NO_CATCHALL_EXCEPTIONS"),
"0");
449 InitContext initContext{*mConfigRegistry, mServiceRegistry};
453 context.statefulProcess = context.init(initContext);
455 if (context.initErrorHandling) {
456 (context.initErrorHandling)(e);
461 context.statefulProcess = context.init(initContext);
462 }
catch (std::exception& ex) {
467 (context.initErrorHandling)(e);
469 (context.initErrorHandling)(e);
474 state.inputChannelInfos.resize(spec.inputChannels.size());
478 int validChannelId = 0;
479 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
480 auto&
name = spec.inputChannels[ci].name;
481 if (
name.find(spec.channelPrefix +
"from_internal-dpl-clock") == 0) {
486 state.inputChannelInfos[ci].id = {validChannelId++};
491 if (spec.callbacksPolicy.policy !=
nullptr) {
492 InitContext initContext{*mConfigRegistry, mServiceRegistry};
497 auto* options = GetConfig();
498 for (
size_t si = 0; si < mStreams.size(); ++si) {
512 O2_SIGNPOST_END(device, sid,
"signal_state",
"No registry active. Ignoring signal.");
521 while (ri != quotaEvaluator.mOffers.size()) {
522 auto& offer = quotaEvaluator.mOffers[ri];
528 if (offer.valid && offer.sharedMemory != 0) {
529 O2_SIGNPOST_END(device, sid,
"signal_state",
"Memory already offered.");
535 for (
auto& offer : quotaEvaluator.mOffers) {
536 if (offer.valid ==
false) {
539 offer.sharedMemory = 1000000000;
546 O2_SIGNPOST_END(device, sid,
"signal_state",
"Done processing signals.");
560 if (oldestTimeslice.timeslice.value <= decongestion.lastTimeslice) {
561 LOG(
debug) <<
"Not sending already sent oldest possible timeslice " << oldestTimeslice.timeslice.value;
564 for (
int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
565 auto& info = proxy.getForwardChannelInfo(
ChannelIndex{fi});
570 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputsCallback",
"Skipping channel %{public}s because it's not a DPL channel",
576 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputsCallback",
"Forwarding to channel %{public}s oldest possible timeslice %zu, prio 20",
577 info.name.c_str(), oldestTimeslice.timeslice.value);
591 O2_SIGNPOST_START(forwarding, sid,
"forwardInputs",
"Starting forwarding for slot %zu with oldestTimeslice %zu %{public}s%{public}s%{public}s",
592 slot.index, oldestTimeslice.timeslice.value, copy ?
"with copy" :
"", copy && consume ?
" and " :
"", consume ?
"with consume" :
"");
595 for (
int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
596 if (forwardedParts[fi].
Size() == 0) {
600 auto& parts = forwardedParts[fi];
601 if (
info.policy ==
nullptr) {
612 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputs",
"Queuing forwarding oldestPossible %zu", oldestTimeslice.timeslice.value);
623 O2_SIGNPOST_START(forwarding, sid,
"forwardInputs",
"Cleaning up slot %zu with oldestTimeslice %zu %{public}s%{public}s%{public}s",
624 slot.index, oldestTimeslice.timeslice.value, copy ?
"with copy" :
"", copy && consume ?
" and " :
"", consume ?
"with consume" :
"");
627 for (
size_t ii = 0, ie = currentSetOfInputs.size(); ii < ie; ++ii) {
628 auto span = std::span<fair::mq::MessagePtr>(currentSetOfInputs[ii]);
641 if (infos.empty() ==
false) {
642 std::vector<fair::mq::RegionInfo> toBeNotified;
643 toBeNotified.swap(infos);
644 static bool dummyRead = getenv(
"DPL_DEBUG_MAP_ALL_SHM_REGIONS") && atoi(getenv(
"DPL_DEBUG_MAP_ALL_SHM_REGIONS"));
645 for (
auto const& info : toBeNotified) {
665void DataProcessingDevice::initPollers()
673 if ((context.statefulProcess !=
nullptr) || (context.statelessProcess !=
nullptr)) {
674 for (
auto& [channelName, channel] : GetChannels()) {
676 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
677 auto& channelSpec = spec.inputChannels[ci];
678 channelInfo = &
state.inputChannelInfos[ci];
679 if (channelSpec.name != channelName) {
682 channelInfo->
channel = &this->GetChannel(channelName, 0);
685 if ((
channelName.rfind(
"from_internal-dpl", 0) == 0) &&
686 (
channelName.rfind(
"from_internal-dpl-aod", 0) != 0) &&
687 (
channelName.rfind(
"from_internal-dpl-ccdb-backend", 0) != 0) &&
688 (
channelName.rfind(
"from_internal-dpl-injected", 0)) != 0) {
689 LOGP(detail,
"{} is an internal channel. Skipping as no input will come from there.", channelName);
693 if (
channelName.rfind(
"from_" + spec.name +
"_", 0) == 0) {
694 LOGP(detail,
"{} is to send data. Not polling.", channelName);
699 LOGP(detail,
"{} is not a DPL socket. Not polling.", channelName);
705 size_t zmq_fd_len =
sizeof(zmq_fd);
708 channel[0].GetSocket().GetOption(
"fd", &zmq_fd, &zmq_fd_len);
713 LOGP(detail,
"Polling socket for {}", channelName);
716 pCtx->loop =
state.loop;
718 pCtx->state = &
state;
720 assert(channelInfo !=
nullptr);
721 pCtx->channelInfo = channelInfo;
722 pCtx->socket = &channel[0].GetSocket();
725 uv_poll_init(
state.loop, poller, zmq_fd);
727 LOGP(detail,
"{} is an out of band channel.", channelName);
728 state.activeOutOfBandPollers.push_back(poller);
731 state.activeInputPollers.push_back(poller);
737 if (
state.activeInputPollers.empty() &&
738 state.activeOutOfBandPollers.empty() &&
739 state.activeTimers.empty() &&
740 state.activeSignals.empty()) {
744 if (
state.inputChannelInfos.empty()) {
745 LOGP(detail,
"No input channels. Setting exit transition timeout to 0.");
746 deviceContext.exitTransitionTimeout = 0;
748 for (
auto& [channelName, channel] : GetChannels()) {
749 if (
channelName.rfind(spec.channelPrefix +
"from_internal-dpl", 0) == 0) {
750 LOGP(detail,
"{} is an internal channel. Not polling.", channelName);
753 if (
channelName.rfind(spec.channelPrefix +
"from_" + spec.name +
"_", 0) == 0) {
754 LOGP(detail,
"{} is an out of band channel. Not polling for output.", channelName);
759 size_t zmq_fd_len =
sizeof(zmq_fd);
762 channel[0].GetSocket().GetOption(
"fd", &zmq_fd, &zmq_fd_len);
764 LOGP(
error,
"Cannot get file descriptor for channel {}", channelName);
767 LOG(detail) <<
"Polling socket for " << channel[0].GetName();
771 pCtx->loop =
state.loop;
773 pCtx->state = &
state;
777 uv_poll_init(
state.loop, poller, zmq_fd);
778 state.activeOutputPollers.push_back(poller);
782 LOGP(detail,
"This is a fake device so we exit after the first iteration.");
783 deviceContext.exitTransitionTimeout = 0;
789 uv_timer_init(
state.loop, timer);
790 timer->data = &
state;
791 uv_update_time(
state.loop);
793 state.activeTimers.push_back(timer);
797void DataProcessingDevice::startPollers()
803 for (
auto* poller :
state.activeInputPollers) {
805 O2_SIGNPOST_START(device, sid,
"socket_state",
"Input socket waiting for connection.");
809 for (
auto& poller :
state.activeOutOfBandPollers) {
813 for (
auto* poller :
state.activeOutputPollers) {
815 O2_SIGNPOST_START(device, sid,
"socket_state",
"Output socket waiting for connection.");
822 uv_timer_init(
state.loop, deviceContext.gracePeriodTimer);
825 deviceContext.dataProcessingGracePeriodTimer->data =
new ServiceRegistryRef(mServiceRegistry);
826 uv_timer_init(
state.loop, deviceContext.dataProcessingGracePeriodTimer);
829void DataProcessingDevice::stopPollers()
834 LOGP(detail,
"Stopping {} input pollers",
state.activeInputPollers.size());
835 for (
auto* poller :
state.activeInputPollers) {
838 uv_poll_stop(poller);
841 LOGP(detail,
"Stopping {} out of band pollers",
state.activeOutOfBandPollers.size());
842 for (
auto* poller :
state.activeOutOfBandPollers) {
843 uv_poll_stop(poller);
846 LOGP(detail,
"Stopping {} output pollers",
state.activeOutOfBandPollers.size());
847 for (
auto* poller :
state.activeOutputPollers) {
850 uv_poll_stop(poller);
854 uv_timer_stop(deviceContext.gracePeriodTimer);
856 free(deviceContext.gracePeriodTimer);
857 deviceContext.gracePeriodTimer =
nullptr;
859 uv_timer_stop(deviceContext.dataProcessingGracePeriodTimer);
861 free(deviceContext.dataProcessingGracePeriodTimer);
862 deviceContext.dataProcessingGracePeriodTimer =
nullptr;
877 for (
auto&
di : distinct) {
878 auto& route = spec.inputs[
di];
879 if (route.configurator.has_value() ==
false) {
884 .
name = route.configurator->name,
886 .lifetime = route.matcher.lifetime,
887 .creator = route.configurator->creatorConfigurator(
state, mServiceRegistry, *mConfigRegistry),
888 .checker = route.configurator->danglingConfigurator(
state, *mConfigRegistry),
889 .handler = route.configurator->expirationConfigurator(
state, *mConfigRegistry)};
890 context.expirationHandlers.emplace_back(std::move(handler));
893 if (
state.awakeMainThread ==
nullptr) {
899 deviceContext.expectedRegionCallbacks = std::stoi(fConfig->GetValue<std::string>(
"expected-region-callbacks"));
900 deviceContext.exitTransitionTimeout = std::stoi(fConfig->GetValue<std::string>(
"exit-transition-timeout"));
901 deviceContext.dataProcessingTimeout = std::stoi(fConfig->GetValue<std::string>(
"data-processing-timeout"));
903 for (
auto& channel : GetChannels()) {
904 channel.second.at(0).Transport()->SubscribeToRegionEvents([&context = deviceContext,
905 ®istry = mServiceRegistry,
906 &pendingRegionInfos = mPendingRegionInfos,
907 ®ionInfoMutex = mRegionInfoMutex](fair::mq::RegionInfo info) {
908 std::lock_guard<std::mutex> lock(regionInfoMutex);
909 LOG(detail) <<
">>> Region info event" << info.event;
910 LOG(detail) <<
"id: " << info.id;
911 LOG(detail) <<
"ptr: " << info.ptr;
912 LOG(detail) <<
"size: " << info.size;
913 LOG(detail) <<
"flags: " << info.flags;
916 pendingRegionInfos.push_back(info);
929 if (deviceContext.sigusr1Handle ==
nullptr) {
931 deviceContext.sigusr1Handle->data = &mServiceRegistry;
932 uv_signal_init(
state.loop, deviceContext.sigusr1Handle);
936 for (
auto& handle :
state.activeSignals) {
937 handle->data = &
state;
940 deviceContext.sigusr1Handle->data = &mServiceRegistry;
943 DataProcessingDevice::initPollers();
951 LOG(
error) <<
"DataProcessor " <<
state.lastActiveDataProcessor.load()->spec->name <<
" was unexpectedly active";
963 O2_SIGNPOST_END(device, cid,
"InitTask",
"Exiting InitTask callback waiting for the remaining region callbacks.");
965 auto hasPendingEvents = [&mutex = mRegionInfoMutex, &pendingRegionInfos = mPendingRegionInfos](
DeviceContext& deviceContext) {
966 std::lock_guard<std::mutex> lock(mutex);
967 return (pendingRegionInfos.empty() ==
false) || deviceContext.expectedRegionCallbacks > 0;
974 while (hasPendingEvents(deviceContext)) {
976 uv_run(
state.loop, UV_RUN_ONCE);
980 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
984 O2_SIGNPOST_END(device, cid,
"InitTask",
"Done waiting for registration events.");
991 bool enableRateLimiting = std::stoi(fConfig->GetValue<std::string>(
"timeframes-rate-limit"));
1000 if (enableRateLimiting ==
false && spec.name.find(
"internal-dpl-injected-dummy-sink") != std::string::npos) {
1003 if (enableRateLimiting) {
1004 for (
auto& spec : spec.outputs) {
1005 if (spec.matcher.binding.value ==
"dpl-summary") {
1012 context.
registry = &mServiceRegistry;
1015 if (context.
error !=
nullptr) {
1029 errorCallback(errorContext);
1043 switch (deviceContext.processingPolicies.
error) {
1054 auto decideEarlyForward = [&context, &deviceContext, &spec,
this]() ->
ForwardPolicy {
1062 for (
auto& forward : spec.forwards) {
1074 for (
auto&
label : spec.labels) {
1075 if (
label.value ==
"output-proxy") {
1084 if (spec.forwards.empty() ==
false) {
1090 forwardPolicy = defaultEarlyForwardPolicy;
1093 forwardPolicy = defaultEarlyForwardPolicy;
1097 bool onlyConditions =
true;
1098 bool overriddenEarlyForward =
false;
1099 for (
auto& forwarded : spec.forwards) {
1100 if (forwarded.matcher.lifetime != Lifetime::Condition) {
1101 onlyConditions =
false;
1105 overriddenEarlyForward =
true;
1109 if (forwarded.matcher.lifetime == Lifetime::Optional) {
1111 overriddenEarlyForward =
true;
1116 if (!overriddenEarlyForward && onlyConditions) {
1117 forwardPolicy = defaultEarlyForwardPolicy;
1118 LOG(detail) <<
"Enabling early forwarding because only conditions to be forwarded";
1120 return forwardPolicy;
1132 state.quitRequested =
false;
1135 for (
auto& info :
state.inputChannelInfos) {
1147 for (
size_t i = 0;
i < mStreams.size(); ++
i) {
1150 context.preStartStreamCallbacks(streamRef);
1152 }
catch (std::exception& e) {
1153 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"PreRun",
"Exception of type std::exception caught in PreRun: %{public}s. Rethrowing.", e.what());
1154 O2_SIGNPOST_END(device, cid,
"PreRun",
"Exiting PreRun due to exception thrown.");
1158 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"PreRun",
"Exception of type o2::framework::RuntimeErrorRef caught in PreRun: %{public}s. Rethrowing.", err.what);
1159 O2_SIGNPOST_END(device, cid,
"PreRun",
"Exiting PreRun due to exception thrown.");
1162 O2_SIGNPOST_END(device, cid,
"PreRun",
"Unknown exception being thrown. Rethrowing.");
1170 using o2::monitoring::Metric;
1171 using o2::monitoring::Monitoring;
1172 using o2::monitoring::tags::Key;
1173 using o2::monitoring::tags::Value;
1176 monitoring.send(
Metric{(uint64_t)1,
"device_state"}.addTag(Key::Subsystem, Value::DPL));
1184 using o2::monitoring::Metric;
1185 using o2::monitoring::Monitoring;
1186 using o2::monitoring::tags::Key;
1187 using o2::monitoring::tags::Value;
1190 monitoring.send(
Metric{(uint64_t)0,
"device_state"}.addTag(Key::Subsystem, Value::DPL));
1209 bool firstLoop =
true;
1211 O2_SIGNPOST_START(device, lid,
"device_state",
"First iteration of the device loop");
1213 bool dplEnableMultithreding = getenv(
"DPL_THREADPOOL_SIZE") !=
nullptr;
1214 if (dplEnableMultithreding) {
1215 setenv(
"UV_THREADPOOL_SIZE",
"1", 1);
1219 if (
state.nextFairMQState.empty() ==
false) {
1220 (
void)this->ChangeState(
state.nextFairMQState.back());
1221 state.nextFairMQState.pop_back();
1226 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1239 state.lastActiveDataProcessor.compare_exchange_strong(lastActive,
nullptr);
1241 auto shouldNotWait = (lastActive !=
nullptr &&
1245 shouldNotWait =
true;
1248 if (lastActive !=
nullptr) {
1251 if (NewStatePending()) {
1253 shouldNotWait =
true;
1259 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"State transition requested and we are now in Idle. We can consider it to be completed.");
1262 if (
state.severityStack.empty() ==
false) {
1263 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
1264 state.severityStack.pop_back();
1270 state.firedTimers.clear();
1272 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
1273 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
1280 O2_SIGNPOST_START(device, lid,
"run_loop",
"Dropping message from slot %" PRIu64
". Forwarding as needed.", (uint64_t)slot.index);
1288 forwardInputs(registry, slot, dropped, oldestOutputInfo,
false,
true);
1293 auto oldestPossibleTimeslice = relayer.getOldestPossibleOutput();
1295 if (shouldNotWait ==
false) {
1299 O2_SIGNPOST_END(device, lid,
"run_loop",
"Run loop completed. %{}s", shouldNotWait ?
"Will immediately schedule a new one" :
"Waiting for next event.");
1300 uv_run(
state.loop, shouldNotWait ? UV_RUN_NOWAIT : UV_RUN_ONCE);
1302 if ((
state.loopReason &
state.tracingFlags) != 0) {
1303 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
1304 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
1305 }
else if (
state.severityStack.empty() ==
false) {
1306 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
1307 state.severityStack.pop_back();
1312 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"Out of band activity detected. Rescanning everything.");
1316 if (!
state.pendingOffers.empty()) {
1317 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"Pending %" PRIu64
" offers. updating the ComputingQuotaEvaluator.", (uint64_t)
state.pendingOffers.size());
1329 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1337 assert(mStreams.size() == mHandles.size());
1340 for (
size_t ti = 0; ti < mStreams.size(); ti++) {
1341 auto& taskInfo = mStreams[ti];
1342 if (taskInfo.running) {
1346 streamRef.index = ti;
1348 using o2::monitoring::Metric;
1349 using o2::monitoring::Monitoring;
1350 using o2::monitoring::tags::Key;
1351 using o2::monitoring::tags::Value;
1354 if (streamRef.index != -1) {
1357 uv_work_t& handle = mHandles[streamRef.index];
1359 handle.data = &mStreams[streamRef.index];
1367 dpStats.processCommandQueue();
1378 struct SchedulingStats {
1379 std::atomic<size_t> lastScheduled = 0;
1380 std::atomic<size_t> numberOfUnscheduledSinceLastScheduled = 0;
1381 std::atomic<size_t> numberOfUnscheduled = 0;
1382 std::atomic<size_t> numberOfScheduled = 0;
1383 std::atomic<size_t> nextWarnAt = 1;
1385 static SchedulingStats schedulingStats;
1390 stream.registry = &mServiceRegistry;
1391 schedulingStats.lastScheduled = uv_now(
state.loop);
1392 schedulingStats.numberOfScheduled++;
1393 schedulingStats.numberOfUnscheduledSinceLastScheduled = 0;
1394 schedulingStats.nextWarnAt = 1;
1395 O2_SIGNPOST_EVENT_EMIT(scheduling, sid,
"Run",
"Enough resources to schedule computation on stream %d", streamRef.index);
1396 if (dplEnableMultithreding) [[unlikely]] {
1404 auto const lastSched = schedulingStats.lastScheduled.load();
1405 auto const schedInfo = lastSched ? fmt::format(
", last scheduled {} ms ago", uv_now(
state.loop) - lastSched) : std::string(
", never successfully scheduled");
1406 auto const buildMissingInfo = [&]() {
1407 auto const& required = spec.resourcePolicy.minRequired;
1408 std::string missingInfo;
1409 if (required.sharedMemory > 0 && accumulated.sharedMemory < required.sharedMemory) {
1410 missingInfo += fmt::format(
" shared memory (have {} MB, need {} MB)", accumulated.sharedMemory / 1000000, required.sharedMemory / 1000000);
1412 if (required.timeslices > 0 && accumulated.timeslices < required.timeslices) {
1413 missingInfo += fmt::format(
" timeslices (have {}, need {})", accumulated.timeslices, required.timeslices);
1415 if (required.cpu > 0 && accumulated.cpu < required.cpu) {
1416 missingInfo += fmt::format(
" CPU cores (have {}, need {})", accumulated.cpu, required.cpu);
1418 if (required.memory > 0 && accumulated.memory < required.memory) {
1419 missingInfo += fmt::format(
" memory (have {} MB, need {} MB)", accumulated.memory / 1000000, required.memory / 1000000);
1421 return missingInfo.empty() ? std::string(
" (policy: ") + spec.resourcePolicy.name +
")" :
" -" + missingInfo;
1423 if (schedulingStats.numberOfUnscheduledSinceLastScheduled >= schedulingStats.nextWarnAt) {
1424 auto const missingStr = buildMissingInfo();
1426 "Not enough resources to schedule computation on stream %d. %zu consecutive skips%s. Missing:%s. Data is not lost and it will be scheduled again.",
1428 schedulingStats.numberOfUnscheduledSinceLastScheduled.load(),
1430 missingStr.c_str());
1431 schedulingStats.nextWarnAt = schedulingStats.nextWarnAt * 2;
1433 auto const missingStr = buildMissingInfo();
1435 "Not enough resources to schedule computation on stream %d. %zu consecutive skips%s. Missing:%s. Data is not lost and it will be scheduled again.",
1437 schedulingStats.numberOfUnscheduledSinceLastScheduled.load(),
1439 missingStr.c_str());
1441 schedulingStats.numberOfUnscheduled++;
1442 schedulingStats.numberOfUnscheduledSinceLastScheduled++;
1449 O2_SIGNPOST_END(device, lid,
"run_loop",
"Run loop completed. Transition handling state %d.", (
int)
state.transitionHandling);
1452 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
1453 auto& info =
state.inputChannelInfos[ci];
1454 info.parts.fParts.clear();
1465 O2_SIGNPOST_START(device, dpid,
"do_prepare",
"Starting DataProcessorContext::doPrepare.");
1483 context.allDone = std::any_of(
state.inputChannelInfos.begin(),
state.inputChannelInfos.end(), [cid](
const auto& info) {
1485 O2_SIGNPOST_EVENT_EMIT(device, cid,
"do_prepare",
"Input channel %{public}s%{public}s has %zu parts left and is in state %d.",
1486 info.channel->GetName().c_str(), (info.id.value == ChannelIndex::INVALID ?
" (non DPL)" :
""), info.parts.fParts.size(), (int)info.state);
1488 O2_SIGNPOST_EVENT_EMIT(device, cid,
"do_prepare",
"External channel %d is in state %d.", info.id.value, (int)info.state);
1493 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"do_prepare",
"Processing %zu input channels.", spec.inputChannels.size());
1496 static std::vector<int> pollOrder;
1497 pollOrder.resize(
state.inputChannelInfos.size());
1498 std::iota(pollOrder.begin(), pollOrder.end(), 0);
1499 std::sort(pollOrder.begin(), pollOrder.end(), [&infos =
state.inputChannelInfos](
int a,
int b) {
1500 return infos[a].oldestForChannel.value < infos[b].oldestForChannel.value;
1504 if (pollOrder.empty()) {
1505 O2_SIGNPOST_END(device, dpid,
"do_prepare",
"Nothing to poll. Waiting for next iteration.");
1508 auto currentOldest =
state.inputChannelInfos[pollOrder.front()].oldestForChannel;
1509 auto currentNewest =
state.inputChannelInfos[pollOrder.back()].oldestForChannel;
1510 auto delta = currentNewest.value - currentOldest.value;
1511 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"do_prepare",
"Oldest possible timeframe range %" PRIu64
" => %" PRIu64
" delta %" PRIu64,
1512 (int64_t)currentOldest.value, (int64_t)currentNewest.value, (int64_t)delta);
1513 auto& infos =
state.inputChannelInfos;
1515 if (context.balancingInputs) {
1517 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));
1518 auto newEnd = std::remove_if(pollOrder.begin(), pollOrder.end(), [&infos, limitNew = currentOldest.value + ahead](
int a) ->
bool {
1519 return infos[a].oldestForChannel.value > limitNew;
1521 for (
auto it = pollOrder.begin(); it < pollOrder.end(); it++) {
1522 const auto& channelInfo =
state.inputChannelInfos[*it];
1528 bool shouldBeRunning = it < newEnd;
1529 if (running != shouldBeRunning) {
1530 uv_poll_start(poller, shouldBeRunning ? UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED : 0, &
on_socket_polled);
1536 pollOrder.erase(newEnd, pollOrder.end());
1538 O2_SIGNPOST_END(device, dpid,
"do_prepare",
"%zu channels pass the channel inbalance balance check.", pollOrder.size());
1540 for (
auto sci : pollOrder) {
1541 auto&
info =
state.inputChannelInfos[sci];
1543 O2_SIGNPOST_START(device, cid,
"channels",
"Processing channel %s",
info.channel->GetName().c_str());
1546 context.allDone =
false;
1551 if (
info.parts.Size()) {
1554 O2_SIGNPOST_END(device, cid,
"channels",
"Flushing channel %s which is in state %d and has %zu parts still pending.",
1555 info.channel->GetName().c_str(), (
int)
info.state,
info.parts.Size());
1558 if (
info.channel ==
nullptr) {
1559 O2_SIGNPOST_END(device, cid,
"channels",
"Channel %s which is in state %d is nullptr and has %zu parts still pending.",
1560 info.channel->GetName().c_str(), (
int)
info.state,
info.parts.Size());
1565 O2_SIGNPOST_END(device, cid,
"channels",
"Channel %s which is in state %d is not a DPL channel and has %zu parts still pending.",
1566 info.channel->GetName().c_str(), (
int)
info.state,
info.parts.Size());
1569 auto& socket =
info.channel->GetSocket();
1574 if (
info.hasPendingEvents == 0) {
1575 socket.Events(&
info.hasPendingEvents);
1577 if ((
info.hasPendingEvents & 1) == 0 && (
info.parts.Size() == 0)) {
1578 O2_SIGNPOST_END(device, cid,
"channels",
"No pending events and no remaining parts to process for channel %{public}s",
info.channel->GetName().c_str());
1584 info.readPolled =
false;
1593 bool newMessages =
false;
1595 O2_SIGNPOST_EVENT_EMIT(device, cid,
"channels",
"Receiving loop called for channel %{public}s (%d) with oldest possible timeslice %zu",
1596 info.channel->GetName().c_str(),
info.id.value,
info.oldestForChannel.value);
1597 if (
info.parts.Size() < 64) {
1598 fair::mq::Parts parts;
1599 info.channel->Receive(parts, 0);
1601 O2_SIGNPOST_EVENT_EMIT(device, cid,
"channels",
"Received %zu parts from channel %{public}s (%d).", parts.Size(),
info.channel->GetName().c_str(),
info.id.value);
1603 for (
auto&& part : parts) {
1604 info.parts.fParts.emplace_back(std::move(part));
1606 newMessages |=
true;
1609 if (
info.parts.Size() >= 0) {
1621 socket.Events(&
info.hasPendingEvents);
1622 if (
info.hasPendingEvents) {
1623 info.readPolled =
false;
1626 state.lastActiveDataProcessor.store(&context);
1629 O2_SIGNPOST_END(device, cid,
"channels",
"Done processing channel %{public}s (%d).",
1630 info.channel->GetName().c_str(),
info.id.value);
1645 context.completed.clear();
1646 context.completed.reserve(16);
1648 state.lastActiveDataProcessor.store(&context);
1652 context.preDanglingCallbacks(danglingContext);
1653 if (
state.lastActiveDataProcessor.load() ==
nullptr) {
1656 auto activity =
ref.get<
DataRelayer>().processDanglingInputs(context.expirationHandlers, *context.registry,
true);
1657 if (activity.expiredSlots > 0) {
1658 state.lastActiveDataProcessor = &context;
1661 context.completed.clear();
1663 state.lastActiveDataProcessor = &context;
1666 context.postDanglingCallbacks(danglingContext);
1674 state.lastActiveDataProcessor = &context;
1697 timingInfo.timeslice = relayer.getOldestPossibleOutput().timeslice.value;
1698 timingInfo.tfCounter = -1;
1699 timingInfo.firstTForbit = -1;
1701 timingInfo.creation = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count();
1702 O2_SIGNPOST_EVENT_EMIT(calibration, dpid,
"calibration",
"TimingInfo.keepAtEndOfStream %d", timingInfo.keepAtEndOfStream);
1706 context.preEOSCallbacks(eosContext);
1710 streamContext.postEOSCallbacks(eosContext);
1711 context.postEOSCallbacks(eosContext);
1713 for (
auto& channel : spec.outputChannels) {
1714 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"state",
"Sending end of stream to %{public}s.", channel.name.c_str());
1721 if (shouldProcess) {
1722 state.lastActiveDataProcessor = &context;
1726 for (
auto& poller :
state.activeOutputPollers) {
1727 uv_poll_stop(poller);
1735 for (
auto& poller :
state.activeOutputPollers) {
1736 uv_poll_stop(poller);
1752 if (deviceContext.sigusr1Handle) {
1758 handle->data =
nullptr;
1779 O2_SIGNPOST_EVENT_EMIT(device, sid,
"device",
"Early forwardinding before injecting data into relayer.");
1786 "Starting forwarding for incoming messages with oldestTimeslice %zu with copy",
1787 oldestTimeslice.timeslice.value);
1788 std::vector<fair::mq::Parts> forwardedParts(proxy.getNumForwardChannels());
1791 for (
int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
1792 if (forwardedParts[fi].
Size() == 0) {
1796 auto& parts = forwardedParts[fi];
1797 if (info.policy ==
nullptr) {
1801 O2_SIGNPOST_EVENT_EMIT(forwarding, sid,
"forwardInputs",
"Forwarding to %{public}s %d", info.name.c_str(), fi);
1807 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputs",
"Queuing forwarding oldestPossible %zu", oldestTimeslice.timeslice.value);
1832 auto getInputTypes = [&info, &context]() -> std::optional<std::vector<InputInfo>> {
1837 auto& parts = info.parts;
1840 std::vector<InputInfo> results;
1842 results.reserve(parts.Size() / 2);
1843 size_t nTotalPayloads = 0;
1847 if (
type != InputType::Invalid &&
length > 1) {
1848 nTotalPayloads +=
length - 1;
1852 for (
size_t pi = 0; pi < parts.Size(); pi += 2) {
1853 auto* headerData = parts.At(pi)->GetData();
1854 auto sih = o2::header::get<SourceInfoHeader*>(headerData);
1855 auto dh = o2::header::get<DataHeader*>(headerData);
1857 O2_SIGNPOST_EVENT_EMIT(device, cid,
"handle_data",
"Got SourceInfoHeader with state %d", (
int)sih->state);
1858 info.state = sih->state;
1859 insertInputInfo(pi, 2, InputType::SourceInfo, info.id);
1860 state.lastActiveDataProcessor = &context;
1862 LOGP(
error,
"Found data attached to a SourceInfoHeader");
1866 auto dih = o2::header::get<DomainInfoHeader*>(headerData);
1868 O2_SIGNPOST_EVENT_EMIT(device, cid,
"handle_data",
"Got DomainInfoHeader with oldestPossibleTimeslice %d", (
int)dih->oldestPossibleTimeslice);
1869 insertInputInfo(pi, 2, InputType::DomainInfo, info.id);
1870 state.lastActiveDataProcessor = &context;
1872 LOGP(
error,
"Found data attached to a DomainInfoHeader");
1877 insertInputInfo(pi, 0, InputType::Invalid, info.id);
1881 if (dh->payloadSize > parts.At(pi + 1)->GetSize()) {
1882 insertInputInfo(pi, 0, InputType::Invalid, info.id);
1886 auto dph = o2::header::get<DataProcessingHeader*>(headerData);
1891 O2_SIGNPOST_START(parts,
pid,
"parts",
"Processing DataHeader %{public}-4s/%{public}-16s/%d with splitPayloadParts %d and splitPayloadIndex %d",
1892 dh->dataOrigin.str, dh->dataDescription.str, dh->subSpecification, dh->splitPayloadParts, dh->splitPayloadIndex);
1894 insertInputInfo(pi, 2, InputType::Invalid, info.id);
1898 if (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) {
1901 insertInputInfo(pi, dh->splitPayloadParts + 1, InputType::Data, info.id);
1902 pi += dh->splitPayloadParts - 1;
1908 size_t finalSplitPayloadIndex = pi + (dh->splitPayloadParts > 0 ? dh->splitPayloadParts : 1) * 2;
1909 if (finalSplitPayloadIndex > parts.Size()) {
1911 insertInputInfo(pi, 0, InputType::Invalid, info.id);
1914 insertInputInfo(pi, 2, InputType::Data, info.id);
1915 for (; pi + 2 < finalSplitPayloadIndex; pi += 2) {
1916 insertInputInfo(pi + 2, 2, InputType::Data, info.id);
1920 if (results.size() + nTotalPayloads != parts.Size()) {
1921 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"handle_data",
"inconsistent number of inputs extracted. %zu vs parts (%zu)", results.size() + nTotalPayloads, parts.Size());
1922 return std::nullopt;
1927 auto reportError = [
ref](
const char*
message) {
1932 auto handleValidMessages = [&info,
ref, &reportError, &context](std::vector<InputInfo>
const& inputInfos) {
1936 auto& parts = info.parts;
1939 bool hasBackpressure =
false;
1940 size_t minBackpressureTimeslice = -1;
1942 size_t oldestPossibleTimeslice = -1;
1943 static std::vector<int> ordering;
1945 ordering.resize(inputInfos.size());
1946 std::iota(ordering.begin(), ordering.end(), 0);
1948 std::stable_sort(ordering.begin(), ordering.end(), [&inputInfos](
int const&
a,
int const&
b) {
1949 auto const& ai = inputInfos[a];
1950 auto const& bi = inputInfos[b];
1951 if (ai.type != bi.type) {
1952 return ai.type < bi.type;
1954 return ai.position < bi.position;
1956 for (
size_t ii = 0; ii < inputInfos.size(); ++ii) {
1957 auto const& input = inputInfos[ordering[ii]];
1958 switch (input.type) {
1959 case InputType::Data: {
1961 auto headerIndex = input.position;
1963 auto nPayloadsPerHeader = 0;
1964 if (input.size > 2) {
1966 nMessages = input.size;
1967 nPayloadsPerHeader = nMessages - 1;
1970 auto dh = o2::header::get<DataHeader*>(parts.At(headerIndex)->GetData());
1971 nMessages = dh->splitPayloadParts > 0 ? dh->splitPayloadParts * 2 : 2;
1972 nPayloadsPerHeader = 1;
1973 ii += (nMessages / 2) - 1;
1977 O2_SIGNPOST_EVENT_EMIT(async_queue, cid,
"onDrop",
"Dropping message from slot %zu. Forwarding as needed. Timeslice %zu",
1978 slot.
index, oldestOutputInfo.timeslice.value);
1985 forwardInputs(
ref, slot, dropped, oldestOutputInfo,
false,
true);
1988 auto relayed = relayer.relay(parts.At(headerIndex)->GetData(),
1989 &parts.At(headerIndex),
1995 switch (relayed.type) {
1997 if (info.normalOpsNotified ==
true && info.backpressureNotified ==
false) {
1998 LOGP(alarm,
"Backpressure on channel {}. Waiting.", info.channel->GetName());
1999 auto& monitoring =
ref.get<o2::monitoring::Monitoring>();
2000 monitoring.send(o2::monitoring::Metric{1, fmt::format(
"backpressure_{}", info.channel->GetName())});
2001 info.backpressureNotified =
true;
2002 info.normalOpsNotified =
false;
2004 policy.backpressure(info);
2005 hasBackpressure =
true;
2006 minBackpressureTimeslice = std::min<size_t>(minBackpressureTimeslice, relayed.timeslice.value);
2011 if (info.normalOpsNotified ==
false && info.backpressureNotified ==
true) {
2012 LOGP(info,
"Back to normal on channel {}.", info.channel->GetName());
2013 auto& monitoring =
ref.get<o2::monitoring::Monitoring>();
2014 monitoring.send(o2::monitoring::Metric{0, fmt::format(
"backpressure_{}", info.channel->GetName())});
2015 info.normalOpsNotified =
true;
2016 info.backpressureNotified =
false;
2021 case InputType::SourceInfo: {
2022 LOGP(detail,
"Received SourceInfo");
2024 state.lastActiveDataProcessor = &context;
2025 auto headerIndex = input.position;
2026 auto payloadIndex = input.position + 1;
2027 assert(payloadIndex < parts.Size());
2030 parts.At(headerIndex).reset(
nullptr);
2031 parts.At(payloadIndex).reset(
nullptr);
2038 case InputType::DomainInfo: {
2042 state.lastActiveDataProcessor = &context;
2043 auto headerIndex = input.position;
2044 auto payloadIndex = input.position + 1;
2045 assert(payloadIndex < parts.Size());
2049 auto dih = o2::header::get<DomainInfoHeader*>(parts.At(headerIndex)->GetData());
2050 if (hasBackpressure && dih->oldestPossibleTimeslice >= minBackpressureTimeslice) {
2053 oldestPossibleTimeslice = std::min(oldestPossibleTimeslice, dih->oldestPossibleTimeslice);
2054 LOGP(
debug,
"Got DomainInfoHeader, new oldestPossibleTimeslice {} on channel {}", oldestPossibleTimeslice, info.id.value);
2055 parts.At(headerIndex).reset(
nullptr);
2056 parts.At(payloadIndex).reset(
nullptr);
2058 case InputType::Invalid: {
2059 reportError(
"Invalid part found.");
2065 if (oldestPossibleTimeslice != (
size_t)-1) {
2066 info.oldestForChannel = {oldestPossibleTimeslice};
2068 context.domainInfoUpdatedCallback(*context.registry, oldestPossibleTimeslice, info.id);
2070 state.lastActiveDataProcessor = &context;
2072 auto it = std::remove_if(parts.fParts.begin(), parts.fParts.end(), [](
auto&
msg) ->
bool { return msg.get() == nullptr; });
2073 parts.fParts.erase(it, parts.end());
2074 if (parts.fParts.size()) {
2075 LOG(
debug) << parts.fParts.size() <<
" messages backpressured";
2087 auto inputTypes = getInputTypes();
2088 if (
bool(inputTypes) ==
false) {
2089 reportError(
"Parts should come in couples. Dropping it.");
2092 handleValidMessages(*inputTypes);
2098struct InputLatency {
2103auto calculateInputRecordLatency(
InputRecord const& record, uint64_t currentTime) -> InputLatency
2107 for (
auto& item : record) {
2108 auto* header = o2::header::get<DataProcessingHeader*>(item.header);
2109 if (header ==
nullptr) {
2112 int64_t partLatency = (0x7fffffffffffffff & currentTime) - (0x7fffffffffffffff & header->creation);
2113 if (partLatency < 0) {
2116 result.minLatency = std::min(
result.minLatency, (uint64_t)partLatency);
2117 result.maxLatency = std::max(
result.maxLatency, (uint64_t)partLatency);
2122auto calculateTotalInputRecordSize(
InputRecord const& record) ->
int
2124 size_t totalInputSize = 0;
2125 for (
auto& item : record) {
2126 auto* header = o2::header::get<DataHeader*>(item.header);
2127 if (header ==
nullptr) {
2130 totalInputSize += header->payloadSize;
2132 return totalInputSize;
2135template <
typename T>
2136void update_maximum(std::atomic<T>& maximum_value, T
const&
value)
noexcept
2138 T prev_value = maximum_value;
2139 while (prev_value <
value &&
2140 !maximum_value.compare_exchange_weak(prev_value,
value)) {
2148 LOGP(
debug,
"DataProcessingDevice::tryDispatchComputation");
2153 std::vector<std::vector<fair::mq::MessagePtr>> currentSetOfInputs;
2156 auto getInputSpan = [
ref, ¤tSetOfInputs](
TimesliceSlot slot,
bool consume =
true) {
2161 currentSetOfInputs = relayer.consumeExistingInputsForTimeslice(slot);
2166 auto const& msgs = currentSetOfInputs[
i];
2167 if (msgs.size() <=
indices.headerIdx) {
2170 auto const& headerMsg = msgs[
indices.headerIdx];
2171 char const* payloadData =
nullptr;
2172 size_t payloadSize = 0;
2173 if (msgs.size() >
indices.payloadIdx && msgs[
indices.payloadIdx]) {
2174 payloadData =
static_cast<char const*
>(msgs[
indices.payloadIdx]->GetData());
2175 payloadSize = msgs[
indices.payloadIdx]->GetSize();
2178 headerMsg ?
static_cast<char const*
>(headerMsg->GetData()) :
nullptr,
2182 auto nofPartsGetter = [¤tSetOfInputs](
size_t i) ->
size_t {
2185 auto refCountGetter = [¤tSetOfInputs](
size_t idx) ->
int {
2186 auto& header =
static_cast<const fair::mq::shmem::Message&
>(*(currentSetOfInputs[idx] |
get_header{0}));
2187 return header.GetRefCount();
2191 return next.headerIdx < currentSetOfInputs[
i].size() ? next :
DataRefIndices{size_t(-1), size_t(-1)};
2193 return InputSpan{nofPartsGetter, refCountGetter, indicesGetter, nextIndicesGetter, currentSetOfInputs.
size()};
2208 auto timeslice = relayer.getTimesliceForSlot(
i);
2210 timingInfo.timeslice = timeslice.value;
2220 auto timeslice = relayer.getTimesliceForSlot(
i);
2222 timingInfo.globalRunNumberChanged = !
TimingInfo::timesliceIsTimer(timeslice.value) && dataProcessorContext.lastRunNumberProcessed != timingInfo.runNumber;
2224 timingInfo.globalRunNumberChanged &= (dataProcessorContext.lastRunNumberProcessed == -1 || timingInfo.runNumber != 0);
2228 timingInfo.streamRunNumberChanged = timingInfo.globalRunNumberChanged;
2236 assert(record.size() == currentSetOfInputs.size());
2237 for (
size_t ii = 0, ie = record.size(); ii < ie; ++ii) {
2241 DataRef input = record.getByPos(ii);
2245 if (input.
header ==
nullptr) {
2249 currentSetOfInputs[ii].clear();
2260 for (
size_t pi = 0, pe = record.size(); pi < pe; ++pi) {
2261 DataRef input = record.getByPos(pi);
2262 if (input.
header ==
nullptr) {
2265 auto sih = o2::header::get<SourceInfoHeader*>(input.
header);
2270 auto dh = o2::header::get<DataHeader*>(input.
header);
2280 if (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) {
2283 pi += dh->splitPayloadParts - 1;
2285 size_t pi = pi + (dh->splitPayloadParts > 0 ? dh->splitPayloadParts : 1) * 2;
2291 if (completed.empty() ==
true) {
2292 LOGP(
debug,
"No computations available for dispatching.");
2301 std::atomic_thread_fence(std::memory_order_release);
2302 char relayerSlotState[1024];
2303 int written = snprintf(relayerSlotState, 1024,
"%d ", pipelineLength);
2304 char*
buffer = relayerSlotState + written;
2305 for (
size_t ai = 0; ai != record.size(); ai++) {
2306 buffer[ai] = record.isValid(ai) ?
'3' :
'0';
2308 buffer[record.size()] = 0;
2310 .size = (
int)(record.size() +
buffer - relayerSlotState),
2311 .
data = relayerSlotState});
2312 uint64_t tEnd = uv_hrtime();
2314 int64_t wallTimeMs = (tEnd - tStart) / 1000000;
2322 auto latency = calculateInputRecordLatency(record, tStartMilli);
2325 static int count = 0;
2332 std::atomic_thread_fence(std::memory_order_release);
2333 char relayerSlotState[1024];
2334 snprintf(relayerSlotState, 1024,
"%d ", pipelineLength);
2335 char*
buffer = strchr(relayerSlotState,
' ') + 1;
2336 for (
size_t ai = 0; ai != record.size(); ai++) {
2337 buffer[ai] = record.isValid(ai) ?
'2' :
'0';
2339 buffer[record.size()] = 0;
2357 switch (spec.completionPolicy.order) {
2359 std::sort(completed.begin(), completed.end(), [](
auto const&
a,
auto const&
b) { return a.timeslice.value < b.timeslice.value; });
2362 std::sort(completed.begin(), completed.end(), [](
auto const&
a,
auto const&
b) { return a.slot.index < b.slot.index; });
2369 for (
auto action : completed) {
2371 O2_SIGNPOST_START(device, aid,
"device",
"Processing action on slot %lu for action %{public}s", action.slot.index, fmt::format(
"{}", action.op).c_str());
2379 prepareAllocatorForCurrentTimeSlice(
TimesliceSlot{action.slot});
2385 InputSpan span = getInputSpan(action.slot, shouldConsume);
2395 dpContext.preProcessingCallbacks(processContext);
2398 context.postDispatchingCallbacks(processContext);
2399 if (spec.forwards.empty() ==
false) {
2401 forwardInputs(
ref, action.slot, currentSetOfInputs, timesliceIndex.getOldestPossibleOutput(),
false);
2402 O2_SIGNPOST_END(device, aid,
"device",
"Forwarding inputs consume: %d.",
false);
2410 bool hasForwards = spec.forwards.empty() ==
false;
2414 O2_SIGNPOST_EVENT_EMIT(device, aid,
"device",
"Early forwarding: %{public}s.", fmt::format(
"{}", action.op).c_str());
2425 O2_SIGNPOST_EVENT_EMIT(device, aid,
"device",
"cleaning early forwarding: %{public}s.", fmt::format(
"{}", action.op).c_str());
2430 markInputsAsDone(action.slot);
2432 uint64_t tStart = uv_hrtime();
2434 preUpdateStats(action, record, tStart);
2436 static bool noCatch = getenv(
"O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv(
"O2_NO_CATCHALL_EXCEPTIONS"),
"0");
2444 switch (action.op) {
2455 if (
state.quitRequested ==
false) {
2459 streamContext.preProcessingCallbacks(processContext);
2465 if (context.statefulProcess && shouldProcess(action)) {
2469 (context.statefulProcess)(processContext);
2471 }
else if (context.statelessProcess && shouldProcess(action)) {
2473 (context.statelessProcess)(processContext);
2475 }
else if (context.statelessProcess || context.statefulProcess) {
2478 O2_SIGNPOST_EVENT_EMIT(device, pcid,
"device",
"No processing callback provided. Switching to %{public}s.",
"Idle");
2481 if (shouldProcess(action)) {
2483 if (timingInfo.globalRunNumberChanged) {
2484 context.lastRunNumberProcessed = timingInfo.runNumber;
2501 streamContext.finaliseOutputsCallbacks(processContext);
2507 streamContext.postProcessingCallbacks(processContext);
2513 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
2514 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
2520 (context.errorHandling)(e, record);
2525 }
catch (std::exception& ex) {
2530 (context.errorHandling)(e, record);
2532 (context.errorHandling)(e, record);
2535 if (
state.severityStack.empty() ==
false) {
2536 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
2537 state.severityStack.pop_back();
2540 postUpdateStats(action, record, tStart, tStartMilli);
2544 cleanupRecord(record);
2545 context.postDispatchingCallbacks(processContext);
2553 context.postForwardingCallbacks(processContext);
2555 cleanTimers(action.slot, record);
2557 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());
2559 O2_SIGNPOST_END(device, sid,
"device",
"Start processing ready actions");
2563 LOGP(detail,
"Broadcasting end of stream");
2564 for (
auto& channel : spec.outputChannels) {
2587 cfg.getRecursive(
name);
2588 std::vector<std::unique_ptr<ParamRetriever>> retrievers;
2589 retrievers.emplace_back(std::make_unique<ConfigurationOptionsRetriever>(&cfg,
name));
2590 auto configStore = std::make_unique<ConfigParamStore>(options, std::move(retrievers));
2591 configStore->preload();
2592 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_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)
DataProcessingDevice(RunningDeviceRef ref, ServiceRegistry &)
static void doPrepare(ServiceRegistryRef)
static bool tryDispatchComputation(ServiceRegistryRef ref, std::vector< DataRelayer::RecordAction > &completed)
static void handleData(ServiceRegistryRef, InputChannelInfo &)
uint32_t getFirstTFOrbitForSlot(TimesliceSlot slot)
Get the firstTForbit associate to a given slot.
void updateCacheStatus(TimesliceSlot slot, CacheEntryStatus oldStatus, CacheEntryStatus newStatus)
uint32_t getRunNumberForSlot(TimesliceSlot slot)
Get the runNumber associated to a given slot.
void prunePending(OnDropCallback)
Prune all the pending entries in the cache.
std::vector< std::vector< fair::mq::MessagePtr > > consumeAllInputsForTimeslice(TimesliceSlot id)
uint64_t getCreationTimeForSlot(TimesliceSlot slot)
Get the creation time associated to a given slot.
ActivityStats processDanglingInputs(std::vector< ExpirationHandler > const &, ServiceRegistryRef context, bool createNew)
uint32_t getFirstTFCounterForSlot(TimesliceSlot slot)
Get the firstTFCounter associate to a given slot.
A service API to communicate with the driver.
virtual fair::mq::Device * device()=0
bool active() const
Check if service of type T is currently active.
OldestOutputInfo getOldestPossibleOutput() const
GLuint const GLchar * name
GLboolean GLboolean GLboolean b
GLsizei const GLfloat * value
GLint GLint GLsizei GLint GLenum GLenum type
GLuint GLsizei GLsizei * length
GLuint GLsizei const GLchar * label
GLsizei GLenum const void * indices
typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode)
GLuint GLsizei const GLchar * message
GLboolean GLboolean GLboolean GLboolean a
Defining ITS Vertex 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)
void on_socket_polled(uv_poll_t *poller, int status, int events)
void run_callback(uv_work_t *handle)
auto forwardOnInsertion(ServiceRegistryRef &ref, std::span< fair::mq::MessagePtr > &messages) -> void
volatile int region_read_global_dummy_variable
void handleRegionCallbacks(ServiceRegistryRef registry, std::vector< fair::mq::RegionInfo > &infos)
Invoke the callbacks for the mPendingRegionInfos.
void on_out_of_band_polled(uv_poll_t *poller, int status, int events)
DeviceSpec const & getRunningDevice(RunningDeviceRef const &running, ServiceRegistryRef const &services)
@ EndOfStreaming
End of streaming requested, but not notified.
@ Streaming
Data is being processed.
@ Idle
End of streaming notified.
void on_communication_requested(uv_async_t *s)
@ Expired
A transition needs to be fullfilled ASAP.
@ NoTransition
No pending transitions.
@ Requested
A transition was notified to be requested.
@ AtCompletionPolicySatisified
RuntimeError & error_from_ref(RuntimeErrorRef)
void on_awake_main_thread(uv_async_t *handle)
@ SHM_OFFER_BYTES_CONSUMED
@ TIMESLICE_NUMBER_EXPIRED
@ TIMESLICE_OFFER_NUMBER_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.
constexpr const char * channelName(int channel)
a couple of static helper functions to create timestamp values for CCDB queries or override obsolete ...
static void run(AsyncQueue &queue, TimesliceId oldestPossibleTimeslice)
static void post(AsyncQueue &queue, AsyncTask const &task)
An actuatual task to be executed.
static void demangled_backtrace_symbols(void **backtrace, unsigned int total, int fd)
static constexpr int INVALID
CompletionOp
Action to take with the InputRecord:
@ Retry
Like Wait but mark the cacheline as dirty.
int64_t timeslices
How many timeslices it can process without giving back control.
int64_t sharedMemory
How much shared memory it can allocate.
Statistics on the offers consumed, expired.
static bool hasOnlyGenerated(DeviceSpec const &spec)
check if spec is a source devide
static TransitionHandlingState updateStateTransition(ServiceRegistryRef const &ref, ProcessingPolicies const &policies)
starts the EoS timers and returns the new TransitionHandlingState in case as new state is requested
static void switchState(ServiceRegistryRef const &ref, StreamingState newState)
change the device StreamingState to newState
static void sendEndOfStream(ServiceRegistryRef const &ref, OutputChannelSpec const &channel)
static bool sendOldestPossibleTimeframe(ServiceRegistryRef const &ref, ForwardChannelInfo const &info, ForwardChannelState &state, size_t timeslice)
static void cleanForwardedMessages(std::span< fair::mq::MessagePtr > ¤tSetOfInputs, bool consume)
static std::vector< fair::mq::Parts > routeForwardedMessageSet(FairMQDeviceProxy &proxy, std::vector< std::vector< fair::mq::MessagePtr > > ¤tSetOfInputs, bool copy, bool consume)
Helper to route messages for forwarding.
static void routeForwardedMessages(FairMQDeviceProxy &proxy, std::span< fair::mq::MessagePtr > ¤tSetOfInputs, std::vector< fair::mq::Parts > &forwardedParts, bool copy, bool consume)
Helper to route messages for forwarding.
Helper struct to hold statistics about the data processing happening.
@ CumulativeRate
Set the value to the specified value if it is positive.
@ Add
Update the rate of the metric given the amount since the last time.
void updateStats(CommandSpec cmd)
std::function< void(o2::framework::RuntimeErrorRef e, InputRecord &record)> errorHandling
ForwardPolicy forwardPolicy
Wether or not the associated DataProcessor can forward things early.
AlgorithmSpec::InitErrorCallback initError
void preLoopCallbacks(ServiceRegistryRef)
Invoke callbacks before we enter the event loop.
void postStopCallbacks(ServiceRegistryRef)
Invoke callbacks on stop.
void preProcessingCallbacks(ProcessingContext &)
Invoke callbacks to be executed before every process method invokation.
ServiceRegistry * registry
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 &)
@ Invalid
Ownership of the data has been taken.
@ Backpressured
The incoming data was not valid and has been dropped.
@ Dropped
The incoming data was not relayed, because we are backpressured.
static bool partialMatch(InputSpec const &spec, o2::header::DataOrigin const &origin)
static std::string describe(InputSpec const &spec)
static bool match(InputSpec const &spec, ConcreteDataMatcher const &target)
TimesliceIndex::OldestOutputInfo oldestTimeslice
static unsigned int pipelineLength(unsigned int minLength)
get max number of timeslices in the queue
static std::unique_ptr< ConfigParamStore > getConfiguration(ServiceRegistryRef registry, const char *name, std::vector< ConfigParamSpec > const &options)
uv_signal_t * sigusr1Handle
ProcessingPolicies & processingPolicies
int expectedRegionCallbacks
Running state information of a given device.
uv_async_t * awakeMainThread
std::atomic< int64_t > cleanupCount
Forward channel information.
InputChannelInfo * channelInfo
fair::mq::Socket * socket
DataProcessingDevice * device
enum EarlyForwardPolicy earlyForward
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