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) {
644 if (infos.empty() ==
false) {
645 std::vector<fair::mq::RegionInfo> toBeNotified;
646 toBeNotified.swap(infos);
647 static bool dummyRead = getenv(
"DPL_DEBUG_MAP_ALL_SHM_REGIONS") && atoi(getenv(
"DPL_DEBUG_MAP_ALL_SHM_REGIONS"));
648 for (
auto const& info : toBeNotified) {
668void DataProcessingDevice::initPollers()
676 if ((context.statefulProcess !=
nullptr) || (context.statelessProcess !=
nullptr)) {
677 for (
auto& [channelName, channel] : GetChannels()) {
679 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
680 auto& channelSpec = spec.inputChannels[ci];
681 channelInfo = &
state.inputChannelInfos[ci];
682 if (channelSpec.name != channelName) {
685 channelInfo->
channel = &this->GetChannel(channelName, 0);
688 if ((
channelName.rfind(
"from_internal-dpl", 0) == 0) &&
689 (
channelName.rfind(
"from_internal-dpl-aod", 0) != 0) &&
690 (
channelName.rfind(
"from_internal-dpl-ccdb-backend", 0) != 0) &&
691 (
channelName.rfind(
"from_internal-dpl-injected", 0)) != 0) {
692 LOGP(detail,
"{} is an internal channel. Skipping as no input will come from there.", channelName);
696 if (
channelName.rfind(
"from_" + spec.name +
"_", 0) == 0) {
697 LOGP(detail,
"{} is to send data. Not polling.", channelName);
702 LOGP(detail,
"{} is not a DPL socket. Not polling.", channelName);
708 size_t zmq_fd_len =
sizeof(zmq_fd);
711 channel[0].GetSocket().GetOption(
"fd", &zmq_fd, &zmq_fd_len);
716 LOGP(detail,
"Polling socket for {}", channelName);
719 pCtx->loop =
state.loop;
721 pCtx->state = &
state;
723 assert(channelInfo !=
nullptr);
724 pCtx->channelInfo = channelInfo;
725 pCtx->socket = &channel[0].GetSocket();
728 uv_poll_init(
state.loop, poller, zmq_fd);
730 LOGP(detail,
"{} is an out of band channel.", channelName);
731 state.activeOutOfBandPollers.push_back(poller);
734 state.activeInputPollers.push_back(poller);
740 if (
state.activeInputPollers.empty() &&
741 state.activeOutOfBandPollers.empty() &&
742 state.activeTimers.empty() &&
743 state.activeSignals.empty()) {
747 if (
state.inputChannelInfos.empty()) {
748 LOGP(detail,
"No input channels. Setting exit transition timeout to 0.");
749 deviceContext.exitTransitionTimeout = 0;
751 for (
auto& [channelName, channel] : GetChannels()) {
752 if (
channelName.rfind(spec.channelPrefix +
"from_internal-dpl", 0) == 0) {
753 LOGP(detail,
"{} is an internal channel. Not polling.", channelName);
756 if (
channelName.rfind(spec.channelPrefix +
"from_" + spec.name +
"_", 0) == 0) {
757 LOGP(detail,
"{} is an out of band channel. Not polling for output.", channelName);
762 size_t zmq_fd_len =
sizeof(zmq_fd);
765 channel[0].GetSocket().GetOption(
"fd", &zmq_fd, &zmq_fd_len);
767 LOGP(
error,
"Cannot get file descriptor for channel {}", channelName);
770 LOG(detail) <<
"Polling socket for " << channel[0].GetName();
774 pCtx->loop =
state.loop;
776 pCtx->state = &
state;
780 uv_poll_init(
state.loop, poller, zmq_fd);
781 state.activeOutputPollers.push_back(poller);
785 LOGP(detail,
"This is a fake device so we exit after the first iteration.");
786 deviceContext.exitTransitionTimeout = 0;
792 uv_timer_init(
state.loop, timer);
793 timer->data = &
state;
794 uv_update_time(
state.loop);
796 state.activeTimers.push_back(timer);
800void DataProcessingDevice::startPollers()
806 for (
auto* poller :
state.activeInputPollers) {
808 O2_SIGNPOST_START(device, sid,
"socket_state",
"Input socket waiting for connection.");
812 for (
auto& poller :
state.activeOutOfBandPollers) {
816 for (
auto* poller :
state.activeOutputPollers) {
818 O2_SIGNPOST_START(device, sid,
"socket_state",
"Output socket waiting for connection.");
825 uv_timer_init(
state.loop, deviceContext.gracePeriodTimer);
828 deviceContext.dataProcessingGracePeriodTimer->data =
new ServiceRegistryRef(mServiceRegistry);
829 uv_timer_init(
state.loop, deviceContext.dataProcessingGracePeriodTimer);
832void DataProcessingDevice::stopPollers()
837 LOGP(detail,
"Stopping {} input pollers",
state.activeInputPollers.size());
838 for (
auto* poller :
state.activeInputPollers) {
841 uv_poll_stop(poller);
844 LOGP(detail,
"Stopping {} out of band pollers",
state.activeOutOfBandPollers.size());
845 for (
auto* poller :
state.activeOutOfBandPollers) {
846 uv_poll_stop(poller);
849 LOGP(detail,
"Stopping {} output pollers",
state.activeOutOfBandPollers.size());
850 for (
auto* poller :
state.activeOutputPollers) {
853 uv_poll_stop(poller);
857 uv_timer_stop(deviceContext.gracePeriodTimer);
859 free(deviceContext.gracePeriodTimer);
860 deviceContext.gracePeriodTimer =
nullptr;
862 uv_timer_stop(deviceContext.dataProcessingGracePeriodTimer);
864 free(deviceContext.dataProcessingGracePeriodTimer);
865 deviceContext.dataProcessingGracePeriodTimer =
nullptr;
880 for (
auto&
di : distinct) {
881 auto& route = spec.inputs[
di];
882 if (route.configurator.has_value() ==
false) {
887 .
name = route.configurator->name,
889 .lifetime = route.matcher.lifetime,
890 .creator = route.configurator->creatorConfigurator(
state, mServiceRegistry, *mConfigRegistry),
891 .checker = route.configurator->danglingConfigurator(
state, *mConfigRegistry),
892 .handler = route.configurator->expirationConfigurator(
state, *mConfigRegistry)};
893 context.expirationHandlers.emplace_back(std::move(handler));
896 if (
state.awakeMainThread ==
nullptr) {
902 deviceContext.expectedRegionCallbacks = std::stoi(fConfig->GetValue<std::string>(
"expected-region-callbacks"));
903 deviceContext.exitTransitionTimeout = std::stoi(fConfig->GetValue<std::string>(
"exit-transition-timeout"));
904 deviceContext.dataProcessingTimeout = std::stoi(fConfig->GetValue<std::string>(
"data-processing-timeout"));
906 for (
auto& channel : GetChannels()) {
907 channel.second.at(0).Transport()->SubscribeToRegionEvents([&context = deviceContext,
908 ®istry = mServiceRegistry,
909 &pendingRegionInfos = mPendingRegionInfos,
910 ®ionInfoMutex = mRegionInfoMutex](fair::mq::RegionInfo info) {
911 std::lock_guard<std::mutex> lock(regionInfoMutex);
912 LOG(detail) <<
">>> Region info event" << info.event;
913 LOG(detail) <<
"id: " << info.id;
914 LOG(detail) <<
"ptr: " << info.ptr;
915 LOG(detail) <<
"size: " << info.size;
916 LOG(detail) <<
"flags: " << info.flags;
919 pendingRegionInfos.push_back(info);
932 if (deviceContext.sigusr1Handle ==
nullptr) {
934 deviceContext.sigusr1Handle->data = &mServiceRegistry;
935 uv_signal_init(
state.loop, deviceContext.sigusr1Handle);
939 for (
auto& handle :
state.activeSignals) {
940 handle->data = &
state;
943 deviceContext.sigusr1Handle->data = &mServiceRegistry;
946 DataProcessingDevice::initPollers();
954 LOG(
error) <<
"DataProcessor " <<
state.lastActiveDataProcessor.load()->spec->name <<
" was unexpectedly active";
966 O2_SIGNPOST_END(device, cid,
"InitTask",
"Exiting InitTask callback waiting for the remaining region callbacks.");
968 auto hasPendingEvents = [&mutex = mRegionInfoMutex, &pendingRegionInfos = mPendingRegionInfos](
DeviceContext& deviceContext) {
969 std::lock_guard<std::mutex> lock(mutex);
970 return (pendingRegionInfos.empty() ==
false) || deviceContext.expectedRegionCallbacks > 0;
977 while (hasPendingEvents(deviceContext)) {
979 uv_run(
state.loop, UV_RUN_ONCE);
983 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
987 O2_SIGNPOST_END(device, cid,
"InitTask",
"Done waiting for registration events.");
994 bool enableRateLimiting = std::stoi(fConfig->GetValue<std::string>(
"timeframes-rate-limit"));
1003 if (enableRateLimiting ==
false && spec.name.find(
"internal-dpl-injected-dummy-sink") != std::string::npos) {
1006 if (enableRateLimiting) {
1007 for (
auto& spec : spec.outputs) {
1008 if (spec.matcher.binding.value ==
"dpl-summary") {
1015 context.
registry = &mServiceRegistry;
1018 if (context.
error !=
nullptr) {
1032 errorCallback(errorContext);
1046 switch (deviceContext.processingPolicies.
error) {
1057 auto decideEarlyForward = [&context, &deviceContext, &spec,
this]() ->
ForwardPolicy {
1065 for (
auto& forward : spec.forwards) {
1077 for (
auto&
label : spec.labels) {
1078 if (
label.value ==
"output-proxy") {
1087 if (spec.forwards.empty() ==
false) {
1093 forwardPolicy = defaultEarlyForwardPolicy;
1096 forwardPolicy = defaultEarlyForwardPolicy;
1100 bool onlyConditions =
true;
1101 bool overriddenEarlyForward =
false;
1102 for (
auto& forwarded : spec.forwards) {
1103 if (forwarded.matcher.lifetime != Lifetime::Condition) {
1104 onlyConditions =
false;
1108 overriddenEarlyForward =
true;
1112 if (forwarded.matcher.lifetime == Lifetime::Optional) {
1114 overriddenEarlyForward =
true;
1119 if (!overriddenEarlyForward && onlyConditions) {
1120 forwardPolicy = defaultEarlyForwardPolicy;
1121 LOG(detail) <<
"Enabling early forwarding because only conditions to be forwarded";
1123 return forwardPolicy;
1135 state.quitRequested =
false;
1138 for (
auto& info :
state.inputChannelInfos) {
1150 for (
size_t i = 0;
i < mStreams.size(); ++
i) {
1153 context.preStartStreamCallbacks(streamRef);
1155 }
catch (std::exception& e) {
1156 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"PreRun",
"Exception of type std::exception caught in PreRun: %{public}s. Rethrowing.", e.what());
1157 O2_SIGNPOST_END(device, cid,
"PreRun",
"Exiting PreRun due to exception thrown.");
1161 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"PreRun",
"Exception of type o2::framework::RuntimeErrorRef caught in PreRun: %{public}s. Rethrowing.", err.what);
1162 O2_SIGNPOST_END(device, cid,
"PreRun",
"Exiting PreRun due to exception thrown.");
1165 O2_SIGNPOST_END(device, cid,
"PreRun",
"Unknown exception being thrown. Rethrowing.");
1173 using o2::monitoring::Metric;
1174 using o2::monitoring::Monitoring;
1175 using o2::monitoring::tags::Key;
1176 using o2::monitoring::tags::Value;
1179 monitoring.send(
Metric{(uint64_t)1,
"device_state"}.addTag(Key::Subsystem, Value::DPL));
1187 using o2::monitoring::Metric;
1188 using o2::monitoring::Monitoring;
1189 using o2::monitoring::tags::Key;
1190 using o2::monitoring::tags::Value;
1193 monitoring.send(
Metric{(uint64_t)0,
"device_state"}.addTag(Key::Subsystem, Value::DPL));
1212 bool firstLoop =
true;
1214 O2_SIGNPOST_START(device, lid,
"device_state",
"First iteration of the device loop");
1216 auto* poolSizeEnv = getenv(
"DPL_THREADPOOL_SIZE");
1217 bool dplEnableMultithreding = poolSizeEnv && std::atoi(poolSizeEnv) > 0;
1220 if (
state.nextFairMQState.empty() ==
false) {
1221 (
void)this->ChangeState(
state.nextFairMQState.back());
1222 state.nextFairMQState.pop_back();
1227 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1240 state.lastActiveDataProcessor.compare_exchange_strong(lastActive,
nullptr);
1242 auto shouldNotWait = (lastActive !=
nullptr &&
1246 shouldNotWait =
true;
1249 if (lastActive !=
nullptr) {
1252 if (NewStatePending()) {
1254 shouldNotWait =
true;
1260 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"State transition requested and we are now in Idle. We can consider it to be completed.");
1263 if (
state.severityStack.empty() ==
false) {
1264 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
1265 state.severityStack.pop_back();
1271 state.firedTimers.clear();
1273 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
1274 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
1281 O2_SIGNPOST_START(device, lid,
"run_loop",
"Dropping message from slot %" PRIu64
". Forwarding as needed.", (uint64_t)slot.index);
1289 forwardInputs(registry, slot, dropped, oldestOutputInfo,
false,
true);
1294 auto oldestPossibleTimeslice = relayer.getOldestPossibleOutput();
1296 if (shouldNotWait ==
false) {
1300 O2_SIGNPOST_END(device, lid,
"run_loop",
"Run loop completed. %{}s", shouldNotWait ?
"Will immediately schedule a new one" :
"Waiting for next event.");
1301 uv_run(
state.loop, shouldNotWait ? UV_RUN_NOWAIT : UV_RUN_ONCE);
1303 if ((
state.loopReason &
state.tracingFlags) != 0) {
1304 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
1305 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
1306 }
else if (
state.severityStack.empty() ==
false) {
1307 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
1308 state.severityStack.pop_back();
1313 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"Out of band activity detected. Rescanning everything.");
1317 if (!
state.pendingOffers.empty()) {
1318 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"Pending %" PRIu64
" offers. updating the ComputingQuotaEvaluator.", (uint64_t)
state.pendingOffers.size());
1330 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1338 assert(mStreams.size() == mHandles.size());
1341 for (
size_t ti = 0; ti < mStreams.size(); ti++) {
1342 auto& taskInfo = mStreams[ti];
1343 if (taskInfo.running) {
1347 streamRef.index = ti;
1349 using o2::monitoring::Metric;
1350 using o2::monitoring::Monitoring;
1351 using o2::monitoring::tags::Key;
1352 using o2::monitoring::tags::Value;
1355 if (streamRef.index != -1) {
1358 uv_work_t& handle = mHandles[streamRef.index];
1360 handle.data = &mStreams[streamRef.index];
1368 dpStats.processCommandQueue();
1379 struct SchedulingStats {
1380 std::atomic<size_t> lastScheduled = 0;
1381 std::atomic<size_t> numberOfUnscheduledSinceLastScheduled = 0;
1382 std::atomic<size_t> numberOfUnscheduled = 0;
1383 std::atomic<size_t> numberOfScheduled = 0;
1384 std::atomic<size_t> nextWarnAt = 1;
1386 static SchedulingStats schedulingStats;
1391 stream.registry = &mServiceRegistry;
1392 schedulingStats.lastScheduled = uv_now(
state.loop);
1393 schedulingStats.numberOfScheduled++;
1394 schedulingStats.numberOfUnscheduledSinceLastScheduled = 0;
1395 schedulingStats.nextWarnAt = 1;
1396 O2_SIGNPOST_EVENT_EMIT(scheduling, sid,
"Run",
"Enough resources to schedule computation on stream %d", streamRef.index);
1397 if (dplEnableMultithreding) [[unlikely]] {
1405 auto const lastSched = schedulingStats.lastScheduled.load();
1406 auto const schedInfo = lastSched ? fmt::format(
", last scheduled {} ms ago", uv_now(
state.loop) - lastSched) : std::string(
", never successfully scheduled");
1407 auto const buildMissingInfo = [&]() {
1408 auto const& required = spec.resourcePolicy.minRequired;
1409 std::string missingInfo;
1410 if (required.sharedMemory > 0 && accumulated.sharedMemory < required.sharedMemory) {
1411 missingInfo += fmt::format(
" shared memory (have {} MB, need {} MB)", accumulated.sharedMemory / 1000000, required.sharedMemory / 1000000);
1413 if (required.timeslices > 0 && accumulated.timeslices < required.timeslices) {
1414 missingInfo += fmt::format(
" timeslices (have {}, need {})", accumulated.timeslices, required.timeslices);
1416 if (required.cpu > 0 && accumulated.cpu < required.cpu) {
1417 missingInfo += fmt::format(
" CPU cores (have {}, need {})", accumulated.cpu, required.cpu);
1419 if (required.memory > 0 && accumulated.memory < required.memory) {
1420 missingInfo += fmt::format(
" memory (have {} MB, need {} MB)", accumulated.memory / 1000000, required.memory / 1000000);
1422 return missingInfo.empty() ? std::string(
" (policy: ") + spec.resourcePolicy.name +
")" :
" -" + missingInfo;
1424 auto const timeSinceLastScheduled = lastSched ? uv_now(
state.loop) - lastSched : 0;
1425 if (schedulingStats.numberOfUnscheduledSinceLastScheduled >= schedulingStats.nextWarnAt) {
1426 auto const missingStr = buildMissingInfo();
1427 if (timeSinceLastScheduled >= 50) {
1429 "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.",
1431 schedulingStats.numberOfUnscheduledSinceLastScheduled.load(),
1433 missingStr.c_str());
1436 "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.",
1438 schedulingStats.numberOfUnscheduledSinceLastScheduled.load(),
1440 missingStr.c_str());
1442 schedulingStats.nextWarnAt = schedulingStats.nextWarnAt * 2;
1444 auto const missingStr = buildMissingInfo();
1446 "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.",
1448 schedulingStats.numberOfUnscheduledSinceLastScheduled.load(),
1450 missingStr.c_str());
1452 schedulingStats.numberOfUnscheduled++;
1453 schedulingStats.numberOfUnscheduledSinceLastScheduled++;
1460 O2_SIGNPOST_END(device, lid,
"run_loop",
"Run loop completed. Transition handling state %d.", (
int)
state.transitionHandling);
1463 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
1464 auto& info =
state.inputChannelInfos[ci];
1465 info.parts.fParts.clear();
1476 O2_SIGNPOST_START(device, dpid,
"do_prepare",
"Starting DataProcessorContext::doPrepare.");
1494 context.allDone = std::any_of(
state.inputChannelInfos.begin(),
state.inputChannelInfos.end(), [cid](
const auto& info) {
1496 O2_SIGNPOST_EVENT_EMIT(device, cid,
"do_prepare",
"Input channel %{public}s%{public}s has %zu parts left and is in state %d.",
1497 info.channel->GetName().c_str(), (info.id.value == ChannelIndex::INVALID ?
" (non DPL)" :
""), info.parts.fParts.size(), (int)info.state);
1499 O2_SIGNPOST_EVENT_EMIT(device, cid,
"do_prepare",
"External channel %d is in state %d.", info.id.value, (int)info.state);
1504 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"do_prepare",
"Processing %zu input channels.", spec.inputChannels.size());
1507 static std::vector<int> pollOrder;
1508 pollOrder.resize(
state.inputChannelInfos.size());
1509 std::iota(pollOrder.begin(), pollOrder.end(), 0);
1510 std::sort(pollOrder.begin(), pollOrder.end(), [&infos =
state.inputChannelInfos](
int a,
int b) {
1511 return infos[a].oldestForChannel.value < infos[b].oldestForChannel.value;
1515 if (pollOrder.empty()) {
1516 O2_SIGNPOST_END(device, dpid,
"do_prepare",
"Nothing to poll. Waiting for next iteration.");
1519 auto currentOldest =
state.inputChannelInfos[pollOrder.front()].oldestForChannel;
1520 auto currentNewest =
state.inputChannelInfos[pollOrder.back()].oldestForChannel;
1521 auto delta = currentNewest.value - currentOldest.value;
1522 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"do_prepare",
"Oldest possible timeframe range %" PRIu64
" => %" PRIu64
" delta %" PRIu64,
1523 (int64_t)currentOldest.value, (int64_t)currentNewest.value, (int64_t)delta);
1524 auto& infos =
state.inputChannelInfos;
1526 if (context.balancingInputs) {
1528 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));
1529 auto newEnd = std::remove_if(pollOrder.begin(), pollOrder.end(), [&infos, limitNew = currentOldest.value + ahead](
int a) ->
bool {
1530 return infos[a].oldestForChannel.value > limitNew;
1532 for (
auto it = pollOrder.begin(); it < pollOrder.end(); it++) {
1533 const auto& channelInfo =
state.inputChannelInfos[*it];
1539 bool shouldBeRunning = it < newEnd;
1540 if (running != shouldBeRunning) {
1541 uv_poll_start(poller, shouldBeRunning ? UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED : 0, &
on_socket_polled);
1547 pollOrder.erase(newEnd, pollOrder.end());
1549 O2_SIGNPOST_END(device, dpid,
"do_prepare",
"%zu channels pass the channel inbalance balance check.", pollOrder.size());
1551 for (
auto sci : pollOrder) {
1552 auto&
info =
state.inputChannelInfos[sci];
1554 O2_SIGNPOST_START(device, cid,
"channels",
"Processing channel %s",
info.channel->GetName().c_str());
1557 context.allDone =
false;
1562 if (
info.parts.Size()) {
1565 O2_SIGNPOST_END(device, cid,
"channels",
"Flushing channel %s which is in state %d and has %zu parts still pending.",
1566 info.channel->GetName().c_str(), (
int)
info.state,
info.parts.Size());
1569 if (
info.channel ==
nullptr) {
1570 O2_SIGNPOST_END(device, cid,
"channels",
"Channel %s which is in state %d is nullptr and has %zu parts still pending.",
1571 info.channel->GetName().c_str(), (
int)
info.state,
info.parts.Size());
1576 O2_SIGNPOST_END(device, cid,
"channels",
"Channel %s which is in state %d is not a DPL channel and has %zu parts still pending.",
1577 info.channel->GetName().c_str(), (
int)
info.state,
info.parts.Size());
1580 auto& socket =
info.channel->GetSocket();
1585 if (
info.hasPendingEvents == 0) {
1586 socket.Events(&
info.hasPendingEvents);
1588 if ((
info.hasPendingEvents & 1) == 0 && (
info.parts.Size() == 0)) {
1589 O2_SIGNPOST_END(device, cid,
"channels",
"No pending events and no remaining parts to process for channel %{public}s",
info.channel->GetName().c_str());
1595 info.readPolled =
false;
1604 bool newMessages =
false;
1606 O2_SIGNPOST_EVENT_EMIT(device, cid,
"channels",
"Receiving loop called for channel %{public}s (%d) with oldest possible timeslice %zu",
1607 info.channel->GetName().c_str(),
info.id.value,
info.oldestForChannel.value);
1608 if (
info.parts.Size() < 64) {
1609 fair::mq::Parts parts;
1610 info.channel->Receive(parts, 0);
1612 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);
1614 for (
auto&& part : parts) {
1615 info.parts.fParts.emplace_back(std::move(part));
1617 newMessages |=
true;
1620 if (
info.parts.Size() >= 0) {
1632 socket.Events(&
info.hasPendingEvents);
1633 if (
info.hasPendingEvents) {
1634 info.readPolled =
false;
1637 state.lastActiveDataProcessor.store(&context);
1640 O2_SIGNPOST_END(device, cid,
"channels",
"Done processing channel %{public}s (%d).",
1641 info.channel->GetName().c_str(),
info.id.value);
1657 streamContext.completed.clear();
1658 streamContext.completed.reserve(16);
1660 state.lastActiveDataProcessor.store(&context);
1664 context.preDanglingCallbacks(danglingContext);
1665 if (
state.lastActiveDataProcessor.load() ==
nullptr) {
1668 auto activity =
ref.get<
DataRelayer>().processDanglingInputs(context.expirationHandlers, *context.registry,
true);
1669 if (activity.expiredSlots > 0) {
1670 state.lastActiveDataProcessor = &context;
1673 streamContext.completed.clear();
1675 state.lastActiveDataProcessor = &context;
1678 context.postDanglingCallbacks(danglingContext);
1686 state.lastActiveDataProcessor = &context;
1709 timingInfo.timeslice = relayer.getOldestPossibleOutput().timeslice.value;
1710 timingInfo.tfCounter = -1;
1711 timingInfo.firstTForbit = -1;
1713 timingInfo.creation = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count();
1714 O2_SIGNPOST_EVENT_EMIT(calibration, dpid,
"calibration",
"TimingInfo.keepAtEndOfStream %d", timingInfo.keepAtEndOfStream);
1718 context.preEOSCallbacks(eosContext);
1723 context.postEOSCallbacks(eosContext);
1725 for (
auto& channel : spec.outputChannels) {
1726 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"state",
"Sending end of stream to %{public}s.", channel.name.c_str());
1733 if (shouldProcess) {
1734 state.lastActiveDataProcessor = &context;
1738 for (
auto& poller :
state.activeOutputPollers) {
1739 uv_poll_stop(poller);
1747 for (
auto& poller :
state.activeOutputPollers) {
1748 uv_poll_stop(poller);
1764 if (deviceContext.sigusr1Handle) {
1770 handle->data =
nullptr;
1791 O2_SIGNPOST_EVENT_EMIT(device, sid,
"device",
"Early forwardinding before injecting data into relayer.");
1798 "Starting forwarding for incoming messages with oldestTimeslice %zu with copy",
1799 oldestTimeslice.timeslice.value);
1800 std::vector<fair::mq::Parts> forwardedParts(proxy.getNumForwardChannels());
1803 for (
int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
1804 if (forwardedParts[fi].
Size() == 0) {
1808 auto& parts = forwardedParts[fi];
1809 if (info.policy ==
nullptr) {
1813 O2_SIGNPOST_EVENT_EMIT(forwarding, sid,
"forwardInputs",
"Forwarding to %{public}s %d", info.name.c_str(), fi);
1819 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputs",
"Queuing forwarding oldestPossible %zu", oldestTimeslice.timeslice.value);
1844 auto getInputTypes = [&info, &context]() -> std::optional<std::vector<InputInfo>> {
1849 auto& parts = info.parts;
1852 std::vector<InputInfo> results;
1854 results.reserve(parts.Size() / 2);
1855 size_t nTotalPayloads = 0;
1859 if (
type != InputType::Invalid &&
length > 1) {
1860 nTotalPayloads +=
length - 1;
1864 for (
size_t pi = 0; pi < parts.Size(); pi += 2) {
1865 auto* headerData = parts.At(pi)->GetData();
1866 auto sih = o2::header::get<SourceInfoHeader*>(headerData);
1867 auto dh = o2::header::get<DataHeader*>(headerData);
1869 O2_SIGNPOST_EVENT_EMIT(device, cid,
"handle_data",
"Got SourceInfoHeader with state %d", (
int)sih->state);
1870 info.state = sih->state;
1871 insertInputInfo(pi, 2, InputType::SourceInfo, info.id);
1872 state.lastActiveDataProcessor = &context;
1874 LOGP(
error,
"Found data attached to a SourceInfoHeader");
1878 auto dih = o2::header::get<DomainInfoHeader*>(headerData);
1880 O2_SIGNPOST_EVENT_EMIT(device, cid,
"handle_data",
"Got DomainInfoHeader with oldestPossibleTimeslice %d", (
int)dih->oldestPossibleTimeslice);
1881 insertInputInfo(pi, 2, InputType::DomainInfo, info.id);
1882 state.lastActiveDataProcessor = &context;
1884 LOGP(
error,
"Found data attached to a DomainInfoHeader");
1889 insertInputInfo(pi, 0, InputType::Invalid, info.id);
1893 if (dh->payloadSize > parts.At(pi + 1)->GetSize()) {
1894 insertInputInfo(pi, 0, InputType::Invalid, info.id);
1898 auto dph = o2::header::get<DataProcessingHeader*>(headerData);
1903 O2_SIGNPOST_START(parts,
pid,
"parts",
"Processing DataHeader %{public}-4s/%{public}-16s/%d with splitPayloadParts %d and splitPayloadIndex %d",
1904 dh->dataOrigin.str, dh->dataDescription.str, dh->subSpecification, dh->splitPayloadParts, dh->splitPayloadIndex);
1906 insertInputInfo(pi, 2, InputType::Invalid, info.id);
1910 if (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) {
1913 insertInputInfo(pi, dh->splitPayloadParts + 1, InputType::Data, info.id);
1914 pi += dh->splitPayloadParts - 1;
1920 size_t finalSplitPayloadIndex = pi + (dh->splitPayloadParts > 0 ? dh->splitPayloadParts : 1) * 2;
1921 if (finalSplitPayloadIndex > parts.Size()) {
1923 insertInputInfo(pi, 0, InputType::Invalid, info.id);
1926 insertInputInfo(pi, 2, InputType::Data, info.id);
1927 for (; pi + 2 < finalSplitPayloadIndex; pi += 2) {
1928 insertInputInfo(pi + 2, 2, InputType::Data, info.id);
1932 if (results.size() + nTotalPayloads != parts.Size()) {
1933 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"handle_data",
"inconsistent number of inputs extracted. %zu vs parts (%zu)", results.size() + nTotalPayloads, parts.Size());
1934 return std::nullopt;
1939 auto reportError = [
ref](
const char*
message) {
1944 auto handleValidMessages = [&info,
ref, &reportError, &context](std::vector<InputInfo>
const& inputInfos) {
1948 auto& parts = info.parts;
1951 bool hasBackpressure =
false;
1952 size_t minBackpressureTimeslice = -1;
1954 size_t oldestPossibleTimeslice = -1;
1955 static std::vector<int> ordering;
1957 ordering.resize(inputInfos.size());
1958 std::iota(ordering.begin(), ordering.end(), 0);
1960 std::stable_sort(ordering.begin(), ordering.end(), [&inputInfos](
int const&
a,
int const&
b) {
1961 auto const& ai = inputInfos[a];
1962 auto const& bi = inputInfos[b];
1963 if (ai.type != bi.type) {
1964 return ai.type < bi.type;
1966 return ai.position < bi.position;
1968 for (
size_t ii = 0; ii < inputInfos.size(); ++ii) {
1969 auto const& input = inputInfos[ordering[ii]];
1970 switch (input.type) {
1971 case InputType::Data: {
1973 auto headerIndex = input.position;
1975 auto nPayloadsPerHeader = 0;
1976 if (input.size > 2) {
1978 nMessages = input.size;
1979 nPayloadsPerHeader = nMessages - 1;
1982 auto dh = o2::header::get<DataHeader*>(parts.At(headerIndex)->GetData());
1983 nMessages = dh->splitPayloadParts > 0 ? dh->splitPayloadParts * 2 : 2;
1984 nPayloadsPerHeader = 1;
1985 ii += (nMessages / 2) - 1;
1989 O2_SIGNPOST_EVENT_EMIT(async_queue, cid,
"onDrop",
"Dropping message from slot %zu. Forwarding as needed. Timeslice %zu",
1990 slot.
index, oldestOutputInfo.timeslice.value);
1997 forwardInputs(
ref, slot, dropped, oldestOutputInfo,
false,
true);
2000 auto relayed = relayer.relay(parts.At(headerIndex)->GetData(),
2001 &parts.At(headerIndex),
2007 switch (relayed.type) {
2009 if (info.normalOpsNotified ==
true && info.backpressureNotified ==
false) {
2010 LOGP(alarm,
"Backpressure on channel {}. Waiting.", info.channel->GetName());
2011 auto& monitoring =
ref.get<o2::monitoring::Monitoring>();
2012 monitoring.send(o2::monitoring::Metric{1, fmt::format(
"backpressure_{}", info.channel->GetName())});
2013 info.backpressureNotified =
true;
2014 info.normalOpsNotified =
false;
2016 policy.backpressure(info);
2017 hasBackpressure =
true;
2018 minBackpressureTimeslice = std::min<size_t>(minBackpressureTimeslice, relayed.timeslice.value);
2023 if (info.normalOpsNotified ==
false && info.backpressureNotified ==
true) {
2024 LOGP(info,
"Back to normal on channel {}.", info.channel->GetName());
2025 auto& monitoring =
ref.get<o2::monitoring::Monitoring>();
2026 monitoring.send(o2::monitoring::Metric{0, fmt::format(
"backpressure_{}", info.channel->GetName())});
2027 info.normalOpsNotified =
true;
2028 info.backpressureNotified =
false;
2033 case InputType::SourceInfo: {
2034 LOGP(detail,
"Received SourceInfo");
2036 state.lastActiveDataProcessor = &context;
2037 auto headerIndex = input.position;
2038 auto payloadIndex = input.position + 1;
2039 assert(payloadIndex < parts.Size());
2042 parts.At(headerIndex).reset(
nullptr);
2043 parts.At(payloadIndex).reset(
nullptr);
2050 case InputType::DomainInfo: {
2054 state.lastActiveDataProcessor = &context;
2055 auto headerIndex = input.position;
2056 auto payloadIndex = input.position + 1;
2057 assert(payloadIndex < parts.Size());
2061 auto dih = o2::header::get<DomainInfoHeader*>(parts.At(headerIndex)->GetData());
2062 if (hasBackpressure && dih->oldestPossibleTimeslice >= minBackpressureTimeslice) {
2065 oldestPossibleTimeslice = std::min(oldestPossibleTimeslice, dih->oldestPossibleTimeslice);
2066 LOGP(
debug,
"Got DomainInfoHeader, new oldestPossibleTimeslice {} on channel {}", oldestPossibleTimeslice, info.id.value);
2067 parts.At(headerIndex).reset(
nullptr);
2068 parts.At(payloadIndex).reset(
nullptr);
2070 case InputType::Invalid: {
2071 reportError(
"Invalid part found.");
2077 if (oldestPossibleTimeslice != (
size_t)-1) {
2078 info.oldestForChannel = {oldestPossibleTimeslice};
2080 context.domainInfoUpdatedCallback(*context.registry, oldestPossibleTimeslice, info.id);
2082 state.lastActiveDataProcessor = &context;
2084 auto it = std::remove_if(parts.fParts.begin(), parts.fParts.end(), [](
auto&
msg) ->
bool { return msg.get() == nullptr; });
2085 parts.fParts.erase(it, parts.end());
2086 if (parts.fParts.size()) {
2087 LOG(
debug) << parts.fParts.size() <<
" messages backpressured";
2099 auto inputTypes = getInputTypes();
2100 if (
bool(inputTypes) ==
false) {
2101 reportError(
"Parts should come in couples. Dropping it.");
2104 handleValidMessages(*inputTypes);
2110struct InputLatency {
2115auto calculateInputRecordLatency(
InputRecord const& record, uint64_t currentTime) -> InputLatency
2119 for (
auto& item : record) {
2120 auto* header = o2::header::get<DataProcessingHeader*>(item.header);
2121 if (header ==
nullptr) {
2124 int64_t partLatency = (0x7fffffffffffffff & currentTime) - (0x7fffffffffffffff & header->creation);
2125 if (partLatency < 0) {
2128 result.minLatency = std::min(
result.minLatency, (uint64_t)partLatency);
2129 result.maxLatency = std::max(
result.maxLatency, (uint64_t)partLatency);
2134auto calculateTotalInputRecordSize(
InputRecord const& record) ->
int
2136 size_t totalInputSize = 0;
2137 for (
auto& item : record) {
2138 auto* header = o2::header::get<DataHeader*>(item.header);
2139 if (header ==
nullptr) {
2142 totalInputSize += header->payloadSize;
2144 return totalInputSize;
2147template <
typename T>
2148void update_maximum(std::atomic<T>& maximum_value, T
const&
value)
noexcept
2150 T prev_value = maximum_value;
2151 while (prev_value <
value &&
2152 !maximum_value.compare_exchange_weak(prev_value,
value)) {
2160 LOGP(
debug,
"DataProcessingDevice::tryDispatchComputation");
2165 std::vector<std::span<fair::mq::MessagePtr>> currentSetOfInputs;
2166 std::vector<std::vector<fair::mq::MessagePtr>> ownedInputs;
2169 auto getInputSpan = [
ref, ¤tSetOfInputs, &ownedInputs](
TimesliceSlot slot,
bool consume =
true) {
2174 ownedInputs = relayer.consumeExistingInputsForTimeslice(slot);
2176 currentSetOfInputs.resize(ownedInputs.size());
2177 for (
size_t i = 0;
i < ownedInputs.size(); ++
i) {
2178 currentSetOfInputs[
i] = std::span(ownedInputs[
i]);
2183 auto const& msgs = currentSetOfInputs[
i];
2184 if (msgs.size() <=
indices.headerIdx) {
2187 auto const& headerMsg = msgs[
indices.headerIdx];
2188 char const* payloadData =
nullptr;
2189 size_t payloadSize = 0;
2190 if (msgs.size() >
indices.payloadIdx && msgs[
indices.payloadIdx]) {
2191 payloadData =
static_cast<char const*
>(msgs[
indices.payloadIdx]->GetData());
2192 payloadSize = msgs[
indices.payloadIdx]->GetSize();
2195 headerMsg ?
static_cast<char const*
>(headerMsg->GetData()) :
nullptr,
2199 auto nofPartsGetter = [¤tSetOfInputs](
size_t i) ->
size_t {
2202 auto refCountGetter = [¤tSetOfInputs](
size_t idx) ->
int {
2203 auto& header =
static_cast<const fair::mq::shmem::Message&
>(*(currentSetOfInputs[idx] |
get_header{0}));
2204 return header.GetRefCount();
2208 return next.headerIdx < currentSetOfInputs[
i].size() ? next :
DataRefIndices{size_t(-1), size_t(-1)};
2210 auto payloadGetter = [¤tSetOfInputs](
size_t i,
DataRefIndices current) -> fair::mq::Message* {
2211 auto const& msgs = currentSetOfInputs[
i];
2212 if (msgs.size() <= current.payloadIdx || !msgs[current.payloadIdx]) {
2215 return msgs[current.payloadIdx].get();
2217 return InputSpan{nofPartsGetter, refCountGetter, indicesGetter, nextIndicesGetter, payloadGetter, currentSetOfInputs.
size()};
2232 auto timeslice = relayer.getTimesliceForSlot(
i);
2234 timingInfo.timeslice = timeslice.value;
2244 auto timeslice = relayer.getTimesliceForSlot(
i);
2246 timingInfo.globalRunNumberChanged = !
TimingInfo::timesliceIsTimer(timeslice.value) && dataProcessorContext.lastRunNumberProcessed != timingInfo.runNumber;
2248 timingInfo.globalRunNumberChanged &= (dataProcessorContext.lastRunNumberProcessed == -1 || timingInfo.runNumber != 0);
2252 timingInfo.streamRunNumberChanged = timingInfo.globalRunNumberChanged;
2260 assert(record.size() == currentSetOfInputs.size());
2261 for (
size_t ii = 0, ie = record.size(); ii < ie; ++ii) {
2265 DataRef input = record.getByPos(ii);
2269 if (input.
header ==
nullptr) {
2274 ownedInputs[ii].clear();
2275 currentSetOfInputs[ii] = {};
2286 for (
size_t pi = 0, pe = record.size(); pi < pe; ++pi) {
2287 DataRef input = record.getByPos(pi);
2288 if (input.
header ==
nullptr) {
2291 auto sih = o2::header::get<SourceInfoHeader*>(input.
header);
2296 auto dh = o2::header::get<DataHeader*>(input.
header);
2306 if (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) {
2309 pi += dh->splitPayloadParts - 1;
2311 size_t pi = pi + (dh->splitPayloadParts > 0 ? dh->splitPayloadParts : 1) * 2;
2317 if (completed.empty() ==
true) {
2318 LOGP(
debug,
"No computations available for dispatching.");
2327 std::atomic_thread_fence(std::memory_order_release);
2328 char relayerSlotState[1024];
2329 int written = snprintf(relayerSlotState, 1024,
"%d ", pipelineLength);
2330 char*
buffer = relayerSlotState + written;
2331 for (
size_t ai = 0; ai != record.size(); ai++) {
2332 buffer[ai] = record.isValid(ai) ?
'3' :
'0';
2334 buffer[record.size()] = 0;
2336 .size = (
int)(record.size() +
buffer - relayerSlotState),
2337 .
data = relayerSlotState});
2338 uint64_t tEnd = uv_hrtime();
2340 int64_t wallTimeMs = (tEnd - tStart) / 1000000;
2348 auto latency = calculateInputRecordLatency(record, tStartMilli);
2351 static int count = 0;
2358 std::atomic_thread_fence(std::memory_order_release);
2359 char relayerSlotState[1024];
2360 snprintf(relayerSlotState, 1024,
"%d ", pipelineLength);
2361 char*
buffer = strchr(relayerSlotState,
' ') + 1;
2362 for (
size_t ai = 0; ai != record.size(); ai++) {
2363 buffer[ai] = record.isValid(ai) ?
'2' :
'0';
2365 buffer[record.size()] = 0;
2383 switch (spec.completionPolicy.order) {
2385 std::sort(completed.begin(), completed.end(), [](
auto const&
a,
auto const&
b) { return a.timeslice.value < b.timeslice.value; });
2388 std::sort(completed.begin(), completed.end(), [](
auto const&
a,
auto const&
b) { return a.slot.index < b.slot.index; });
2395 for (
auto action : completed) {
2397 O2_SIGNPOST_START(device, aid,
"device",
"Processing action on slot %lu for action %{public}s", action.slot.index, fmt::format(
"{}", action.op).c_str());
2405 prepareAllocatorForCurrentTimeSlice(
TimesliceSlot{action.slot});
2411 InputSpan span = getInputSpan(action.slot, shouldConsume);
2421 dpContext.preProcessingCallbacks(processContext);
2424 context.postDispatchingCallbacks(processContext);
2425 if (spec.forwards.empty() ==
false) {
2427 forwardInputs(
ref, action.slot, currentSetOfInputs, timesliceIndex.getOldestPossibleOutput(),
false);
2428 O2_SIGNPOST_END(device, aid,
"device",
"Forwarding inputs consume: %d.",
false);
2436 bool hasForwards = spec.forwards.empty() ==
false;
2440 O2_SIGNPOST_EVENT_EMIT(device, aid,
"device",
"Early forwarding: %{public}s.", fmt::format(
"{}", action.op).c_str());
2451 O2_SIGNPOST_EVENT_EMIT(device, aid,
"device",
"cleaning early forwarding: %{public}s.", fmt::format(
"{}", action.op).c_str());
2456 markInputsAsDone(action.slot);
2458 uint64_t tStart = uv_hrtime();
2460 preUpdateStats(action, record, tStart);
2462 static bool noCatch = getenv(
"O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv(
"O2_NO_CATCHALL_EXCEPTIONS"),
"0");
2470 switch (action.op) {
2481 if (
state.quitRequested ==
false) {
2485 streamContext.preProcessingCallbacks(processContext);
2491 if (context.statefulProcess && shouldProcess(action)) {
2495 (context.statefulProcess)(processContext);
2497 }
else if (context.statelessProcess && shouldProcess(action)) {
2499 (context.statelessProcess)(processContext);
2501 }
else if (context.statelessProcess || context.statefulProcess) {
2504 O2_SIGNPOST_EVENT_EMIT(device, pcid,
"device",
"No processing callback provided. Switching to %{public}s.",
"Idle");
2507 if (shouldProcess(action)) {
2509 if (timingInfo.globalRunNumberChanged) {
2510 context.lastRunNumberProcessed = timingInfo.runNumber;
2527 streamContext.finaliseOutputsCallbacks(processContext);
2533 streamContext.postProcessingCallbacks(processContext);
2539 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
2540 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
2546 (context.errorHandling)(e, record);
2551 }
catch (std::exception& ex) {
2556 (context.errorHandling)(e, record);
2558 (context.errorHandling)(e, record);
2561 if (
state.severityStack.empty() ==
false) {
2562 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
2563 state.severityStack.pop_back();
2566 postUpdateStats(action, record, tStart, tStartMilli);
2570 cleanupRecord(record);
2571 context.postDispatchingCallbacks(processContext);
2579 context.postForwardingCallbacks(processContext);
2581 cleanTimers(action.slot, record);
2583 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());
2585 O2_SIGNPOST_END(device, sid,
"device",
"Start processing ready actions");
2589 LOGP(detail,
"Broadcasting end of stream");
2590 for (
auto& channel : spec.outputChannels) {
2613 cfg.getRecursive(
name);
2614 std::vector<std::unique_ptr<ParamRetriever>> retrievers;
2615 retrievers.emplace_back(std::make_unique<ConfigurationOptionsRetriever>(&cfg,
name));
2616 auto configStore = std::make_unique<ConfigParamStore>(options, std::move(retrievers));
2617 configStore->preload();
2618 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 std::vector< fair::mq::Parts > routeForwardedMessageSet(FairMQDeviceProxy &proxy, std::vector< std::span< fair::mq::MessagePtr > > ¤tSetOfInputs, bool copy, bool consume)
Helper to route messages for forwarding.
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 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