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);
190 auto* poolSizeEnv = getenv(
"DPL_THREADPOOL_SIZE");
194 size_t numStreams = poolSizeEnv ? std::max(0, std::atoi(poolSizeEnv)) : 0;
195 mStreams.resize(std::max(numStreams, 1UL));
196 mHandles.resize(std::max(numStreams, 1UL));
204 mAwakeHandle->data = &
state;
206 LOG(
error) <<
"Unable to initialise subscription";
210 SubscribeToNewTransition(
"dpl", [wakeHandle = mAwakeHandle](fair::mq::Transition t) {
211 int res = uv_async_send(wakeHandle);
213 LOG(
error) <<
"Unable to notify subscription";
215 LOG(
debug) <<
"State transition requested";
228 O2_SIGNPOST_START(device, sid,
"run_callback",
"Starting run callback on stream %d", task->id.index);
230 O2_SIGNPOST_END(device, sid,
"run_callback",
"Done processing data for stream %d", task->id.index);
243 using o2::monitoring::Metric;
244 using o2::monitoring::Monitoring;
245 using o2::monitoring::tags::Key;
246 using o2::monitoring::tags::Value;
250 stats.totalConsumedBytes += accumulatedConsumed.
sharedMemory;
253 stats.totalConsumedTimeslices += std::min<int64_t>(accumulatedConsumed.
timeslices, 1);
257 dpStats.processCommandQueue();
267 dpStats.processCommandQueue();
270 for (
auto& consumer :
state.offerConsumers) {
271 quotaEvaluator.consume(task->id.index, consumer, reportConsumedOffer);
273 state.offerConsumers.clear();
274 quotaEvaluator.handleExpired(reportExpiredOffer);
275 quotaEvaluator.dispose(task->id.index);
276 task->running =
false;
304 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"Data pending on socket for channel %{public}s", context->name);
308 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"Socket connected for channel %{public}s", context->name);
310 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"Socket connected for read in context %{public}s", context->name);
311 uv_poll_start(poller, UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED, &
on_socket_polled);
314 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"Socket connected for write for channel %{public}s", context->name);
322 case UV_DISCONNECT: {
323 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"Socket disconnected in context %{public}s", context->name);
325 case UV_PRIORITIZED: {
326 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"Socket prioritized for context %{public}s", context->name);
338 LOGP(fatal,
"Error while polling {}: {}", context->name, status);
343 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"Data pending on socket for channel %{public}s", context->name);
345 assert(context->channelInfo);
346 context->channelInfo->readPolled =
true;
349 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"OOB socket connected for channel %{public}s", context->name);
351 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"OOB socket connected for read in context %{public}s", context->name);
354 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"OOB socket connected for write for channel %{public}s", context->name);
358 case UV_DISCONNECT: {
359 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"OOB socket disconnected in context %{public}s", context->name);
362 case UV_PRIORITIZED: {
363 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"OOB socket prioritized for context %{public}s", context->name);
384 context.statelessProcess = spec.algorithm.onProcess;
386 context.error = spec.algorithm.onError;
387 context.
initError = spec.algorithm.onInitError;
390 if (configStore ==
nullptr) {
391 std::vector<std::unique_ptr<ParamRetriever>> retrievers;
392 retrievers.emplace_back(std::make_unique<FairOptionsRetriever>(GetConfig()));
393 configStore = std::make_unique<ConfigParamStore>(spec.options, std::move(retrievers));
394 configStore->preload();
395 configStore->activate();
398 using boost::property_tree::ptree;
401 for (
auto&
entry : configStore->store()) {
402 std::stringstream ss;
404 if (
entry.second.empty() ==
false) {
405 boost::property_tree::json_parser::write_json(ss,
entry.second,
false);
408 str =
entry.second.get_value<std::string>();
410 std::string configString = fmt::format(
"[CONFIG] {}={} 1 {}",
entry.first,
str, configStore->provenance(
entry.first.c_str())).c_str();
414 mConfigRegistry = std::make_unique<ConfigParamRegistry>(std::move(configStore));
417 if (context.initError) {
418 context.initErrorHandling = [&errorCallback = context.initError,
431 errorCallback(errorContext);
434 context.initErrorHandling = [&serviceRegistry = mServiceRegistry](
RuntimeErrorRef e) {
449 context.expirationHandlers.clear();
450 context.init = spec.algorithm.onInit;
452 static bool noCatch = getenv(
"O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv(
"O2_NO_CATCHALL_EXCEPTIONS"),
"0");
453 InitContext initContext{*mConfigRegistry, mServiceRegistry};
457 context.statefulProcess = context.init(initContext);
459 if (context.initErrorHandling) {
460 (context.initErrorHandling)(e);
465 context.statefulProcess = context.init(initContext);
466 }
catch (std::exception& ex) {
471 (context.initErrorHandling)(e);
473 (context.initErrorHandling)(e);
478 state.inputChannelInfos.resize(spec.inputChannels.size());
482 int validChannelId = 0;
483 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
484 auto&
name = spec.inputChannels[ci].name;
485 if (
name.find(spec.channelPrefix +
"from_internal-dpl-clock") == 0) {
490 state.inputChannelInfos[ci].id = {validChannelId++};
495 if (spec.callbacksPolicy.policy !=
nullptr) {
496 InitContext initContext{*mConfigRegistry, mServiceRegistry};
501 auto* options = GetConfig();
502 for (
size_t si = 0; si < mStreams.size(); ++si) {
516 O2_SIGNPOST_END(device, sid,
"signal_state",
"No registry active. Ignoring signal.");
525 while (ri != quotaEvaluator.mOffers.size()) {
526 auto& offer = quotaEvaluator.mOffers[ri];
532 if (offer.valid && offer.sharedMemory != 0) {
533 O2_SIGNPOST_END(device, sid,
"signal_state",
"Memory already offered.");
539 for (
auto& offer : quotaEvaluator.mOffers) {
540 if (offer.valid ==
false) {
543 offer.sharedMemory = 1000000000;
550 O2_SIGNPOST_END(device, sid,
"signal_state",
"Done processing signals.");
564 if (oldestTimeslice.timeslice.value <= decongestion.lastTimeslice) {
565 LOG(
debug) <<
"Not sending already sent oldest possible timeslice " << oldestTimeslice.timeslice.value;
568 for (
int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
569 auto& info = proxy.getForwardChannelInfo(
ChannelIndex{fi});
574 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputsCallback",
"Skipping channel %{public}s because it's not a DPL channel",
580 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputsCallback",
"Forwarding to channel %{public}s oldest possible timeslice %zu, prio 20",
581 info.name.c_str(), oldestTimeslice.timeslice.value);
595 O2_SIGNPOST_START(forwarding, sid,
"forwardInputs",
"Starting forwarding for slot %zu with oldestTimeslice %zu %{public}s%{public}s%{public}s",
596 slot.index, oldestTimeslice.timeslice.value, copy ?
"with copy" :
"", copy && consume ?
" and " :
"", consume ?
"with consume" :
"");
599 for (
int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
600 if (forwardedParts[fi].
Size() == 0) {
604 auto& parts = forwardedParts[fi];
605 if (
info.policy ==
nullptr) {
616 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputs",
"Queuing forwarding oldestPossible %zu", oldestTimeslice.timeslice.value);
627 O2_SIGNPOST_START(forwarding, sid,
"forwardInputs",
"Cleaning up slot %zu with oldestTimeslice %zu %{public}s%{public}s%{public}s",
628 slot.index, oldestTimeslice.timeslice.value, copy ?
"with copy" :
"", copy && consume ?
" and " :
"", consume ?
"with consume" :
"");
631 for (
size_t ii = 0, ie = currentSetOfInputs.size(); ii < ie; ++ii) {
632 auto span = std::span<fair::mq::MessagePtr>(currentSetOfInputs[ii]);
645 if (infos.empty() ==
false) {
646 std::vector<fair::mq::RegionInfo> toBeNotified;
647 toBeNotified.swap(infos);
648 static bool dummyRead = getenv(
"DPL_DEBUG_MAP_ALL_SHM_REGIONS") && atoi(getenv(
"DPL_DEBUG_MAP_ALL_SHM_REGIONS"));
649 for (
auto const& info : toBeNotified) {
669void DataProcessingDevice::initPollers()
677 if ((context.statefulProcess !=
nullptr) || (context.statelessProcess !=
nullptr)) {
678 for (
auto& [channelName, channel] : GetChannels()) {
680 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
681 auto& channelSpec = spec.inputChannels[ci];
682 channelInfo = &
state.inputChannelInfos[ci];
683 if (channelSpec.name != channelName) {
686 channelInfo->
channel = &this->GetChannel(channelName, 0);
689 if ((
channelName.rfind(
"from_internal-dpl", 0) == 0) &&
690 (
channelName.rfind(
"from_internal-dpl-aod", 0) != 0) &&
691 (
channelName.rfind(
"from_internal-dpl-ccdb-backend", 0) != 0) &&
692 (
channelName.rfind(
"from_internal-dpl-injected", 0)) != 0) {
693 LOGP(detail,
"{} is an internal channel. Skipping as no input will come from there.", channelName);
697 if (
channelName.rfind(
"from_" + spec.name +
"_", 0) == 0) {
698 LOGP(detail,
"{} is to send data. Not polling.", channelName);
703 LOGP(detail,
"{} is not a DPL socket. Not polling.", channelName);
709 size_t zmq_fd_len =
sizeof(zmq_fd);
712 channel[0].GetSocket().GetOption(
"fd", &zmq_fd, &zmq_fd_len);
717 LOGP(detail,
"Polling socket for {}", channelName);
720 pCtx->loop =
state.loop;
722 pCtx->state = &
state;
724 assert(channelInfo !=
nullptr);
725 pCtx->channelInfo = channelInfo;
726 pCtx->socket = &channel[0].GetSocket();
729 uv_poll_init(
state.loop, poller, zmq_fd);
731 LOGP(detail,
"{} is an out of band channel.", channelName);
732 state.activeOutOfBandPollers.push_back(poller);
735 state.activeInputPollers.push_back(poller);
741 if (
state.activeInputPollers.empty() &&
742 state.activeOutOfBandPollers.empty() &&
743 state.activeTimers.empty() &&
744 state.activeSignals.empty()) {
748 if (
state.inputChannelInfos.empty()) {
749 LOGP(detail,
"No input channels. Setting exit transition timeout to 0.");
750 deviceContext.exitTransitionTimeout = 0;
752 for (
auto& [channelName, channel] : GetChannels()) {
753 if (
channelName.rfind(spec.channelPrefix +
"from_internal-dpl", 0) == 0) {
754 LOGP(detail,
"{} is an internal channel. Not polling.", channelName);
757 if (
channelName.rfind(spec.channelPrefix +
"from_" + spec.name +
"_", 0) == 0) {
758 LOGP(detail,
"{} is an out of band channel. Not polling for output.", channelName);
763 size_t zmq_fd_len =
sizeof(zmq_fd);
766 channel[0].GetSocket().GetOption(
"fd", &zmq_fd, &zmq_fd_len);
768 LOGP(
error,
"Cannot get file descriptor for channel {}", channelName);
771 LOG(detail) <<
"Polling socket for " << channel[0].GetName();
775 pCtx->loop =
state.loop;
777 pCtx->state = &
state;
781 uv_poll_init(
state.loop, poller, zmq_fd);
782 state.activeOutputPollers.push_back(poller);
786 LOGP(detail,
"This is a fake device so we exit after the first iteration.");
787 deviceContext.exitTransitionTimeout = 0;
793 uv_timer_init(
state.loop, timer);
794 timer->data = &
state;
795 uv_update_time(
state.loop);
797 state.activeTimers.push_back(timer);
801void DataProcessingDevice::startPollers()
807 for (
auto* poller :
state.activeInputPollers) {
809 O2_SIGNPOST_START(device, sid,
"socket_state",
"Input socket waiting for connection.");
813 for (
auto& poller :
state.activeOutOfBandPollers) {
817 for (
auto* poller :
state.activeOutputPollers) {
819 O2_SIGNPOST_START(device, sid,
"socket_state",
"Output socket waiting for connection.");
826 uv_timer_init(
state.loop, deviceContext.gracePeriodTimer);
829 deviceContext.dataProcessingGracePeriodTimer->data =
new ServiceRegistryRef(mServiceRegistry);
830 uv_timer_init(
state.loop, deviceContext.dataProcessingGracePeriodTimer);
833void DataProcessingDevice::stopPollers()
838 LOGP(detail,
"Stopping {} input pollers",
state.activeInputPollers.size());
839 for (
auto* poller :
state.activeInputPollers) {
842 uv_poll_stop(poller);
845 LOGP(detail,
"Stopping {} out of band pollers",
state.activeOutOfBandPollers.size());
846 for (
auto* poller :
state.activeOutOfBandPollers) {
847 uv_poll_stop(poller);
850 LOGP(detail,
"Stopping {} output pollers",
state.activeOutOfBandPollers.size());
851 for (
auto* poller :
state.activeOutputPollers) {
854 uv_poll_stop(poller);
858 uv_timer_stop(deviceContext.gracePeriodTimer);
860 free(deviceContext.gracePeriodTimer);
861 deviceContext.gracePeriodTimer =
nullptr;
863 uv_timer_stop(deviceContext.dataProcessingGracePeriodTimer);
865 free(deviceContext.dataProcessingGracePeriodTimer);
866 deviceContext.dataProcessingGracePeriodTimer =
nullptr;
881 for (
auto&
di : distinct) {
882 auto& route = spec.inputs[
di];
883 if (route.configurator.has_value() ==
false) {
888 .
name = route.configurator->name,
890 .lifetime = route.matcher.lifetime,
891 .creator = route.configurator->creatorConfigurator(
state, mServiceRegistry, *mConfigRegistry),
892 .checker = route.configurator->danglingConfigurator(
state, *mConfigRegistry),
893 .handler = route.configurator->expirationConfigurator(
state, *mConfigRegistry)};
894 context.expirationHandlers.emplace_back(std::move(handler));
897 if (
state.awakeMainThread ==
nullptr) {
903 deviceContext.expectedRegionCallbacks = std::stoi(fConfig->GetValue<std::string>(
"expected-region-callbacks"));
904 deviceContext.exitTransitionTimeout = std::stoi(fConfig->GetValue<std::string>(
"exit-transition-timeout"));
905 deviceContext.dataProcessingTimeout = std::stoi(fConfig->GetValue<std::string>(
"data-processing-timeout"));
907 for (
auto& channel : GetChannels()) {
908 channel.second.at(0).Transport()->SubscribeToRegionEvents([&context = deviceContext,
909 ®istry = mServiceRegistry,
910 &pendingRegionInfos = mPendingRegionInfos,
911 ®ionInfoMutex = mRegionInfoMutex](fair::mq::RegionInfo info) {
912 std::lock_guard<std::mutex> lock(regionInfoMutex);
913 LOG(detail) <<
">>> Region info event" << info.event;
914 LOG(detail) <<
"id: " << info.id;
915 LOG(detail) <<
"ptr: " << info.ptr;
916 LOG(detail) <<
"size: " << info.size;
917 LOG(detail) <<
"flags: " << info.flags;
920 pendingRegionInfos.push_back(info);
933 if (deviceContext.sigusr1Handle ==
nullptr) {
935 deviceContext.sigusr1Handle->data = &mServiceRegistry;
936 uv_signal_init(
state.loop, deviceContext.sigusr1Handle);
940 for (
auto& handle :
state.activeSignals) {
941 handle->data = &
state;
944 deviceContext.sigusr1Handle->data = &mServiceRegistry;
947 DataProcessingDevice::initPollers();
955 LOG(
error) <<
"DataProcessor " <<
state.lastActiveDataProcessor.load()->spec->name <<
" was unexpectedly active";
967 O2_SIGNPOST_END(device, cid,
"InitTask",
"Exiting InitTask callback waiting for the remaining region callbacks.");
969 auto hasPendingEvents = [&mutex = mRegionInfoMutex, &pendingRegionInfos = mPendingRegionInfos](
DeviceContext& deviceContext) {
970 std::lock_guard<std::mutex> lock(mutex);
971 return (pendingRegionInfos.empty() ==
false) || deviceContext.expectedRegionCallbacks > 0;
978 while (hasPendingEvents(deviceContext)) {
980 uv_run(
state.loop, UV_RUN_ONCE);
984 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
988 O2_SIGNPOST_END(device, cid,
"InitTask",
"Done waiting for registration events.");
995 bool enableRateLimiting = std::stoi(fConfig->GetValue<std::string>(
"timeframes-rate-limit"));
1004 if (enableRateLimiting ==
false && spec.name.find(
"internal-dpl-injected-dummy-sink") != std::string::npos) {
1007 if (enableRateLimiting) {
1008 for (
auto& spec : spec.outputs) {
1009 if (spec.matcher.binding.value ==
"dpl-summary") {
1016 context.
registry = &mServiceRegistry;
1019 if (context.
error !=
nullptr) {
1033 errorCallback(errorContext);
1047 switch (deviceContext.processingPolicies.
error) {
1058 auto decideEarlyForward = [&context, &deviceContext, &spec,
this]() ->
ForwardPolicy {
1066 for (
auto& forward : spec.forwards) {
1078 for (
auto&
label : spec.labels) {
1079 if (
label.value ==
"output-proxy") {
1088 if (spec.forwards.empty() ==
false) {
1094 forwardPolicy = defaultEarlyForwardPolicy;
1097 forwardPolicy = defaultEarlyForwardPolicy;
1101 bool onlyConditions =
true;
1102 bool overriddenEarlyForward =
false;
1103 for (
auto& forwarded : spec.forwards) {
1104 if (forwarded.matcher.lifetime != Lifetime::Condition) {
1105 onlyConditions =
false;
1109 overriddenEarlyForward =
true;
1113 if (forwarded.matcher.lifetime == Lifetime::Optional) {
1115 overriddenEarlyForward =
true;
1120 if (!overriddenEarlyForward && onlyConditions) {
1121 forwardPolicy = defaultEarlyForwardPolicy;
1122 LOG(detail) <<
"Enabling early forwarding because only conditions to be forwarded";
1124 return forwardPolicy;
1136 state.quitRequested =
false;
1139 for (
auto& info :
state.inputChannelInfos) {
1151 for (
size_t i = 0;
i < mStreams.size(); ++
i) {
1154 context.preStartStreamCallbacks(streamRef);
1156 }
catch (std::exception& e) {
1157 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"PreRun",
"Exception of type std::exception caught in PreRun: %{public}s. Rethrowing.", e.what());
1158 O2_SIGNPOST_END(device, cid,
"PreRun",
"Exiting PreRun due to exception thrown.");
1162 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"PreRun",
"Exception of type o2::framework::RuntimeErrorRef caught in PreRun: %{public}s. Rethrowing.", err.what);
1163 O2_SIGNPOST_END(device, cid,
"PreRun",
"Exiting PreRun due to exception thrown.");
1166 O2_SIGNPOST_END(device, cid,
"PreRun",
"Unknown exception being thrown. Rethrowing.");
1174 using o2::monitoring::Metric;
1175 using o2::monitoring::Monitoring;
1176 using o2::monitoring::tags::Key;
1177 using o2::monitoring::tags::Value;
1180 monitoring.send(
Metric{(uint64_t)1,
"device_state"}.addTag(Key::Subsystem, Value::DPL));
1188 using o2::monitoring::Metric;
1189 using o2::monitoring::Monitoring;
1190 using o2::monitoring::tags::Key;
1191 using o2::monitoring::tags::Value;
1194 monitoring.send(
Metric{(uint64_t)0,
"device_state"}.addTag(Key::Subsystem, Value::DPL));
1213 bool firstLoop =
true;
1215 O2_SIGNPOST_START(device, lid,
"device_state",
"First iteration of the device loop");
1217 auto* poolSizeEnv = getenv(
"DPL_THREADPOOL_SIZE");
1218 bool dplEnableMultithreding = poolSizeEnv && std::atoi(poolSizeEnv) > 0;
1221 if (
state.nextFairMQState.empty() ==
false) {
1222 (
void)this->ChangeState(
state.nextFairMQState.back());
1223 state.nextFairMQState.pop_back();
1228 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1241 state.lastActiveDataProcessor.compare_exchange_strong(lastActive,
nullptr);
1243 auto shouldNotWait = (lastActive !=
nullptr &&
1247 shouldNotWait =
true;
1250 if (lastActive !=
nullptr) {
1253 if (NewStatePending()) {
1255 shouldNotWait =
true;
1261 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"State transition requested and we are now in Idle. We can consider it to be completed.");
1264 if (
state.severityStack.empty() ==
false) {
1265 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
1266 state.severityStack.pop_back();
1272 state.firedTimers.clear();
1274 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
1275 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
1282 O2_SIGNPOST_START(device, lid,
"run_loop",
"Dropping message from slot %" PRIu64
". Forwarding as needed.", (uint64_t)slot.index);
1290 forwardInputs(registry, slot, dropped, oldestOutputInfo,
false,
true);
1295 auto oldestPossibleTimeslice = relayer.getOldestPossibleOutput();
1297 if (shouldNotWait ==
false) {
1301 O2_SIGNPOST_END(device, lid,
"run_loop",
"Run loop completed. %{}s", shouldNotWait ?
"Will immediately schedule a new one" :
"Waiting for next event.");
1302 uv_run(
state.loop, shouldNotWait ? UV_RUN_NOWAIT : UV_RUN_ONCE);
1304 if ((
state.loopReason &
state.tracingFlags) != 0) {
1305 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
1306 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
1307 }
else if (
state.severityStack.empty() ==
false) {
1308 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
1309 state.severityStack.pop_back();
1314 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"Out of band activity detected. Rescanning everything.");
1318 if (!
state.pendingOffers.empty()) {
1319 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"Pending %" PRIu64
" offers. updating the ComputingQuotaEvaluator.", (uint64_t)
state.pendingOffers.size());
1331 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1339 assert(mStreams.size() == mHandles.size());
1342 for (
size_t ti = 0; ti < mStreams.size(); ti++) {
1343 auto& taskInfo = mStreams[ti];
1344 if (taskInfo.running) {
1348 streamRef.index = ti;
1350 using o2::monitoring::Metric;
1351 using o2::monitoring::Monitoring;
1352 using o2::monitoring::tags::Key;
1353 using o2::monitoring::tags::Value;
1356 if (streamRef.index != -1) {
1359 uv_work_t& handle = mHandles[streamRef.index];
1361 handle.data = &mStreams[streamRef.index];
1369 dpStats.processCommandQueue();
1380 struct SchedulingStats {
1381 std::atomic<size_t> lastScheduled = 0;
1382 std::atomic<size_t> numberOfUnscheduledSinceLastScheduled = 0;
1383 std::atomic<size_t> numberOfUnscheduled = 0;
1384 std::atomic<size_t> numberOfScheduled = 0;
1385 std::atomic<size_t> nextWarnAt = 1;
1387 static SchedulingStats schedulingStats;
1392 stream.registry = &mServiceRegistry;
1393 schedulingStats.lastScheduled = uv_now(
state.loop);
1394 schedulingStats.numberOfScheduled++;
1395 schedulingStats.numberOfUnscheduledSinceLastScheduled = 0;
1396 schedulingStats.nextWarnAt = 1;
1397 O2_SIGNPOST_EVENT_EMIT(scheduling, sid,
"Run",
"Enough resources to schedule computation on stream %d", streamRef.index);
1398 if (dplEnableMultithreding) [[unlikely]] {
1406 auto const lastSched = schedulingStats.lastScheduled.load();
1407 auto const schedInfo = lastSched ? fmt::format(
", last scheduled {} ms ago", uv_now(
state.loop) - lastSched) : std::string(
", never successfully scheduled");
1408 auto const buildMissingInfo = [&]() {
1409 auto const& required = spec.resourcePolicy.minRequired;
1410 std::string missingInfo;
1411 if (required.sharedMemory > 0 && accumulated.sharedMemory < required.sharedMemory) {
1412 missingInfo += fmt::format(
" shared memory (have {} MB, need {} MB)", accumulated.sharedMemory / 1000000, required.sharedMemory / 1000000);
1414 if (required.timeslices > 0 && accumulated.timeslices < required.timeslices) {
1415 missingInfo += fmt::format(
" timeslices (have {}, need {})", accumulated.timeslices, required.timeslices);
1417 if (required.cpu > 0 && accumulated.cpu < required.cpu) {
1418 missingInfo += fmt::format(
" CPU cores (have {}, need {})", accumulated.cpu, required.cpu);
1420 if (required.memory > 0 && accumulated.memory < required.memory) {
1421 missingInfo += fmt::format(
" memory (have {} MB, need {} MB)", accumulated.memory / 1000000, required.memory / 1000000);
1423 return missingInfo.empty() ? std::string(
" (policy: ") + spec.resourcePolicy.name +
")" :
" -" + missingInfo;
1425 auto const timeSinceLastScheduled = lastSched ? uv_now(
state.loop) - lastSched : 0;
1426 if (schedulingStats.numberOfUnscheduledSinceLastScheduled >= schedulingStats.nextWarnAt) {
1427 auto const missingStr = buildMissingInfo();
1428 if (timeSinceLastScheduled >= 50) {
1430 "Not enough resources to schedule computation on stream %d. %zu consecutive skips%s. Missing:%s. Data is not lost and it will be scheduled again.",
1432 schedulingStats.numberOfUnscheduledSinceLastScheduled.load(),
1434 missingStr.c_str());
1437 "Not enough resources to schedule computation on stream %d. %zu consecutive skips%s. Missing:%s. Data is not lost and it will be scheduled again.",
1439 schedulingStats.numberOfUnscheduledSinceLastScheduled.load(),
1441 missingStr.c_str());
1443 schedulingStats.nextWarnAt = schedulingStats.nextWarnAt * 2;
1445 auto const missingStr = buildMissingInfo();
1447 "Not enough resources to schedule computation on stream %d. %zu consecutive skips%s. Missing:%s. Data is not lost and it will be scheduled again.",
1449 schedulingStats.numberOfUnscheduledSinceLastScheduled.load(),
1451 missingStr.c_str());
1453 schedulingStats.numberOfUnscheduled++;
1454 schedulingStats.numberOfUnscheduledSinceLastScheduled++;
1461 O2_SIGNPOST_END(device, lid,
"run_loop",
"Run loop completed. Transition handling state %d.", (
int)
state.transitionHandling);
1464 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
1465 auto& info =
state.inputChannelInfos[ci];
1466 info.parts.fParts.clear();
1477 O2_SIGNPOST_START(device, dpid,
"do_prepare",
"Starting DataProcessorContext::doPrepare.");
1495 context.allDone = std::any_of(
state.inputChannelInfos.begin(),
state.inputChannelInfos.end(), [cid](
const auto& info) {
1497 O2_SIGNPOST_EVENT_EMIT(device, cid,
"do_prepare",
"Input channel %{public}s%{public}s has %zu parts left and is in state %d.",
1498 info.channel->GetName().c_str(), (info.id.value == ChannelIndex::INVALID ?
" (non DPL)" :
""), info.parts.fParts.size(), (int)info.state);
1500 O2_SIGNPOST_EVENT_EMIT(device, cid,
"do_prepare",
"External channel %d is in state %d.", info.id.value, (int)info.state);
1505 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"do_prepare",
"Processing %zu input channels.", spec.inputChannels.size());
1508 static std::vector<int> pollOrder;
1509 pollOrder.resize(
state.inputChannelInfos.size());
1510 std::iota(pollOrder.begin(), pollOrder.end(), 0);
1511 std::sort(pollOrder.begin(), pollOrder.end(), [&infos =
state.inputChannelInfos](
int a,
int b) {
1512 return infos[a].oldestForChannel.value < infos[b].oldestForChannel.value;
1516 if (pollOrder.empty()) {
1517 O2_SIGNPOST_END(device, dpid,
"do_prepare",
"Nothing to poll. Waiting for next iteration.");
1520 auto currentOldest =
state.inputChannelInfos[pollOrder.front()].oldestForChannel;
1521 auto currentNewest =
state.inputChannelInfos[pollOrder.back()].oldestForChannel;
1522 auto delta = currentNewest.value - currentOldest.value;
1523 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"do_prepare",
"Oldest possible timeframe range %" PRIu64
" => %" PRIu64
" delta %" PRIu64,
1524 (int64_t)currentOldest.value, (int64_t)currentNewest.value, (int64_t)delta);
1525 auto& infos =
state.inputChannelInfos;
1527 if (context.balancingInputs) {
1529 static uint64_t ahead = getenv(
"DPL_MAX_CHANNEL_AHEAD") ? std::atoll(getenv(
"DPL_MAX_CHANNEL_AHEAD")) :
std::
max(8,
std::
min(pipelineLength - 48, pipelineLength / 2));
1530 auto newEnd = std::remove_if(pollOrder.begin(), pollOrder.end(), [&infos, limitNew = currentOldest.value + ahead](
int a) ->
bool {
1531 return infos[a].oldestForChannel.value > limitNew;
1533 for (
auto it = pollOrder.begin(); it < pollOrder.end(); it++) {
1534 const auto& channelInfo =
state.inputChannelInfos[*it];
1540 bool shouldBeRunning = it < newEnd;
1541 if (running != shouldBeRunning) {
1542 uv_poll_start(poller, shouldBeRunning ? UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED : 0, &
on_socket_polled);
1548 pollOrder.erase(newEnd, pollOrder.end());
1550 O2_SIGNPOST_END(device, dpid,
"do_prepare",
"%zu channels pass the channel inbalance balance check.", pollOrder.size());
1552 for (
auto sci : pollOrder) {
1553 auto&
info =
state.inputChannelInfos[sci];
1555 O2_SIGNPOST_START(device, cid,
"channels",
"Processing channel %s",
info.channel->GetName().c_str());
1558 context.allDone =
false;
1563 if (
info.parts.Size()) {
1566 O2_SIGNPOST_END(device, cid,
"channels",
"Flushing channel %s which is in state %d and has %zu parts still pending.",
1567 info.channel->GetName().c_str(), (
int)
info.state,
info.parts.Size());
1570 if (
info.channel ==
nullptr) {
1571 O2_SIGNPOST_END(device, cid,
"channels",
"Channel %s which is in state %d is nullptr and has %zu parts still pending.",
1572 info.channel->GetName().c_str(), (
int)
info.state,
info.parts.Size());
1577 O2_SIGNPOST_END(device, cid,
"channels",
"Channel %s which is in state %d is not a DPL channel and has %zu parts still pending.",
1578 info.channel->GetName().c_str(), (
int)
info.state,
info.parts.Size());
1581 auto& socket =
info.channel->GetSocket();
1586 if (
info.hasPendingEvents == 0) {
1587 socket.Events(&
info.hasPendingEvents);
1589 if ((
info.hasPendingEvents & 1) == 0 && (
info.parts.Size() == 0)) {
1590 O2_SIGNPOST_END(device, cid,
"channels",
"No pending events and no remaining parts to process for channel %{public}s",
info.channel->GetName().c_str());
1596 info.readPolled =
false;
1605 bool newMessages =
false;
1607 O2_SIGNPOST_EVENT_EMIT(device, cid,
"channels",
"Receiving loop called for channel %{public}s (%d) with oldest possible timeslice %zu",
1608 info.channel->GetName().c_str(),
info.id.value,
info.oldestForChannel.value);
1609 if (
info.parts.Size() < 64) {
1610 fair::mq::Parts parts;
1611 info.channel->Receive(parts, 0);
1613 O2_SIGNPOST_EVENT_EMIT(device, cid,
"channels",
"Received %zu parts from channel %{public}s (%d).", parts.Size(),
info.channel->GetName().c_str(),
info.id.value);
1615 for (
auto&& part : parts) {
1616 info.parts.fParts.emplace_back(std::move(part));
1618 newMessages |=
true;
1621 if (
info.parts.Size() >= 0) {
1633 socket.Events(&
info.hasPendingEvents);
1634 if (
info.hasPendingEvents) {
1635 info.readPolled =
false;
1638 state.lastActiveDataProcessor.store(&context);
1641 O2_SIGNPOST_END(device, cid,
"channels",
"Done processing channel %{public}s (%d).",
1642 info.channel->GetName().c_str(),
info.id.value);
1658 streamContext.completed.clear();
1659 streamContext.completed.reserve(16);
1661 state.lastActiveDataProcessor.store(&context);
1665 context.preDanglingCallbacks(danglingContext);
1666 if (
state.lastActiveDataProcessor.load() ==
nullptr) {
1669 auto activity =
ref.get<
DataRelayer>().processDanglingInputs(context.expirationHandlers, *context.registry,
true);
1670 if (activity.expiredSlots > 0) {
1671 state.lastActiveDataProcessor = &context;
1674 streamContext.completed.clear();
1676 state.lastActiveDataProcessor = &context;
1679 context.postDanglingCallbacks(danglingContext);
1687 state.lastActiveDataProcessor = &context;
1710 timingInfo.timeslice = relayer.getOldestPossibleOutput().timeslice.value;
1711 timingInfo.tfCounter = -1;
1712 timingInfo.firstTForbit = -1;
1714 timingInfo.creation = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count();
1715 O2_SIGNPOST_EVENT_EMIT(calibration, dpid,
"calibration",
"TimingInfo.keepAtEndOfStream %d", timingInfo.keepAtEndOfStream);
1719 context.preEOSCallbacks(eosContext);
1724 context.postEOSCallbacks(eosContext);
1726 for (
auto& channel : spec.outputChannels) {
1727 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"state",
"Sending end of stream to %{public}s.", channel.name.c_str());
1734 if (shouldProcess) {
1735 state.lastActiveDataProcessor = &context;
1739 for (
auto& poller :
state.activeOutputPollers) {
1740 uv_poll_stop(poller);
1748 for (
auto& poller :
state.activeOutputPollers) {
1749 uv_poll_stop(poller);
1765 if (deviceContext.sigusr1Handle) {
1771 handle->data =
nullptr;
1792 O2_SIGNPOST_EVENT_EMIT(device, sid,
"device",
"Early forwardinding before injecting data into relayer.");
1799 "Starting forwarding for incoming messages with oldestTimeslice %zu with copy",
1800 oldestTimeslice.timeslice.value);
1801 std::vector<fair::mq::Parts> forwardedParts(proxy.getNumForwardChannels());
1804 for (
int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
1805 if (forwardedParts[fi].
Size() == 0) {
1809 auto& parts = forwardedParts[fi];
1810 if (info.policy ==
nullptr) {
1814 O2_SIGNPOST_EVENT_EMIT(forwarding, sid,
"forwardInputs",
"Forwarding to %{public}s %d", info.name.c_str(), fi);
1820 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputs",
"Queuing forwarding oldestPossible %zu", oldestTimeslice.timeslice.value);
1845 auto getInputTypes = [&info, &context]() -> std::optional<std::vector<InputInfo>> {
1850 auto& parts = info.parts;
1853 std::vector<InputInfo> results;
1855 results.reserve(parts.Size() / 2);
1856 size_t nTotalPayloads = 0;
1860 if (
type != InputType::Invalid &&
length > 1) {
1861 nTotalPayloads +=
length - 1;
1865 for (
size_t pi = 0; pi < parts.Size(); pi += 2) {
1866 auto* headerData = parts.At(pi)->GetData();
1867 auto sih = o2::header::get<SourceInfoHeader*>(headerData);
1868 auto dh = o2::header::get<DataHeader*>(headerData);
1870 O2_SIGNPOST_EVENT_EMIT(device, cid,
"handle_data",
"Got SourceInfoHeader with state %d", (
int)sih->state);
1871 info.state = sih->state;
1872 insertInputInfo(pi, 2, InputType::SourceInfo, info.id);
1873 state.lastActiveDataProcessor = &context;
1875 LOGP(
error,
"Found data attached to a SourceInfoHeader");
1879 auto dih = o2::header::get<DomainInfoHeader*>(headerData);
1881 O2_SIGNPOST_EVENT_EMIT(device, cid,
"handle_data",
"Got DomainInfoHeader with oldestPossibleTimeslice %d", (
int)dih->oldestPossibleTimeslice);
1882 insertInputInfo(pi, 2, InputType::DomainInfo, info.id);
1883 state.lastActiveDataProcessor = &context;
1885 LOGP(
error,
"Found data attached to a DomainInfoHeader");
1890 insertInputInfo(pi, 0, InputType::Invalid, info.id);
1894 if (dh->payloadSize > parts.At(pi + 1)->GetSize()) {
1895 insertInputInfo(pi, 0, InputType::Invalid, info.id);
1899 auto dph = o2::header::get<DataProcessingHeader*>(headerData);
1904 O2_SIGNPOST_START(parts,
pid,
"parts",
"Processing DataHeader %{public}-4s/%{public}-16s/%d with splitPayloadParts %d and splitPayloadIndex %d",
1905 dh->dataOrigin.str, dh->dataDescription.str, dh->subSpecification, dh->splitPayloadParts, dh->splitPayloadIndex);
1907 insertInputInfo(pi, 2, InputType::Invalid, info.id);
1911 if (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) {
1914 insertInputInfo(pi, dh->splitPayloadParts + 1, InputType::Data, info.id);
1915 pi += dh->splitPayloadParts - 1;
1921 size_t finalSplitPayloadIndex = pi + (dh->splitPayloadParts > 0 ? dh->splitPayloadParts : 1) * 2;
1922 if (finalSplitPayloadIndex > parts.Size()) {
1924 insertInputInfo(pi, 0, InputType::Invalid, info.id);
1927 insertInputInfo(pi, 2, InputType::Data, info.id);
1928 for (; pi + 2 < finalSplitPayloadIndex; pi += 2) {
1929 insertInputInfo(pi + 2, 2, InputType::Data, info.id);
1933 if (results.size() + nTotalPayloads != parts.Size()) {
1934 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"handle_data",
"inconsistent number of inputs extracted. %zu vs parts (%zu)", results.size() + nTotalPayloads, parts.Size());
1935 return std::nullopt;
1940 auto reportError = [
ref](
const char*
message) {
1945 auto handleValidMessages = [&info,
ref, &reportError, &context](std::vector<InputInfo>
const& inputInfos) {
1949 auto& parts = info.parts;
1952 bool hasBackpressure =
false;
1953 size_t minBackpressureTimeslice = -1;
1955 size_t oldestPossibleTimeslice = -1;
1956 static std::vector<int> ordering;
1958 ordering.resize(inputInfos.size());
1959 std::iota(ordering.begin(), ordering.end(), 0);
1961 std::stable_sort(ordering.begin(), ordering.end(), [&inputInfos](
int const&
a,
int const&
b) {
1962 auto const& ai = inputInfos[a];
1963 auto const& bi = inputInfos[b];
1964 if (ai.type != bi.type) {
1965 return ai.type < bi.type;
1967 return ai.position < bi.position;
1969 for (
size_t ii = 0; ii < inputInfos.size(); ++ii) {
1970 auto const& input = inputInfos[ordering[ii]];
1971 switch (input.type) {
1972 case InputType::Data: {
1974 auto headerIndex = input.position;
1976 auto nPayloadsPerHeader = 0;
1977 if (input.size > 2) {
1979 nMessages = input.size;
1980 nPayloadsPerHeader = nMessages - 1;
1983 auto dh = o2::header::get<DataHeader*>(parts.At(headerIndex)->GetData());
1984 nMessages = dh->splitPayloadParts > 0 ? dh->splitPayloadParts * 2 : 2;
1985 nPayloadsPerHeader = 1;
1986 ii += (nMessages / 2) - 1;
1990 O2_SIGNPOST_EVENT_EMIT(async_queue, cid,
"onDrop",
"Dropping message from slot %zu. Forwarding as needed. Timeslice %zu",
1991 slot.
index, oldestOutputInfo.timeslice.value);
1998 forwardInputs(
ref, slot, dropped, oldestOutputInfo,
false,
true);
2001 auto relayed = relayer.relay(parts.At(headerIndex)->GetData(),
2002 &parts.At(headerIndex),
2008 switch (relayed.type) {
2010 if (info.normalOpsNotified ==
true && info.backpressureNotified ==
false) {
2011 LOGP(alarm,
"Backpressure on channel {}. Waiting.", info.channel->GetName());
2012 auto& monitoring =
ref.get<o2::monitoring::Monitoring>();
2013 monitoring.send(o2::monitoring::Metric{1, fmt::format(
"backpressure_{}", info.channel->GetName())});
2014 info.backpressureNotified =
true;
2015 info.normalOpsNotified =
false;
2017 policy.backpressure(info);
2018 hasBackpressure =
true;
2019 minBackpressureTimeslice = std::min<size_t>(minBackpressureTimeslice, relayed.timeslice.value);
2024 if (info.normalOpsNotified ==
false && info.backpressureNotified ==
true) {
2025 LOGP(info,
"Back to normal on channel {}.", info.channel->GetName());
2026 auto& monitoring =
ref.get<o2::monitoring::Monitoring>();
2027 monitoring.send(o2::monitoring::Metric{0, fmt::format(
"backpressure_{}", info.channel->GetName())});
2028 info.normalOpsNotified =
true;
2029 info.backpressureNotified =
false;
2034 case InputType::SourceInfo: {
2035 LOGP(detail,
"Received SourceInfo");
2037 state.lastActiveDataProcessor = &context;
2038 auto headerIndex = input.position;
2039 auto payloadIndex = input.position + 1;
2040 assert(payloadIndex < parts.Size());
2043 parts.At(headerIndex).reset(
nullptr);
2044 parts.At(payloadIndex).reset(
nullptr);
2051 case InputType::DomainInfo: {
2055 state.lastActiveDataProcessor = &context;
2056 auto headerIndex = input.position;
2057 auto payloadIndex = input.position + 1;
2058 assert(payloadIndex < parts.Size());
2062 auto dih = o2::header::get<DomainInfoHeader*>(parts.At(headerIndex)->GetData());
2063 if (hasBackpressure && dih->oldestPossibleTimeslice >= minBackpressureTimeslice) {
2066 oldestPossibleTimeslice = std::min(oldestPossibleTimeslice, dih->oldestPossibleTimeslice);
2067 LOGP(
debug,
"Got DomainInfoHeader, new oldestPossibleTimeslice {} on channel {}", oldestPossibleTimeslice, info.id.value);
2068 parts.At(headerIndex).reset(
nullptr);
2069 parts.At(payloadIndex).reset(
nullptr);
2071 case InputType::Invalid: {
2072 reportError(
"Invalid part found.");
2078 if (oldestPossibleTimeslice != (
size_t)-1) {
2079 info.oldestForChannel = {oldestPossibleTimeslice};
2081 context.domainInfoUpdatedCallback(*context.registry, oldestPossibleTimeslice, info.id);
2083 state.lastActiveDataProcessor = &context;
2085 auto it = std::remove_if(parts.fParts.begin(), parts.fParts.end(), [](
auto&
msg) ->
bool { return msg.get() == nullptr; });
2086 parts.fParts.erase(it, parts.end());
2087 if (parts.fParts.size()) {
2088 LOG(
debug) << parts.fParts.size() <<
" messages backpressured";
2100 auto inputTypes = getInputTypes();
2101 if (
bool(inputTypes) ==
false) {
2102 reportError(
"Parts should come in couples. Dropping it.");
2105 handleValidMessages(*inputTypes);
2111struct InputLatency {
2116auto calculateInputRecordLatency(
InputRecord const& record, uint64_t currentTime) -> InputLatency
2120 for (
auto& item : record) {
2121 auto* header = o2::header::get<DataProcessingHeader*>(item.header);
2122 if (header ==
nullptr) {
2125 int64_t partLatency = (0x7fffffffffffffff & currentTime) - (0x7fffffffffffffff & header->creation);
2126 if (partLatency < 0) {
2129 result.minLatency = std::min(
result.minLatency, (uint64_t)partLatency);
2130 result.maxLatency = std::max(
result.maxLatency, (uint64_t)partLatency);
2135auto calculateTotalInputRecordSize(
InputRecord const& record) ->
int
2137 size_t totalInputSize = 0;
2138 for (
auto& item : record) {
2139 auto* header = o2::header::get<DataHeader*>(item.header);
2140 if (header ==
nullptr) {
2143 totalInputSize += header->payloadSize;
2145 return totalInputSize;
2148template <
typename T>
2149void update_maximum(std::atomic<T>& maximum_value, T
const&
value)
noexcept
2151 T prev_value = maximum_value;
2152 while (prev_value <
value &&
2153 !maximum_value.compare_exchange_weak(prev_value,
value)) {
2161 LOGP(
debug,
"DataProcessingDevice::tryDispatchComputation");
2166 std::vector<std::vector<fair::mq::MessagePtr>> currentSetOfInputs;
2169 auto getInputSpan = [
ref, ¤tSetOfInputs](
TimesliceSlot slot,
bool consume =
true) {
2174 currentSetOfInputs = relayer.consumeExistingInputsForTimeslice(slot);
2179 auto const& msgs = currentSetOfInputs[
i];
2180 if (msgs.size() <=
indices.headerIdx) {
2183 auto const& headerMsg = msgs[
indices.headerIdx];
2184 char const* payloadData =
nullptr;
2185 size_t payloadSize = 0;
2186 if (msgs.size() >
indices.payloadIdx && msgs[
indices.payloadIdx]) {
2187 payloadData =
static_cast<char const*
>(msgs[
indices.payloadIdx]->GetData());
2188 payloadSize = msgs[
indices.payloadIdx]->GetSize();
2191 headerMsg ?
static_cast<char const*
>(headerMsg->GetData()) :
nullptr,
2195 auto nofPartsGetter = [¤tSetOfInputs](
size_t i) ->
size_t {
2198 auto refCountGetter = [¤tSetOfInputs](
size_t idx) ->
int {
2199 auto& header =
static_cast<const fair::mq::shmem::Message&
>(*(currentSetOfInputs[idx] |
get_header{0}));
2200 return header.GetRefCount();
2204 return next.headerIdx < currentSetOfInputs[
i].size() ? next :
DataRefIndices{size_t(-1), size_t(-1)};
2206 return InputSpan{nofPartsGetter, refCountGetter, indicesGetter, nextIndicesGetter, currentSetOfInputs.
size()};
2221 auto timeslice = relayer.getTimesliceForSlot(
i);
2223 timingInfo.timeslice = timeslice.value;
2233 auto timeslice = relayer.getTimesliceForSlot(
i);
2235 timingInfo.globalRunNumberChanged = !
TimingInfo::timesliceIsTimer(timeslice.value) && dataProcessorContext.lastRunNumberProcessed != timingInfo.runNumber;
2237 timingInfo.globalRunNumberChanged &= (dataProcessorContext.lastRunNumberProcessed == -1 || timingInfo.runNumber != 0);
2241 timingInfo.streamRunNumberChanged = timingInfo.globalRunNumberChanged;
2249 assert(record.size() == currentSetOfInputs.size());
2250 for (
size_t ii = 0, ie = record.size(); ii < ie; ++ii) {
2254 DataRef input = record.getByPos(ii);
2258 if (input.
header ==
nullptr) {
2262 currentSetOfInputs[ii].clear();
2273 for (
size_t pi = 0, pe = record.size(); pi < pe; ++pi) {
2274 DataRef input = record.getByPos(pi);
2275 if (input.
header ==
nullptr) {
2278 auto sih = o2::header::get<SourceInfoHeader*>(input.
header);
2283 auto dh = o2::header::get<DataHeader*>(input.
header);
2293 if (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) {
2296 pi += dh->splitPayloadParts - 1;
2298 size_t pi = pi + (dh->splitPayloadParts > 0 ? dh->splitPayloadParts : 1) * 2;
2304 if (completed.empty() ==
true) {
2305 LOGP(
debug,
"No computations available for dispatching.");
2314 std::atomic_thread_fence(std::memory_order_release);
2315 char relayerSlotState[1024];
2316 int written = snprintf(relayerSlotState, 1024,
"%d ", pipelineLength);
2317 char*
buffer = relayerSlotState + written;
2318 for (
size_t ai = 0; ai != record.size(); ai++) {
2319 buffer[ai] = record.isValid(ai) ?
'3' :
'0';
2321 buffer[record.size()] = 0;
2323 .size = (
int)(record.size() +
buffer - relayerSlotState),
2324 .
data = relayerSlotState});
2325 uint64_t tEnd = uv_hrtime();
2327 int64_t wallTimeMs = (tEnd - tStart) / 1000000;
2335 auto latency = calculateInputRecordLatency(record, tStartMilli);
2338 static int count = 0;
2345 std::atomic_thread_fence(std::memory_order_release);
2346 char relayerSlotState[1024];
2347 snprintf(relayerSlotState, 1024,
"%d ", pipelineLength);
2348 char*
buffer = strchr(relayerSlotState,
' ') + 1;
2349 for (
size_t ai = 0; ai != record.size(); ai++) {
2350 buffer[ai] = record.isValid(ai) ?
'2' :
'0';
2352 buffer[record.size()] = 0;
2370 switch (spec.completionPolicy.order) {
2372 std::sort(completed.begin(), completed.end(), [](
auto const&
a,
auto const&
b) { return a.timeslice.value < b.timeslice.value; });
2375 std::sort(completed.begin(), completed.end(), [](
auto const&
a,
auto const&
b) { return a.slot.index < b.slot.index; });
2382 for (
auto action : completed) {
2384 O2_SIGNPOST_START(device, aid,
"device",
"Processing action on slot %lu for action %{public}s", action.slot.index, fmt::format(
"{}", action.op).c_str());
2392 prepareAllocatorForCurrentTimeSlice(
TimesliceSlot{action.slot});
2398 InputSpan span = getInputSpan(action.slot, shouldConsume);
2408 dpContext.preProcessingCallbacks(processContext);
2411 context.postDispatchingCallbacks(processContext);
2412 if (spec.forwards.empty() ==
false) {
2414 forwardInputs(
ref, action.slot, currentSetOfInputs, timesliceIndex.getOldestPossibleOutput(),
false);
2415 O2_SIGNPOST_END(device, aid,
"device",
"Forwarding inputs consume: %d.",
false);
2423 bool hasForwards = spec.forwards.empty() ==
false;
2427 O2_SIGNPOST_EVENT_EMIT(device, aid,
"device",
"Early forwarding: %{public}s.", fmt::format(
"{}", action.op).c_str());
2438 O2_SIGNPOST_EVENT_EMIT(device, aid,
"device",
"cleaning early forwarding: %{public}s.", fmt::format(
"{}", action.op).c_str());
2443 markInputsAsDone(action.slot);
2445 uint64_t tStart = uv_hrtime();
2447 preUpdateStats(action, record, tStart);
2449 static bool noCatch = getenv(
"O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv(
"O2_NO_CATCHALL_EXCEPTIONS"),
"0");
2457 switch (action.op) {
2468 if (
state.quitRequested ==
false) {
2472 streamContext.preProcessingCallbacks(processContext);
2478 if (context.statefulProcess && shouldProcess(action)) {
2482 (context.statefulProcess)(processContext);
2484 }
else if (context.statelessProcess && shouldProcess(action)) {
2486 (context.statelessProcess)(processContext);
2488 }
else if (context.statelessProcess || context.statefulProcess) {
2491 O2_SIGNPOST_EVENT_EMIT(device, pcid,
"device",
"No processing callback provided. Switching to %{public}s.",
"Idle");
2494 if (shouldProcess(action)) {
2496 if (timingInfo.globalRunNumberChanged) {
2497 context.lastRunNumberProcessed = timingInfo.runNumber;
2514 streamContext.finaliseOutputsCallbacks(processContext);
2520 streamContext.postProcessingCallbacks(processContext);
2526 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
2527 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
2533 (context.errorHandling)(e, record);
2538 }
catch (std::exception& ex) {
2543 (context.errorHandling)(e, record);
2545 (context.errorHandling)(e, record);
2548 if (
state.severityStack.empty() ==
false) {
2549 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
2550 state.severityStack.pop_back();
2553 postUpdateStats(action, record, tStart, tStartMilli);
2557 cleanupRecord(record);
2558 context.postDispatchingCallbacks(processContext);
2566 context.postForwardingCallbacks(processContext);
2568 cleanTimers(action.slot, record);
2570 O2_SIGNPOST_END(device, aid,
"device",
"Done processing action on slot %lu for action %{public}s", action.slot.index, fmt::format(
"{}", action.op).c_str());
2572 O2_SIGNPOST_END(device, sid,
"device",
"Start processing ready actions");
2576 LOGP(detail,
"Broadcasting end of stream");
2577 for (
auto& channel : spec.outputChannels) {
2600 cfg.getRecursive(
name);
2601 std::vector<std::unique_ptr<ParamRetriever>> retrievers;
2602 retrievers.emplace_back(std::make_unique<ConfigurationOptionsRetriever>(&cfg,
name));
2603 auto configStore = std::make_unique<ConfigParamStore>(options, std::move(retrievers));
2604 configStore->preload();
2605 configStore->activate();
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 preEOSCallbacks(EndOfStreamContext &)
Invoke callbacks to be executed before every EOS user callback invokation.
void preProcessingCallbacks(ProcessingContext &)
Invoke callbacks to be executed before every process method invokation.
ServiceRegistry * registry
void postEOSCallbacks(EndOfStreamContext &)
Invoke callbacks to be executed after every EOS user callback invokation.
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 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