34#if defined(__APPLE__) || defined(NDEBUG)
35#define O2_SIGNPOST_IMPLEMENTATION
59#include <fairmq/Parts.h>
60#include <fairmq/Socket.h>
61#include <fairmq/ProgOptions.h>
62#include <fairmq/shmem/Message.h>
63#include <Configuration/ConfigurationInterface.h>
64#include <Configuration/ConfigurationFactory.h>
65#include <Monitoring/Monitoring.h>
67#include <TClonesArray.h>
69#include <fmt/ostream.h>
77#include <boost/property_tree/json_parser.hpp>
135 return devices[running.
index];
145 : mRunningDevice{running},
146 mConfigRegistry{nullptr},
147 mServiceRegistry{registry}
149 GetConfig()->Subscribe<std::string>(
"dpl", [®istry = mServiceRegistry](
const std::string&
key, std::string
value) {
150 if (
key ==
"cleanup") {
154 int64_t newCleanupCount = std::stoll(
value);
155 if (newCleanupCount <= cleanupCount) {
158 deviceState.cleanupCount.store(newCleanupCount);
159 for (
auto& info : deviceState.inputChannelInfos) {
160 fair::mq::Parts parts;
161 while (info.channel->Receive(parts, 0)) {
162 LOGP(
debug,
"Dropping {} parts", parts.Size());
163 if (parts.Size() == 0) {
171 std::function<
void(
const fair::mq::State)> stateWatcher = [
this, ®istry = mServiceRegistry](
const fair::mq::State
state) ->
void {
176 control.notifyDeviceState(fair::mq::GetStateName(
state));
179 if (deviceState.nextFairMQState.empty() ==
false) {
180 auto state = deviceState.nextFairMQState.back();
182 deviceState.nextFairMQState.pop_back();
187 this->SubscribeToStateChange(
"99-dpl", stateWatcher);
199 mAwakeHandle->data = &
state;
201 LOG(
error) <<
"Unable to initialise subscription";
205 SubscribeToNewTransition(
"dpl", [wakeHandle = mAwakeHandle](fair::mq::Transition t) {
206 int res = uv_async_send(wakeHandle);
208 LOG(
error) <<
"Unable to notify subscription";
210 LOG(
debug) <<
"State transition requested";
224 O2_SIGNPOST_START(device, sid,
"run_callback",
"Starting run callback on stream %d", task->id.index);
227 O2_SIGNPOST_END(device, sid,
"run_callback",
"Done processing data for stream %d", task->id.index);
240 using o2::monitoring::Metric;
241 using o2::monitoring::Monitoring;
242 using o2::monitoring::tags::Key;
243 using o2::monitoring::tags::Value;
247 stats.totalConsumedBytes += accumulatedConsumed.
sharedMemory;
250 stats.totalConsumedTimeslices += std::min<int64_t>(accumulatedConsumed.
timeslices, 1);
254 dpStats.processCommandQueue();
264 dpStats.processCommandQueue();
267 for (
auto& consumer :
state.offerConsumers) {
268 quotaEvaluator.consume(task->id.index, consumer, reportConsumedOffer);
270 state.offerConsumers.clear();
271 quotaEvaluator.handleExpired(reportExpiredOffer);
272 quotaEvaluator.dispose(task->id.index);
273 task->running =
false;
301 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"Data pending on socket for channel %{public}s", context->name);
305 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"Socket connected for channel %{public}s", context->name);
307 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"Socket connected for read in context %{public}s", context->name);
308 uv_poll_start(poller, UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED, &
on_socket_polled);
311 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"Socket connected for write for channel %{public}s", context->name);
319 case UV_DISCONNECT: {
320 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"Socket disconnected in context %{public}s", context->name);
322 case UV_PRIORITIZED: {
323 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"Socket prioritized for context %{public}s", context->name);
335 LOGP(fatal,
"Error while polling {}: {}", context->name, status);
340 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"Data pending on socket for channel %{public}s", context->name);
342 assert(context->channelInfo);
343 context->channelInfo->readPolled =
true;
346 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"OOB socket connected for channel %{public}s", context->name);
348 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"OOB socket connected for read in context %{public}s", context->name);
351 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"OOB socket connected for write for channel %{public}s", context->name);
355 case UV_DISCONNECT: {
356 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"OOB socket disconnected in context %{public}s", context->name);
359 case UV_PRIORITIZED: {
360 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"OOB socket prioritized for context %{public}s", context->name);
381 context.statelessProcess = spec.algorithm.onProcess;
383 context.error = spec.algorithm.onError;
384 context.
initError = spec.algorithm.onInitError;
387 if (configStore ==
nullptr) {
388 std::vector<std::unique_ptr<ParamRetriever>> retrievers;
389 retrievers.emplace_back(std::make_unique<FairOptionsRetriever>(GetConfig()));
390 configStore = std::make_unique<ConfigParamStore>(spec.options, std::move(retrievers));
391 configStore->preload();
392 configStore->activate();
395 using boost::property_tree::ptree;
398 for (
auto&
entry : configStore->store()) {
399 std::stringstream ss;
401 if (
entry.second.empty() ==
false) {
402 boost::property_tree::json_parser::write_json(ss,
entry.second,
false);
406 str =
entry.second.get_value<std::string>();
408 std::string configString = fmt::format(
"[CONFIG] {}={} 1 {}",
entry.first,
str, configStore->provenance(
entry.first.c_str())).c_str();
412 mConfigRegistry = std::make_unique<ConfigParamRegistry>(std::move(configStore));
415 if (context.initError) {
416 context.initErrorHandling = [&errorCallback = context.initError,
429 errorCallback(errorContext);
432 context.initErrorHandling = [&serviceRegistry = mServiceRegistry](
RuntimeErrorRef e) {
447 context.expirationHandlers.clear();
448 context.init = spec.algorithm.onInit;
450 static bool noCatch = getenv(
"O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv(
"O2_NO_CATCHALL_EXCEPTIONS"),
"0");
451 InitContext initContext{*mConfigRegistry, mServiceRegistry};
455 context.statefulProcess = context.init(initContext);
457 if (context.initErrorHandling) {
458 (context.initErrorHandling)(e);
463 context.statefulProcess = context.init(initContext);
464 }
catch (std::exception& ex) {
469 (context.initErrorHandling)(e);
471 (context.initErrorHandling)(e);
476 state.inputChannelInfos.resize(spec.inputChannels.size());
480 int validChannelId = 0;
481 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
482 auto&
name = spec.inputChannels[ci].name;
483 if (
name.find(spec.channelPrefix +
"from_internal-dpl-clock") == 0) {
488 state.inputChannelInfos[ci].id = {validChannelId++};
493 if (spec.callbacksPolicy.policy !=
nullptr) {
494 InitContext initContext{*mConfigRegistry, mServiceRegistry};
499 auto* options = GetConfig();
500 for (
size_t si = 0; si < mStreams.size(); ++si) {
514 O2_SIGNPOST_END(device, sid,
"signal_state",
"No registry active. Ignoring signal.");
523 while (ri != quotaEvaluator.mOffers.size()) {
524 auto& offer = quotaEvaluator.mOffers[ri];
530 if (offer.valid && offer.sharedMemory != 0) {
531 O2_SIGNPOST_END(device, sid,
"signal_state",
"Memory already offered.");
537 for (
auto& offer : quotaEvaluator.mOffers) {
538 if (offer.valid ==
false) {
541 offer.sharedMemory = 1000000000;
548 O2_SIGNPOST_END(device, sid,
"signal_state",
"Done processing signals.");
562 if (oldestTimeslice.timeslice.value <= decongestion.lastTimeslice) {
563 LOG(
debug) <<
"Not sending already sent oldest possible timeslice " << oldestTimeslice.timeslice.value;
566 for (
int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
567 auto& info = proxy.getForwardChannelInfo(
ChannelIndex{fi});
572 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputsCallback",
"Skipping channel %{public}s because it's not a DPL channel",
578 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputsCallback",
"Forwarding to channel %{public}s oldest possible timeslice %zu, prio 20",
579 info.name.c_str(), oldestTimeslice.timeslice.value);
593 O2_SIGNPOST_START(forwarding, sid,
"forwardInputs",
"Starting forwarding for slot %zu with oldestTimeslice %zu %{public}s%{public}s%{public}s",
594 slot.index, oldestTimeslice.timeslice.value, copy ?
"with copy" :
"", copy && consume ?
" and " :
"", consume ?
"with consume" :
"");
597 for (
int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
598 if (forwardedParts[fi].
Size() == 0) {
602 auto& parts = forwardedParts[fi];
603 if (info.
policy ==
nullptr) {
614 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputs",
"Queuing forwarding oldestPossible %zu", oldestTimeslice.timeslice.value);
626 if (infos.empty() ==
false) {
627 std::vector<fair::mq::RegionInfo> toBeNotified;
628 toBeNotified.swap(infos);
629 static bool dummyRead = getenv(
"DPL_DEBUG_MAP_ALL_SHM_REGIONS") && atoi(getenv(
"DPL_DEBUG_MAP_ALL_SHM_REGIONS"));
630 for (
auto const& info : toBeNotified) {
650void DataProcessingDevice::initPollers()
658 if ((context.statefulProcess !=
nullptr) || (context.statelessProcess !=
nullptr)) {
659 for (
auto& [channelName, channel] : GetChannels()) {
661 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
662 auto& channelSpec = spec.inputChannels[ci];
663 channelInfo = &
state.inputChannelInfos[ci];
664 if (channelSpec.name != channelName) {
667 channelInfo->
channel = &this->GetChannel(channelName, 0);
670 if ((
channelName.rfind(
"from_internal-dpl", 0) == 0) &&
671 (
channelName.rfind(
"from_internal-dpl-aod", 0) != 0) &&
672 (
channelName.rfind(
"from_internal-dpl-ccdb-backend", 0) != 0) &&
673 (
channelName.rfind(
"from_internal-dpl-injected", 0)) != 0) {
674 LOGP(detail,
"{} is an internal channel. Skipping as no input will come from there.", channelName);
678 if (
channelName.rfind(
"from_" + spec.name +
"_", 0) == 0) {
679 LOGP(detail,
"{} is to send data. Not polling.", channelName);
684 LOGP(detail,
"{} is not a DPL socket. Not polling.", channelName);
690 size_t zmq_fd_len =
sizeof(zmq_fd);
693 channel[0].GetSocket().GetOption(
"fd", &zmq_fd, &zmq_fd_len);
698 LOGP(detail,
"Polling socket for {}", channelName);
701 pCtx->loop =
state.loop;
703 pCtx->state = &
state;
705 assert(channelInfo !=
nullptr);
706 pCtx->channelInfo = channelInfo;
707 pCtx->socket = &channel[0].GetSocket();
710 uv_poll_init(
state.loop, poller, zmq_fd);
712 LOGP(detail,
"{} is an out of band channel.", channelName);
713 state.activeOutOfBandPollers.push_back(poller);
716 state.activeInputPollers.push_back(poller);
722 if (
state.activeInputPollers.empty() &&
723 state.activeOutOfBandPollers.empty() &&
724 state.activeTimers.empty() &&
725 state.activeSignals.empty()) {
729 if (
state.inputChannelInfos.empty()) {
730 LOGP(detail,
"No input channels. Setting exit transition timeout to 0.");
731 deviceContext.exitTransitionTimeout = 0;
733 for (
auto& [channelName, channel] : GetChannels()) {
734 if (
channelName.rfind(spec.channelPrefix +
"from_internal-dpl", 0) == 0) {
735 LOGP(detail,
"{} is an internal channel. Not polling.", channelName);
738 if (
channelName.rfind(spec.channelPrefix +
"from_" + spec.name +
"_", 0) == 0) {
739 LOGP(detail,
"{} is an out of band channel. Not polling for output.", channelName);
744 size_t zmq_fd_len =
sizeof(zmq_fd);
747 channel[0].GetSocket().GetOption(
"fd", &zmq_fd, &zmq_fd_len);
749 LOGP(
error,
"Cannot get file descriptor for channel {}", channelName);
752 LOG(detail) <<
"Polling socket for " << channel[0].GetName();
756 pCtx->loop =
state.loop;
758 pCtx->state = &
state;
762 uv_poll_init(
state.loop, poller, zmq_fd);
763 state.activeOutputPollers.push_back(poller);
767 LOGP(detail,
"This is a fake device so we exit after the first iteration.");
768 deviceContext.exitTransitionTimeout = 0;
774 uv_timer_init(
state.loop, timer);
775 timer->data = &
state;
776 uv_update_time(
state.loop);
778 state.activeTimers.push_back(timer);
782void DataProcessingDevice::startPollers()
788 for (
auto* poller :
state.activeInputPollers) {
790 O2_SIGNPOST_START(device, sid,
"socket_state",
"Input socket waiting for connection.");
794 for (
auto& poller :
state.activeOutOfBandPollers) {
798 for (
auto* poller :
state.activeOutputPollers) {
800 O2_SIGNPOST_START(device, sid,
"socket_state",
"Output socket waiting for connection.");
807 uv_timer_init(
state.loop, deviceContext.gracePeriodTimer);
810 deviceContext.dataProcessingGracePeriodTimer->data =
new ServiceRegistryRef(mServiceRegistry);
811 uv_timer_init(
state.loop, deviceContext.dataProcessingGracePeriodTimer);
814void DataProcessingDevice::stopPollers()
819 LOGP(detail,
"Stopping {} input pollers",
state.activeInputPollers.size());
820 for (
auto* poller :
state.activeInputPollers) {
823 uv_poll_stop(poller);
826 LOGP(detail,
"Stopping {} out of band pollers",
state.activeOutOfBandPollers.size());
827 for (
auto* poller :
state.activeOutOfBandPollers) {
828 uv_poll_stop(poller);
831 LOGP(detail,
"Stopping {} output pollers",
state.activeOutOfBandPollers.size());
832 for (
auto* poller :
state.activeOutputPollers) {
835 uv_poll_stop(poller);
839 uv_timer_stop(deviceContext.gracePeriodTimer);
841 free(deviceContext.gracePeriodTimer);
842 deviceContext.gracePeriodTimer =
nullptr;
844 uv_timer_stop(deviceContext.dataProcessingGracePeriodTimer);
846 free(deviceContext.dataProcessingGracePeriodTimer);
847 deviceContext.dataProcessingGracePeriodTimer =
nullptr;
862 for (
auto&
di : distinct) {
863 auto& route = spec.inputs[
di];
864 if (route.configurator.has_value() ==
false) {
869 .
name = route.configurator->name,
871 .lifetime = route.matcher.lifetime,
872 .creator = route.configurator->creatorConfigurator(
state, mServiceRegistry, *mConfigRegistry),
873 .checker = route.configurator->danglingConfigurator(
state, *mConfigRegistry),
874 .handler = route.configurator->expirationConfigurator(
state, *mConfigRegistry)};
875 context.expirationHandlers.emplace_back(std::move(handler));
878 if (
state.awakeMainThread ==
nullptr) {
884 deviceContext.expectedRegionCallbacks = std::stoi(fConfig->GetValue<std::string>(
"expected-region-callbacks"));
885 deviceContext.exitTransitionTimeout = std::stoi(fConfig->GetValue<std::string>(
"exit-transition-timeout"));
886 deviceContext.dataProcessingTimeout = std::stoi(fConfig->GetValue<std::string>(
"data-processing-timeout"));
888 for (
auto& channel : GetChannels()) {
889 channel.second.at(0).Transport()->SubscribeToRegionEvents([&context = deviceContext,
890 ®istry = mServiceRegistry,
891 &pendingRegionInfos = mPendingRegionInfos,
892 ®ionInfoMutex = mRegionInfoMutex](fair::mq::RegionInfo info) {
893 std::lock_guard<std::mutex> lock(regionInfoMutex);
894 LOG(detail) <<
">>> Region info event" << info.event;
895 LOG(detail) <<
"id: " << info.id;
896 LOG(detail) <<
"ptr: " << info.ptr;
897 LOG(detail) <<
"size: " << info.size;
898 LOG(detail) <<
"flags: " << info.flags;
901 pendingRegionInfos.push_back(info);
914 if (deviceContext.sigusr1Handle ==
nullptr) {
916 deviceContext.sigusr1Handle->data = &mServiceRegistry;
917 uv_signal_init(
state.loop, deviceContext.sigusr1Handle);
921 for (
auto& handle :
state.activeSignals) {
922 handle->data = &
state;
925 deviceContext.sigusr1Handle->data = &mServiceRegistry;
928 DataProcessingDevice::initPollers();
936 LOG(
error) <<
"DataProcessor " <<
state.lastActiveDataProcessor.load()->spec->name <<
" was unexpectedly active";
948 O2_SIGNPOST_END(device, cid,
"InitTask",
"Exiting InitTask callback waiting for the remaining region callbacks.");
950 auto hasPendingEvents = [&mutex = mRegionInfoMutex, &pendingRegionInfos = mPendingRegionInfos](
DeviceContext& deviceContext) {
951 std::lock_guard<std::mutex> lock(mutex);
952 return (pendingRegionInfos.empty() ==
false) || deviceContext.expectedRegionCallbacks > 0;
959 while (hasPendingEvents(deviceContext)) {
961 uv_run(
state.loop, UV_RUN_ONCE);
965 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
969 O2_SIGNPOST_END(device, cid,
"InitTask",
"Done waiting for registration events.");
976 bool enableRateLimiting = std::stoi(fConfig->GetValue<std::string>(
"timeframes-rate-limit"));
985 if (enableRateLimiting ==
false && spec.name.find(
"internal-dpl-injected-dummy-sink") != std::string::npos) {
988 if (enableRateLimiting) {
989 for (
auto& spec : spec.outputs) {
990 if (spec.matcher.binding.value ==
"dpl-summary") {
997 context.
registry = &mServiceRegistry;
1000 if (context.
error !=
nullptr) {
1014 errorCallback(errorContext);
1028 switch (deviceContext.processingPolicies.
error) {
1039 auto decideEarlyForward = [&context, &deviceContext, &spec,
this]() ->
bool {
1043 bool onlyConditions =
true;
1044 bool overriddenEarlyForward =
false;
1045 for (
auto& forwarded : spec.forwards) {
1046 if (forwarded.matcher.lifetime != Lifetime::Condition) {
1047 onlyConditions =
false;
1051 overriddenEarlyForward =
true;
1055 if (forwarded.matcher.lifetime == Lifetime::Optional) {
1057 overriddenEarlyForward =
true;
1062 if (!overriddenEarlyForward && onlyConditions) {
1064 LOG(detail) <<
"Enabling early forwarding because only conditions to be forwarded";
1066 return canForwardEarly;
1078 state.quitRequested =
false;
1081 for (
auto& info :
state.inputChannelInfos) {
1093 for (
size_t i = 0;
i < mStreams.size(); ++
i) {
1096 context.preStartStreamCallbacks(streamRef);
1098 }
catch (std::exception& e) {
1099 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"PreRun",
"Exception of type std::exception caught in PreRun: %{public}s. Rethrowing.", e.what());
1100 O2_SIGNPOST_END(device, cid,
"PreRun",
"Exiting PreRun due to exception thrown.");
1104 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"PreRun",
"Exception of type o2::framework::RuntimeErrorRef caught in PreRun: %{public}s. Rethrowing.", err.what);
1105 O2_SIGNPOST_END(device, cid,
"PreRun",
"Exiting PreRun due to exception thrown.");
1108 O2_SIGNPOST_END(device, cid,
"PreRun",
"Unknown exception being thrown. Rethrowing.");
1116 using o2::monitoring::Metric;
1117 using o2::monitoring::Monitoring;
1118 using o2::monitoring::tags::Key;
1119 using o2::monitoring::tags::Value;
1122 monitoring.send(
Metric{(uint64_t)1,
"device_state"}.addTag(Key::Subsystem, Value::DPL));
1130 using o2::monitoring::Metric;
1131 using o2::monitoring::Monitoring;
1132 using o2::monitoring::tags::Key;
1133 using o2::monitoring::tags::Value;
1136 monitoring.send(
Metric{(uint64_t)0,
"device_state"}.addTag(Key::Subsystem, Value::DPL));
1155 bool firstLoop =
true;
1157 O2_SIGNPOST_START(device, lid,
"device_state",
"First iteration of the device loop");
1159 bool dplEnableMultithreding = getenv(
"DPL_THREADPOOL_SIZE") !=
nullptr;
1160 if (dplEnableMultithreding) {
1161 setenv(
"UV_THREADPOOL_SIZE",
"1", 1);
1165 if (
state.nextFairMQState.empty() ==
false) {
1166 (
void)this->ChangeState(
state.nextFairMQState.back());
1167 state.nextFairMQState.pop_back();
1172 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1185 state.lastActiveDataProcessor.compare_exchange_strong(lastActive,
nullptr);
1187 auto shouldNotWait = (lastActive !=
nullptr &&
1191 shouldNotWait =
true;
1194 if (lastActive !=
nullptr) {
1197 if (NewStatePending()) {
1199 shouldNotWait =
true;
1205 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"State transition requested and we are now in Idle. We can consider it to be completed.");
1208 if (
state.severityStack.empty() ==
false) {
1209 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
1210 state.severityStack.pop_back();
1216 state.firedTimers.clear();
1218 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
1219 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
1226 O2_SIGNPOST_START(device, lid,
"run_loop",
"Dropping message from slot %" PRIu64
". Forwarding as needed.", (uint64_t)slot.index);
1234 forwardInputs(registry, slot, dropped, oldestOutputInfo,
false,
true);
1239 auto oldestPossibleTimeslice = relayer.getOldestPossibleOutput();
1241 if (shouldNotWait ==
false) {
1245 O2_SIGNPOST_END(device, lid,
"run_loop",
"Run loop completed. %{}s", shouldNotWait ?
"Will immediately schedule a new one" :
"Waiting for next event.");
1246 uv_run(
state.loop, shouldNotWait ? UV_RUN_NOWAIT : UV_RUN_ONCE);
1248 if ((
state.loopReason &
state.tracingFlags) != 0) {
1249 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
1250 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
1251 }
else if (
state.severityStack.empty() ==
false) {
1252 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
1253 state.severityStack.pop_back();
1258 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"Out of band activity detected. Rescanning everything.");
1262 if (!
state.pendingOffers.empty()) {
1263 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"Pending %" PRIu64
" offers. updating the ComputingQuotaEvaluator.", (uint64_t)
state.pendingOffers.size());
1275 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1279 assert(mStreams.size() == mHandles.size());
1282 for (
size_t ti = 0; ti < mStreams.size(); ti++) {
1283 auto& taskInfo = mStreams[ti];
1284 if (taskInfo.running) {
1288 streamRef.index = ti;
1290 using o2::monitoring::Metric;
1291 using o2::monitoring::Monitoring;
1292 using o2::monitoring::tags::Key;
1293 using o2::monitoring::tags::Value;
1296 if (streamRef.index != -1) {
1299 uv_work_t& handle = mHandles[streamRef.index];
1301 handle.data = &mStreams[streamRef.index];
1309 dpStats.processCommandQueue();
1319 struct SchedulingStats {
1320 std::atomic<size_t> lastScheduled = 0;
1321 std::atomic<size_t> numberOfUnscheduledSinceLastScheduled = 0;
1322 std::atomic<size_t> numberOfUnscheduled = 0;
1323 std::atomic<size_t> numberOfScheduled = 0;
1325 static SchedulingStats schedulingStats;
1330 stream.registry = &mServiceRegistry;
1331 schedulingStats.lastScheduled = uv_now(
state.loop);
1332 schedulingStats.numberOfScheduled++;
1333 schedulingStats.numberOfUnscheduledSinceLastScheduled = 0;
1334 O2_SIGNPOST_EVENT_EMIT(scheduling, sid,
"Run",
"Enough resources to schedule computation on stream %d", streamRef.index);
1335 if (dplEnableMultithreding) [[unlikely]] {
1343 if (schedulingStats.numberOfUnscheduledSinceLastScheduled > 100 ||
1344 (uv_now(
state.loop) - schedulingStats.lastScheduled) > 30000) {
1346 "Not enough resources to schedule computation. %zu skipped so far. Last scheduled at %zu.",
1347 schedulingStats.numberOfUnscheduledSinceLastScheduled.load(),
1348 schedulingStats.lastScheduled.load());
1351 "Not enough resources to schedule computation. %zu skipped so far. Last scheduled at %zu.",
1352 schedulingStats.numberOfUnscheduledSinceLastScheduled.load(),
1353 schedulingStats.lastScheduled.load());
1355 schedulingStats.numberOfUnscheduled++;
1356 schedulingStats.numberOfUnscheduledSinceLastScheduled++;
1363 O2_SIGNPOST_END(device, lid,
"run_loop",
"Run loop completed. Transition handling state %d.", (
int)
state.transitionHandling);
1366 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
1367 auto& info =
state.inputChannelInfos[ci];
1368 info.parts.fParts.clear();
1379 O2_SIGNPOST_START(device, dpid,
"do_prepare",
"Starting DataProcessorContext::doPrepare.");
1397 context.allDone = std::any_of(
state.inputChannelInfos.begin(),
state.inputChannelInfos.end(), [cid](
const auto& info) {
1399 O2_SIGNPOST_EVENT_EMIT(device, cid,
"do_prepare",
"Input channel %{public}s%{public}s has %zu parts left and is in state %d.",
1400 info.channel->GetName().c_str(), (info.id.value == ChannelIndex::INVALID ?
" (non DPL)" :
""), info.parts.fParts.size(), (int)info.state);
1402 O2_SIGNPOST_EVENT_EMIT(device, cid,
"do_prepare",
"External channel %d is in state %d.", info.id.value, (int)info.state);
1407 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"do_prepare",
"Processing %zu input channels.", spec.inputChannels.size());
1410 static std::vector<int> pollOrder;
1411 pollOrder.resize(
state.inputChannelInfos.size());
1412 std::iota(pollOrder.begin(), pollOrder.end(), 0);
1413 std::sort(pollOrder.begin(), pollOrder.end(), [&infos =
state.inputChannelInfos](
int a,
int b) {
1414 return infos[a].oldestForChannel.value < infos[b].oldestForChannel.value;
1418 if (pollOrder.empty()) {
1419 O2_SIGNPOST_END(device, dpid,
"do_prepare",
"Nothing to poll. Waiting for next iteration.");
1422 auto currentOldest =
state.inputChannelInfos[pollOrder.front()].oldestForChannel;
1423 auto currentNewest =
state.inputChannelInfos[pollOrder.back()].oldestForChannel;
1424 auto delta = currentNewest.value - currentOldest.value;
1425 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"do_prepare",
"Oldest possible timeframe range %" PRIu64
" => %" PRIu64
" delta %" PRIu64,
1426 (int64_t)currentOldest.value, (int64_t)currentNewest.value, (int64_t)delta);
1427 auto& infos =
state.inputChannelInfos;
1429 if (context.balancingInputs) {
1431 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));
1432 auto newEnd = std::remove_if(pollOrder.begin(), pollOrder.end(), [&infos, limitNew = currentOldest.value + ahead](
int a) ->
bool {
1433 return infos[a].oldestForChannel.value > limitNew;
1435 for (
auto it = pollOrder.begin(); it < pollOrder.end(); it++) {
1436 const auto& channelInfo =
state.inputChannelInfos[*it];
1442 bool shouldBeRunning = it < newEnd;
1443 if (running != shouldBeRunning) {
1444 uv_poll_start(poller, shouldBeRunning ? UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED : 0, &
on_socket_polled);
1450 pollOrder.erase(newEnd, pollOrder.end());
1452 O2_SIGNPOST_END(device, dpid,
"do_prepare",
"%zu channels pass the channel inbalance balance check.", pollOrder.size());
1454 for (
auto sci : pollOrder) {
1455 auto& info =
state.inputChannelInfos[sci];
1456 auto& channelSpec = spec.inputChannels[sci];
1458 O2_SIGNPOST_START(device, cid,
"channels",
"Processing channel %s", channelSpec.name.c_str());
1461 context.allDone =
false;
1466 if (info.parts.Size()) {
1469 O2_SIGNPOST_END(device, cid,
"channels",
"Flushing channel %s which is in state %d and has %zu parts still pending.",
1470 channelSpec.name.c_str(), (
int)info.state, info.parts.Size());
1473 if (info.
channel ==
nullptr) {
1474 O2_SIGNPOST_END(device, cid,
"channels",
"Channel %s which is in state %d is nullptr and has %zu parts still pending.",
1475 channelSpec.name.c_str(), (
int)info.state, info.parts.Size());
1480 O2_SIGNPOST_END(device, cid,
"channels",
"Channel %s which is in state %d is not a DPL channel and has %zu parts still pending.",
1481 channelSpec.name.c_str(), (
int)info.state, info.parts.Size());
1484 auto& socket = info.
channel->GetSocket();
1489 if (info.hasPendingEvents == 0) {
1490 socket.Events(&info.hasPendingEvents);
1492 if ((info.hasPendingEvents & 1) == 0 && (info.parts.Size() == 0)) {
1493 O2_SIGNPOST_END(device, cid,
"channels",
"No pending events and no remaining parts to process for channel %{public}s", channelSpec.name.c_str());
1499 info.readPolled =
false;
1508 bool newMessages =
false;
1510 O2_SIGNPOST_EVENT_EMIT(device, cid,
"channels",
"Receiving loop called for channel %{public}s (%d) with oldest possible timeslice %zu",
1511 channelSpec.name.c_str(), info.id.value, info.oldestForChannel.value);
1512 if (info.parts.Size() < 64) {
1513 fair::mq::Parts parts;
1514 info.
channel->Receive(parts, 0);
1516 O2_SIGNPOST_EVENT_EMIT(device, cid,
"channels",
"Received %zu parts from channel %{public}s (%d).", parts.Size(), channelSpec.name.c_str(), info.id.value);
1518 for (
auto&& part : parts) {
1519 info.parts.fParts.emplace_back(std::move(part));
1521 newMessages |=
true;
1524 if (info.parts.Size() >= 0) {
1536 socket.Events(&info.hasPendingEvents);
1537 if (info.hasPendingEvents) {
1538 info.readPolled =
false;
1541 state.lastActiveDataProcessor.store(&context);
1544 O2_SIGNPOST_END(device, cid,
"channels",
"Done processing channel %{public}s (%d).",
1545 channelSpec.name.c_str(), info.id.value);
1560 context.completed.clear();
1561 context.completed.reserve(16);
1563 state.lastActiveDataProcessor.store(&context);
1567 context.preDanglingCallbacks(danglingContext);
1568 if (
state.lastActiveDataProcessor.load() ==
nullptr) {
1571 auto activity =
ref.get<
DataRelayer>().processDanglingInputs(context.expirationHandlers, *context.registry,
true);
1572 if (activity.expiredSlots > 0) {
1573 state.lastActiveDataProcessor = &context;
1576 context.completed.clear();
1578 state.lastActiveDataProcessor = &context;
1581 context.postDanglingCallbacks(danglingContext);
1589 state.lastActiveDataProcessor = &context;
1612 timingInfo.timeslice = relayer.getOldestPossibleOutput().timeslice.value;
1613 timingInfo.tfCounter = -1;
1614 timingInfo.firstTForbit = -1;
1616 timingInfo.creation = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count();
1617 O2_SIGNPOST_EVENT_EMIT(calibration, dpid,
"calibration",
"TimingInfo.keepAtEndOfStream %d", timingInfo.keepAtEndOfStream);
1621 context.preEOSCallbacks(eosContext);
1625 streamContext.postEOSCallbacks(eosContext);
1626 context.postEOSCallbacks(eosContext);
1628 for (
auto& channel : spec.outputChannels) {
1629 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"state",
"Sending end of stream to %{public}s.", channel.name.c_str());
1636 if (shouldProcess) {
1637 state.lastActiveDataProcessor = &context;
1641 for (
auto& poller :
state.activeOutputPollers) {
1642 uv_poll_stop(poller);
1650 for (
auto& poller :
state.activeOutputPollers) {
1651 uv_poll_stop(poller);
1667 if (deviceContext.sigusr1Handle) {
1673 handle->data =
nullptr;
1702 auto getInputTypes = [&info, &context]() -> std::optional<std::vector<InputInfo>> {
1707 auto& parts = info.
parts;
1710 std::vector<InputInfo> results;
1712 results.reserve(parts.Size() / 2);
1713 size_t nTotalPayloads = 0;
1717 if (
type != InputType::Invalid &&
length > 1) {
1718 nTotalPayloads +=
length - 1;
1722 for (
size_t pi = 0; pi < parts.Size(); pi += 2) {
1723 auto* headerData = parts.At(pi)->GetData();
1724 auto sih = o2::header::get<SourceInfoHeader*>(headerData);
1725 auto dh = o2::header::get<DataHeader*>(headerData);
1727 O2_SIGNPOST_EVENT_EMIT(device, cid,
"handle_data",
"Got SourceInfoHeader with state %d", (
int)sih->state);
1728 info.
state = sih->state;
1729 insertInputInfo(pi, 2, InputType::SourceInfo, info.
id);
1730 state.lastActiveDataProcessor = &context;
1732 LOGP(
error,
"Found data attached to a SourceInfoHeader");
1736 auto dih = o2::header::get<DomainInfoHeader*>(headerData);
1738 O2_SIGNPOST_EVENT_EMIT(device, cid,
"handle_data",
"Got DomainInfoHeader with oldestPossibleTimeslice %d", (
int)dih->oldestPossibleTimeslice);
1739 insertInputInfo(pi, 2, InputType::DomainInfo, info.
id);
1740 state.lastActiveDataProcessor = &context;
1742 LOGP(
error,
"Found data attached to a DomainInfoHeader");
1747 insertInputInfo(pi, 0, InputType::Invalid, info.
id);
1751 if (dh->payloadSize > parts.At(pi + 1)->GetSize()) {
1752 insertInputInfo(pi, 0, InputType::Invalid, info.
id);
1756 auto dph = o2::header::get<DataProcessingHeader*>(headerData);
1761 O2_SIGNPOST_START(parts,
pid,
"parts",
"Processing DataHeader %{public}-4s/%{public}-16s/%d with splitPayloadParts %d and splitPayloadIndex %d",
1762 dh->dataOrigin.str, dh->dataDescription.str, dh->subSpecification, dh->splitPayloadParts, dh->splitPayloadIndex);
1764 insertInputInfo(pi, 2, InputType::Invalid, info.
id);
1768 if (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) {
1771 insertInputInfo(pi, dh->splitPayloadParts + 1, InputType::Data, info.
id);
1772 pi += dh->splitPayloadParts - 1;
1778 size_t finalSplitPayloadIndex = pi + (dh->splitPayloadParts > 0 ? dh->splitPayloadParts : 1) * 2;
1779 if (finalSplitPayloadIndex > parts.Size()) {
1781 insertInputInfo(pi, 0, InputType::Invalid, info.
id);
1784 insertInputInfo(pi, 2, InputType::Data, info.
id);
1785 for (; pi + 2 < finalSplitPayloadIndex; pi += 2) {
1786 insertInputInfo(pi + 2, 2, InputType::Data, info.
id);
1790 if (results.size() + nTotalPayloads != parts.Size()) {
1791 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"handle_data",
"inconsistent number of inputs extracted. %zu vs parts (%zu)", results.size() + nTotalPayloads, parts.Size());
1792 return std::nullopt;
1797 auto reportError = [
ref](
const char*
message) {
1802 auto handleValidMessages = [&info,
ref, &reportError](std::vector<InputInfo>
const& inputInfos) {
1806 auto& parts = info.
parts;
1809 bool hasBackpressure =
false;
1810 size_t minBackpressureTimeslice = -1;
1812 size_t oldestPossibleTimeslice = -1;
1813 static std::vector<int> ordering;
1815 ordering.resize(inputInfos.size());
1816 std::iota(ordering.begin(), ordering.end(), 0);
1818 std::stable_sort(ordering.begin(), ordering.end(), [&inputInfos](
int const&
a,
int const&
b) {
1819 auto const& ai = inputInfos[a];
1820 auto const& bi = inputInfos[b];
1821 if (ai.type != bi.type) {
1822 return ai.type < bi.type;
1824 return ai.position < bi.position;
1826 for (
size_t ii = 0; ii < inputInfos.size(); ++ii) {
1827 auto const& input = inputInfos[ordering[ii]];
1828 switch (input.type) {
1829 case InputType::Data: {
1831 auto headerIndex = input.position;
1833 auto nPayloadsPerHeader = 0;
1834 if (input.size > 2) {
1836 nMessages = input.size;
1837 nPayloadsPerHeader = nMessages - 1;
1840 auto dh = o2::header::get<DataHeader*>(parts.At(headerIndex)->GetData());
1841 nMessages = dh->splitPayloadParts > 0 ? dh->splitPayloadParts * 2 : 2;
1842 nPayloadsPerHeader = 1;
1843 ii += (nMessages / 2) - 1;
1847 O2_SIGNPOST_EVENT_EMIT(async_queue, cid,
"onDrop",
"Dropping message from slot %zu. Forwarding as needed. Timeslice %zu",
1848 slot.
index, oldestOutputInfo.timeslice.value);
1855 forwardInputs(
ref, slot, dropped, oldestOutputInfo,
false,
true);
1857 auto relayed = relayer.relay(parts.At(headerIndex)->GetData(),
1858 &parts.At(headerIndex),
1863 switch (relayed.type) {
1866 LOGP(alarm,
"Backpressure on channel {}. Waiting.", info.
channel->GetName());
1867 auto& monitoring =
ref.get<o2::monitoring::Monitoring>();
1868 monitoring.send(o2::monitoring::Metric{1, fmt::format(
"backpressure_{}", info.
channel->GetName())});
1872 policy.backpressure(info);
1873 hasBackpressure =
true;
1874 minBackpressureTimeslice = std::min<size_t>(minBackpressureTimeslice, relayed.timeslice.value);
1880 LOGP(info,
"Back to normal on channel {}.", info.
channel->GetName());
1881 auto& monitoring =
ref.get<o2::monitoring::Monitoring>();
1882 monitoring.send(o2::monitoring::Metric{0, fmt::format(
"backpressure_{}", info.
channel->GetName())});
1889 case InputType::SourceInfo: {
1890 LOGP(detail,
"Received SourceInfo");
1892 state.lastActiveDataProcessor = &context;
1893 auto headerIndex = input.position;
1894 auto payloadIndex = input.position + 1;
1895 assert(payloadIndex < parts.Size());
1898 parts.At(headerIndex).reset(
nullptr);
1899 parts.At(payloadIndex).reset(
nullptr);
1906 case InputType::DomainInfo: {
1910 state.lastActiveDataProcessor = &context;
1911 auto headerIndex = input.position;
1912 auto payloadIndex = input.position + 1;
1913 assert(payloadIndex < parts.Size());
1917 auto dih = o2::header::get<DomainInfoHeader*>(parts.At(headerIndex)->GetData());
1918 if (hasBackpressure && dih->oldestPossibleTimeslice >= minBackpressureTimeslice) {
1921 oldestPossibleTimeslice = std::min(oldestPossibleTimeslice, dih->oldestPossibleTimeslice);
1922 LOGP(
debug,
"Got DomainInfoHeader, new oldestPossibleTimeslice {} on channel {}", oldestPossibleTimeslice, info.
id.
value);
1923 parts.At(headerIndex).reset(
nullptr);
1924 parts.At(payloadIndex).reset(
nullptr);
1926 case InputType::Invalid: {
1927 reportError(
"Invalid part found.");
1933 if (oldestPossibleTimeslice != (
size_t)-1) {
1936 context.domainInfoUpdatedCallback(*context.registry, oldestPossibleTimeslice, info.
id);
1938 state.lastActiveDataProcessor = &context;
1940 auto it = std::remove_if(parts.fParts.begin(), parts.fParts.end(), [](
auto&
msg) ->
bool { return msg.get() == nullptr; });
1941 parts.fParts.erase(it, parts.end());
1942 if (parts.fParts.size()) {
1943 LOG(
debug) << parts.fParts.size() <<
" messages backpressured";
1955 auto inputTypes = getInputTypes();
1956 if (
bool(inputTypes) ==
false) {
1957 reportError(
"Parts should come in couples. Dropping it.");
1960 handleValidMessages(*inputTypes);
1966struct InputLatency {
1971auto calculateInputRecordLatency(
InputRecord const& record, uint64_t currentTime) -> InputLatency
1975 for (
auto& item : record) {
1976 auto* header = o2::header::get<DataProcessingHeader*>(item.header);
1977 if (header ==
nullptr) {
1980 int64_t partLatency = (0x7fffffffffffffff & currentTime) - (0x7fffffffffffffff & header->creation);
1981 if (partLatency < 0) {
1984 result.minLatency = std::min(
result.minLatency, (uint64_t)partLatency);
1985 result.maxLatency = std::max(
result.maxLatency, (uint64_t)partLatency);
1990auto calculateTotalInputRecordSize(
InputRecord const& record) ->
int
1992 size_t totalInputSize = 0;
1993 for (
auto& item : record) {
1994 auto* header = o2::header::get<DataHeader*>(item.header);
1995 if (header ==
nullptr) {
1998 totalInputSize += header->payloadSize;
2000 return totalInputSize;
2003template <
typename T>
2004void update_maximum(std::atomic<T>& maximum_value, T
const&
value)
noexcept
2006 T prev_value = maximum_value;
2007 while (prev_value <
value &&
2008 !maximum_value.compare_exchange_weak(prev_value,
value)) {
2016 LOGP(
debug,
"DataProcessingDevice::tryDispatchComputation");
2021 std::vector<MessageSet> currentSetOfInputs;
2024 auto getInputSpan = [
ref, ¤tSetOfInputs](
TimesliceSlot slot,
bool consume =
true) {
2029 currentSetOfInputs = relayer.consumeExistingInputsForTimeslice(slot);
2031 auto getter = [¤tSetOfInputs](
size_t i,
size_t partindex) ->
DataRef {
2032 if (currentSetOfInputs[
i].getNumberOfPairs() > partindex) {
2033 const char* headerptr =
nullptr;
2034 const char* payloadptr =
nullptr;
2035 size_t payloadSize = 0;
2041 auto const& headerMsg = currentSetOfInputs[
i].associatedHeader(partindex);
2042 auto const& payloadMsg = currentSetOfInputs[
i].associatedPayload(partindex);
2043 headerptr =
static_cast<char const*
>(headerMsg->GetData());
2044 payloadptr = payloadMsg ?
static_cast<char const*
>(payloadMsg->GetData()) :
nullptr;
2045 payloadSize = payloadMsg ? payloadMsg->GetSize() : 0;
2046 return DataRef{
nullptr, headerptr, payloadptr, payloadSize};
2050 auto nofPartsGetter = [¤tSetOfInputs](
size_t i) ->
size_t {
2051 return currentSetOfInputs[
i].getNumberOfPairs();
2053 auto refCountGetter = [¤tSetOfInputs](
size_t idx) ->
int {
2054 auto& header =
static_cast<const fair::mq::shmem::Message&
>(*currentSetOfInputs[idx].header(0));
2055 return header.GetRefCount();
2057 return InputSpan{getter, nofPartsGetter, refCountGetter, currentSetOfInputs.
size()};
2072 auto timeslice = relayer.getTimesliceForSlot(
i);
2074 timingInfo.timeslice = timeslice.value;
2084 auto timeslice = relayer.getTimesliceForSlot(
i);
2086 timingInfo.globalRunNumberChanged = !
TimingInfo::timesliceIsTimer(timeslice.value) && dataProcessorContext.lastRunNumberProcessed != timingInfo.runNumber;
2088 timingInfo.globalRunNumberChanged &= (dataProcessorContext.lastRunNumberProcessed == -1 || timingInfo.runNumber != 0);
2092 timingInfo.streamRunNumberChanged = timingInfo.globalRunNumberChanged;
2100 assert(record.size() == currentSetOfInputs.size());
2101 for (
size_t ii = 0, ie = record.size(); ii < ie; ++ii) {
2105 DataRef input = record.getByPos(ii);
2109 if (input.
header ==
nullptr) {
2113 currentSetOfInputs[ii].clear();
2124 for (
size_t pi = 0, pe = record.size(); pi < pe; ++pi) {
2125 DataRef input = record.getByPos(pi);
2126 if (input.
header ==
nullptr) {
2129 auto sih = o2::header::get<SourceInfoHeader*>(input.
header);
2134 auto dh = o2::header::get<DataHeader*>(input.
header);
2144 if (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) {
2147 pi += dh->splitPayloadParts - 1;
2149 size_t pi = pi + (dh->splitPayloadParts > 0 ? dh->splitPayloadParts : 1) * 2;
2155 if (completed.empty() ==
true) {
2156 LOGP(
debug,
"No computations available for dispatching.");
2163 std::atomic_thread_fence(std::memory_order_release);
2164 char relayerSlotState[1024];
2166 char*
buffer = relayerSlotState + written;
2167 for (
size_t ai = 0; ai != record.size(); ai++) {
2168 buffer[ai] = record.isValid(ai) ?
'3' :
'0';
2170 buffer[record.size()] = 0;
2172 .size = (
int)(record.size() +
buffer - relayerSlotState),
2173 .
data = relayerSlotState});
2174 uint64_t tEnd = uv_hrtime();
2176 int64_t wallTimeMs = (tEnd - tStart) / 1000000;
2184 auto latency = calculateInputRecordLatency(record, tStartMilli);
2187 static int count = 0;
2194 std::atomic_thread_fence(std::memory_order_release);
2195 char relayerSlotState[1024];
2197 char*
buffer = strchr(relayerSlotState,
' ') + 1;
2198 for (
size_t ai = 0; ai != record.size(); ai++) {
2199 buffer[ai] = record.isValid(ai) ?
'2' :
'0';
2201 buffer[record.size()] = 0;
2219 switch (spec.completionPolicy.order) {
2221 std::sort(completed.begin(), completed.end(), [](
auto const&
a,
auto const&
b) { return a.timeslice.value < b.timeslice.value; });
2224 std::sort(completed.begin(), completed.end(), [](
auto const&
a,
auto const&
b) { return a.slot.index < b.slot.index; });
2231 for (
auto action : completed) {
2233 O2_SIGNPOST_START(device, aid,
"device",
"Processing action on slot %lu for action %{public}s", action.
slot.
index, fmt::format(
"{}", action.
op).c_str());
2257 dpContext.preProcessingCallbacks(processContext);
2260 context.postDispatchingCallbacks(processContext);
2261 if (spec.forwards.empty() ==
false) {
2263 forwardInputs(
ref, action.
slot, currentSetOfInputs, timesliceIndex.getOldestPossibleOutput(),
false);
2264 O2_SIGNPOST_END(device, aid,
"device",
"Forwarding inputs consume: %d.",
false);
2272 bool hasForwards = spec.forwards.empty() ==
false;
2275 if (context.canForwardEarly && hasForwards && consumeSomething) {
2276 O2_SIGNPOST_EVENT_EMIT(device, aid,
"device",
"Early forwainding: %{public}s.", fmt::format(
"{}", action.
op).c_str());
2280 markInputsAsDone(action.
slot);
2282 uint64_t tStart = uv_hrtime();
2284 preUpdateStats(action, record, tStart);
2286 static bool noCatch = getenv(
"O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv(
"O2_NO_CATCHALL_EXCEPTIONS"),
"0");
2294 switch (action.
op) {
2305 if (
state.quitRequested ==
false) {
2309 streamContext.preProcessingCallbacks(processContext);
2315 if (context.statefulProcess && shouldProcess(action)) {
2319 (context.statefulProcess)(processContext);
2321 }
else if (context.statelessProcess && shouldProcess(action)) {
2323 (context.statelessProcess)(processContext);
2325 }
else if (context.statelessProcess || context.statefulProcess) {
2328 O2_SIGNPOST_EVENT_EMIT(device, pcid,
"device",
"No processing callback provided. Switching to %{public}s.",
"Idle");
2331 if (shouldProcess(action)) {
2333 if (timingInfo.globalRunNumberChanged) {
2334 context.lastRunNumberProcessed = timingInfo.runNumber;
2351 streamContext.finaliseOutputsCallbacks(processContext);
2357 streamContext.postProcessingCallbacks(processContext);
2363 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
2364 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
2370 (context.errorHandling)(e, record);
2375 }
catch (std::exception& ex) {
2380 (context.errorHandling)(e, record);
2382 (context.errorHandling)(e, record);
2385 if (
state.severityStack.empty() ==
false) {
2386 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
2387 state.severityStack.pop_back();
2390 postUpdateStats(action, record, tStart, tStartMilli);
2394 cleanupRecord(record);
2395 context.postDispatchingCallbacks(processContext);
2398 if ((context.canForwardEarly ==
false) && hasForwards && consumeSomething) {
2403 context.postForwardingCallbacks(processContext);
2405 cleanTimers(action.
slot, record);
2407 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());
2409 O2_SIGNPOST_END(device, sid,
"device",
"Start processing ready actions");
2413 LOGP(detail,
"Broadcasting end of stream");
2414 for (
auto& channel : spec.outputChannels) {
2437 cfg.getRecursive(
name);
2438 std::vector<std::unique_ptr<ParamRetriever>> retrievers;
2439 retrievers.emplace_back(std::make_unique<ConfigurationOptionsRetriever>(&cfg,
name));
2440 auto configStore = std::make_unique<ConfigParamStore>(options, std::move(retrievers));
2441 configStore->preload();
2442 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< MessageSet > consumeAllInputsForTimeslice(TimesliceSlot id)
uint64_t getCreationTimeForSlot(TimesliceSlot slot)
Get the creation time associated to a given slot.
ActivityStats processDanglingInputs(std::vector< ExpirationHandler > const &, ServiceRegistryRef context, bool createNew)
uint32_t getFirstTFCounterForSlot(TimesliceSlot slot)
Get the firstTFCounter associate to a given slot.
A service API to communicate with the driver.
bool active() const
Check if service of type T is currently active.
GLuint const GLchar * name
GLboolean GLboolean GLboolean b
GLsizei const GLfloat * value
GLint GLint GLsizei GLint GLenum GLenum type
GLuint GLsizei GLsizei * length
typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode)
GLuint GLsizei const GLchar * message
GLboolean GLboolean GLboolean GLboolean a
Defining PrimaryVertex explicitly as messageable.
auto decongestionCallbackLate
RuntimeErrorRef runtime_error(const char *)
ServiceKind
The kind of service we are asking for.
void on_idle_timer(uv_timer_t *handle)
@ DPL
The channel is a normal input channel.
void run_completion(uv_work_t *handle, int status)
void on_socket_polled(uv_poll_t *poller, int status, int events)
void run_callback(uv_work_t *handle)
volatile int region_read_global_dummy_variable
void handleRegionCallbacks(ServiceRegistryRef registry, std::vector< fair::mq::RegionInfo > &infos)
Invoke the callbacks for the mPendingRegionInfos.
void on_out_of_band_polled(uv_poll_t *poller, int status, int events)
DeviceSpec const & getRunningDevice(RunningDeviceRef const &running, ServiceRegistryRef const &services)
@ EndOfStreaming
End of streaming requested, but not notified.
@ Streaming
Data is being processed.
@ Idle
End of streaming notified.
void on_communication_requested(uv_async_t *s)
@ Expired
A transition needs to be fullfilled ASAP.
@ NoTransition
No pending transitions.
@ Requested
A transition was notified to be requested.
RuntimeError & error_from_ref(RuntimeErrorRef)
void on_awake_main_thread(uv_async_t *handle)
@ SHM_OFFER_BYTES_CONSUMED
@ 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 ...
Defining DataPointCompositeObject explicitly as copiable.
static void run(AsyncQueue &queue, TimesliceId oldestPossibleTimeslice)
static void post(AsyncQueue &queue, AsyncTask const &task)
An actuatual task to be executed.
static void demangled_backtrace_symbols(void **backtrace, unsigned int total, int fd)
static constexpr int INVALID
CompletionOp
Action to take with the InputRecord:
@ Retry
Like Wait but mark the cacheline as dirty.
int64_t 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 std::vector< fair::mq::Parts > routeForwardedMessageSet(FairMQDeviceProxy &proxy, std::vector< MessageSet > ¤tSetOfInputs, bool copy, bool consume)
Helper to route messages for forwarding.
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)
Helper struct to hold statistics about the data processing happening.
@ CumulativeRate
Set the value to the specified value if it is positive.
@ Add
Update the rate of the metric given the amount since the last time.
void updateStats(CommandSpec cmd)
std::function< void(o2::framework::RuntimeErrorRef e, InputRecord &record)> errorHandling
AlgorithmSpec::InitErrorCallback initError
void preLoopCallbacks(ServiceRegistryRef)
Invoke callbacks before we enter the event loop.
void postStopCallbacks(ServiceRegistryRef)
Invoke callbacks on stop.
void preProcessingCallbacks(ProcessingContext &)
Invoke callbacks to be executed before every process method invokation.
ServiceRegistry * registry
bool canForwardEarly
Wether or not the associated DataProcessor can forward things early.
AlgorithmSpec::ErrorCallback error
void preStartCallbacks(ServiceRegistryRef)
Invoke callbacks to be executed in PreRun(), before the User Start callbacks.
AlgorithmSpec::ProcessCallback statefulProcess
static std::vector< size_t > createDistinctRouteIndex(std::vector< InputRoute > const &)
CompletionPolicy::CompletionOp op
@ Invalid
Ownership of the data has been taken.
@ Backpressured
The incoming data was not valid and has been dropped.
@ Dropped
The incoming data was not relayed, because we are backpressured.
static bool partialMatch(InputSpec const &spec, o2::header::DataOrigin const &origin)
static std::string describe(InputSpec const &spec)
TimesliceIndex::OldestOutputInfo oldestTimeslice
static unsigned int pipelineLength()
get max number of timeslices in the queue
static std::unique_ptr< ConfigParamStore > getConfiguration(ServiceRegistryRef registry, const char *name, std::vector< ConfigParamSpec > const &options)
uv_signal_t * sigusr1Handle
ProcessingPolicies & processingPolicies
int expectedRegionCallbacks
Running state information of a given device.
uv_async_t * awakeMainThread
std::atomic< int64_t > cleanupCount
Forward channel information.
ChannelAccountingType channelType
Wether or not it's a DPL internal channel.
fair::mq::Channel & channel
std::string name
The name of the channel.
ForwardingPolicy const * policy
ForwardingCallback forward
InputChannelInfo * channelInfo
fair::mq::Socket * socket
DataProcessingDevice * device
enum EarlyForwardPolicy earlyForward
Information about the running workflow.
static Salt streamSalt(short streamId, short dataProcessorId)
void lateBindStreamServices(DeviceState &state, fair::mq::ProgOptions &options, ServiceRegistry::Salt salt)
static Salt globalStreamSalt(short streamId)
static Salt globalDeviceSalt()
void * get(ServiceTypeHash typeHash, Salt salt, ServiceKind kind, char const *name=nullptr) const
void finaliseOutputsCallbacks(ProcessingContext &)
Invoke callbacks to be executed after every process method invokation.
void preProcessingCallbacks(ProcessingContext &pcx)
Invoke callbacks to be executed before every process method invokation.
void preEOSCallbacks(EndOfStreamContext &eosContext)
Invoke callbacks to be executed before every EOS user callback invokation.
void postProcessingCallbacks(ProcessingContext &pcx)
Invoke callbacks to be executed after every process method invokation.
static int64_t getRealtimeSinceEpochStandalone()
bool keepAtEndOfStream
Wether this kind of data should be flushed during end of stream.
static bool timesliceIsTimer(size_t timeslice)
static TimesliceId getTimeslice(data_matcher::VariableContext const &variables)
void backpressure(InputChannelInfo const &)
locked_execution(ServiceRegistryRef &ref_)
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"
uint64_t const void const *restrict const msg