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#if __has_include(<fairmq/shmem/Message.h>)
63#include <fairmq/shmem/Message.h>
65#include <Configuration/ConfigurationInterface.h>
66#include <Configuration/ConfigurationFactory.h>
67#include <Monitoring/Monitoring.h>
69#include <TClonesArray.h>
71#include <fmt/ostream.h>
79#include <boost/property_tree/json_parser.hpp>
137 return devices[running.
index];
147 : mRunningDevice{running},
148 mConfigRegistry{nullptr},
149 mServiceRegistry{registry}
151 GetConfig()->Subscribe<std::string>(
"dpl", [®istry = mServiceRegistry](
const std::string&
key, std::string
value) {
152 if (
key ==
"cleanup") {
156 int64_t newCleanupCount = std::stoll(
value);
157 if (newCleanupCount <= cleanupCount) {
160 deviceState.cleanupCount.store(newCleanupCount);
161 for (
auto& info : deviceState.inputChannelInfos) {
162 fair::mq::Parts parts;
163 while (info.channel->Receive(parts, 0)) {
164 LOGP(
debug,
"Dropping {} parts", parts.Size());
165 if (parts.Size() == 0) {
173 std::function<
void(
const fair::mq::State)> stateWatcher = [
this, ®istry = mServiceRegistry](
const fair::mq::State
state) ->
void {
178 control.notifyDeviceState(fair::mq::GetStateName(
state));
181 if (deviceState.nextFairMQState.empty() ==
false) {
182 auto state = deviceState.nextFairMQState.back();
184 deviceState.nextFairMQState.pop_back();
189 this->SubscribeToStateChange(
"99-dpl", stateWatcher);
201 mAwakeHandle->data = &
state;
203 LOG(
error) <<
"Unable to initialise subscription";
207 SubscribeToNewTransition(
"dpl", [wakeHandle = mAwakeHandle](fair::mq::Transition t) {
208 int res = uv_async_send(wakeHandle);
210 LOG(
error) <<
"Unable to notify subscription";
212 LOG(
debug) <<
"State transition requested";
226 O2_SIGNPOST_START(device, sid,
"run_callback",
"Starting run callback on stream %d", task->id.index);
229 O2_SIGNPOST_END(device, sid,
"run_callback",
"Done processing data for stream %d", task->id.index);
242 using o2::monitoring::Metric;
243 using o2::monitoring::Monitoring;
244 using o2::monitoring::tags::Key;
245 using o2::monitoring::tags::Value;
249 stats.totalConsumedBytes += accumulatedConsumed.
sharedMemory;
252 stats.totalConsumedTimeslices += std::min<int64_t>(accumulatedConsumed.
timeslices, 1);
256 dpStats.processCommandQueue();
266 dpStats.processCommandQueue();
269 for (
auto& consumer :
state.offerConsumers) {
270 quotaEvaluator.consume(task->id.index, consumer, reportConsumedOffer);
272 state.offerConsumers.clear();
273 quotaEvaluator.handleExpired(reportExpiredOffer);
274 quotaEvaluator.dispose(task->id.index);
275 task->running =
false;
303 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"Data pending on socket for channel %{public}s", context->name);
307 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"Socket connected for channel %{public}s", context->name);
309 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"Socket connected for read in context %{public}s", context->name);
310 uv_poll_start(poller, UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED, &
on_socket_polled);
313 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"Socket connected for write for channel %{public}s", context->name);
321 case UV_DISCONNECT: {
322 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"Socket disconnected in context %{public}s", context->name);
324 case UV_PRIORITIZED: {
325 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"Socket prioritized for context %{public}s", context->name);
337 LOGP(fatal,
"Error while polling {}: {}", context->name, status);
342 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"Data pending on socket for channel %{public}s", context->name);
344 assert(context->channelInfo);
345 context->channelInfo->readPolled =
true;
348 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"OOB socket connected for channel %{public}s", context->name);
350 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"OOB socket connected for read in context %{public}s", context->name);
353 O2_SIGNPOST_START(sockets, sid,
"socket_state",
"OOB socket connected for write for channel %{public}s", context->name);
357 case UV_DISCONNECT: {
358 O2_SIGNPOST_END(sockets, sid,
"socket_state",
"OOB socket disconnected in context %{public}s", context->name);
361 case UV_PRIORITIZED: {
362 O2_SIGNPOST_EVENT_EMIT(sockets, sid,
"socket_state",
"OOB socket prioritized for context %{public}s", context->name);
383 context.statelessProcess = spec.algorithm.onProcess;
385 context.error = spec.algorithm.onError;
386 context.
initError = spec.algorithm.onInitError;
389 if (configStore ==
nullptr) {
390 std::vector<std::unique_ptr<ParamRetriever>> retrievers;
391 retrievers.emplace_back(std::make_unique<FairOptionsRetriever>(GetConfig()));
392 configStore = std::make_unique<ConfigParamStore>(spec.options, std::move(retrievers));
393 configStore->preload();
394 configStore->activate();
397 using boost::property_tree::ptree;
400 for (
auto&
entry : configStore->store()) {
401 std::stringstream ss;
403 if (
entry.second.empty() ==
false) {
404 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.");
553static auto toBeForwardedHeader = [](
void* header) ->
bool {
558 if (header ==
nullptr) {
561 auto sih = o2::header::get<SourceInfoHeader*>(header);
566 auto dih = o2::header::get<DomainInfoHeader*>(header);
571 auto dh = o2::header::get<DataHeader*>(header);
575 auto dph = o2::header::get<DataProcessingHeader*>(header);
582static auto toBeforwardedMessageSet = [](std::vector<ChannelIndex>& cachedForwardingChoices,
584 std::unique_ptr<fair::mq::Message>& header,
585 std::unique_ptr<fair::mq::Message>& payload,
588 if (header.get() ==
nullptr) {
595 if (payload.get() ==
nullptr && consume ==
true) {
599 header.reset(
nullptr);
603 auto fdph = o2::header::get<DataProcessingHeader*>(header->GetData());
604 if (fdph ==
nullptr) {
605 LOG(error) <<
"Data is missing DataProcessingHeader";
608 auto fdh = o2::header::get<DataHeader*>(header->GetData());
609 if (fdh ==
nullptr) {
610 LOG(error) <<
"Data is missing DataHeader";
617 if (fdh->splitPayloadIndex == 0 || fdh->splitPayloadParts <= 1 || total > 1) {
618 proxy.getMatchingForwardChannelIndexes(cachedForwardingChoices, *fdh, fdph->startTime);
620 return cachedForwardingChoices.empty() ==
false;
634 if (oldestTimeslice.timeslice.value <= decongestion.lastTimeslice) {
635 LOG(
debug) <<
"Not sending already sent oldest possible timeslice " << oldestTimeslice.timeslice.value;
638 for (
int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
639 auto& info = proxy.getForwardChannelInfo(
ChannelIndex{fi});
644 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputsCallback",
"Skipping channel %{public}s because it's not a DPL channel",
650 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputsCallback",
"Forwarding to channel %{public}s oldest possible timeslice %zu, prio 20",
651 info.name.c_str(), oldestTimeslice.timeslice.value);
664 std::vector<fair::mq::Parts> forwardedParts;
665 forwardedParts.resize(proxy.getNumForwards());
666 std::vector<ChannelIndex> cachedForwardingChoices{};
668 O2_SIGNPOST_START(forwarding, sid,
"forwardInputs",
"Starting forwarding for slot %zu with oldestTimeslice %zu %{public}s%{public}s%{public}s",
669 slot.index, oldestTimeslice.timeslice.value, copy ?
"with copy" :
"", copy && consume ?
" and " :
"", consume ?
"with consume" :
"");
671 for (
size_t ii = 0, ie = currentSetOfInputs.size(); ii < ie; ++ii) {
672 auto& messageSet = currentSetOfInputs[ii];
674 if (messageSet.size() == 0) {
677 if (!toBeForwardedHeader(messageSet.header(0)->GetData())) {
680 cachedForwardingChoices.clear();
682 for (
size_t pi = 0; pi < currentSetOfInputs[ii].size(); ++pi) {
683 auto& messageSet = currentSetOfInputs[ii];
684 auto& header = messageSet.header(pi);
685 auto& payload = messageSet.payload(pi);
686 auto total = messageSet.getNumberOfPayloads(pi);
688 if (!toBeforwardedMessageSet(cachedForwardingChoices, proxy, header, payload, total, consume)) {
694 if (cachedForwardingChoices.size() > 1) {
697 auto* dh = o2::header::get<DataHeader*>(header->GetData());
698 auto* dph = o2::header::get<DataProcessingHeader*>(header->GetData());
701 for (
auto& cachedForwardingChoice : cachedForwardingChoices) {
702 auto&& newHeader = header->GetTransport()->CreateMessage();
704 fmt::format(
"{}/{}/{}@timeslice:{} tfCounter:{}", dh->dataOrigin, dh->dataDescription, dh->subSpecification, dph->startTime, dh->tfCounter).c_str(), cachedForwardingChoice.value);
705 newHeader->Copy(*header);
706 forwardedParts[cachedForwardingChoice.value].AddPart(std::move(newHeader));
708 for (
size_t payloadIndex = 0; payloadIndex < messageSet.getNumberOfPayloads(pi); ++payloadIndex) {
709 auto&& newPayload = header->GetTransport()->CreateMessage();
710 newPayload->Copy(*messageSet.payload(pi, payloadIndex));
711 forwardedParts[cachedForwardingChoice.value].AddPart(std::move(newPayload));
716 fmt::format(
"{}/{}/{}@timeslice:{} tfCounter:{}", dh->dataOrigin, dh->dataDescription, dh->subSpecification, dph->startTime, dh->tfCounter).c_str(), cachedForwardingChoices.back().value);
717 forwardedParts[cachedForwardingChoices.back().value].AddPart(std::move(messageSet.header(pi)));
718 for (
size_t payloadIndex = 0; payloadIndex < messageSet.getNumberOfPayloads(pi); ++payloadIndex) {
719 forwardedParts[cachedForwardingChoices.back().value].AddPart(std::move(messageSet.payload(pi, payloadIndex)));
724 O2_SIGNPOST_EVENT_EMIT(forwarding, sid,
"forwardInputs",
"Forwarding %zu messages", forwardedParts.size());
725 for (
int fi = 0; fi < proxy.getNumForwardChannels(); fi++) {
726 if (forwardedParts[fi].
Size() == 0) {
730 auto& parts = forwardedParts[fi];
731 if (info.
policy ==
nullptr) {
742 O2_SIGNPOST_EVENT_EMIT(async_queue, aid,
"forwardInputs",
"Queuing forwarding oldestPossible %zu", oldestTimeslice.timeslice.value);
754 if (infos.empty() ==
false) {
755 std::vector<fair::mq::RegionInfo> toBeNotified;
756 toBeNotified.swap(infos);
757 static bool dummyRead = getenv(
"DPL_DEBUG_MAP_ALL_SHM_REGIONS") && atoi(getenv(
"DPL_DEBUG_MAP_ALL_SHM_REGIONS"));
758 for (
auto const& info : toBeNotified) {
778void DataProcessingDevice::initPollers()
786 if ((context.statefulProcess !=
nullptr) || (context.statelessProcess !=
nullptr)) {
787 for (
auto& [channelName, channel] : GetChannels()) {
789 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
790 auto& channelSpec = spec.inputChannels[ci];
791 channelInfo = &
state.inputChannelInfos[ci];
792 if (channelSpec.name != channelName) {
795 channelInfo->
channel = &this->GetChannel(channelName, 0);
798 if ((
channelName.rfind(
"from_internal-dpl", 0) == 0) &&
799 (
channelName.rfind(
"from_internal-dpl-aod", 0) != 0) &&
800 (
channelName.rfind(
"from_internal-dpl-ccdb-backend", 0) != 0) &&
801 (
channelName.rfind(
"from_internal-dpl-injected", 0)) != 0) {
802 LOGP(detail,
"{} is an internal channel. Skipping as no input will come from there.", channelName);
806 if (
channelName.rfind(
"from_" + spec.name +
"_", 0) == 0) {
807 LOGP(detail,
"{} is to send data. Not polling.", channelName);
812 LOGP(detail,
"{} is not a DPL socket. Not polling.", channelName);
818 size_t zmq_fd_len =
sizeof(zmq_fd);
821 channel[0].GetSocket().GetOption(
"fd", &zmq_fd, &zmq_fd_len);
826 LOGP(detail,
"Polling socket for {}", channelName);
829 pCtx->loop =
state.loop;
831 pCtx->state = &
state;
833 assert(channelInfo !=
nullptr);
834 pCtx->channelInfo = channelInfo;
835 pCtx->socket = &channel[0].GetSocket();
838 uv_poll_init(
state.loop, poller, zmq_fd);
840 LOGP(detail,
"{} is an out of band channel.", channelName);
841 state.activeOutOfBandPollers.push_back(poller);
844 state.activeInputPollers.push_back(poller);
850 if (
state.activeInputPollers.empty() &&
851 state.activeOutOfBandPollers.empty() &&
852 state.activeTimers.empty() &&
853 state.activeSignals.empty()) {
857 if (
state.inputChannelInfos.empty()) {
858 LOGP(detail,
"No input channels. Setting exit transition timeout to 0.");
859 deviceContext.exitTransitionTimeout = 0;
861 for (
auto& [channelName, channel] : GetChannels()) {
862 if (
channelName.rfind(spec.channelPrefix +
"from_internal-dpl", 0) == 0) {
863 LOGP(detail,
"{} is an internal channel. Not polling.", channelName);
866 if (
channelName.rfind(spec.channelPrefix +
"from_" + spec.name +
"_", 0) == 0) {
867 LOGP(detail,
"{} is an out of band channel. Not polling for output.", channelName);
872 size_t zmq_fd_len =
sizeof(zmq_fd);
875 channel[0].GetSocket().GetOption(
"fd", &zmq_fd, &zmq_fd_len);
877 LOGP(
error,
"Cannot get file descriptor for channel {}", channelName);
880 LOG(detail) <<
"Polling socket for " << channel[0].GetName();
884 pCtx->loop =
state.loop;
886 pCtx->state = &
state;
890 uv_poll_init(
state.loop, poller, zmq_fd);
891 state.activeOutputPollers.push_back(poller);
895 LOGP(detail,
"This is a fake device so we exit after the first iteration.");
896 deviceContext.exitTransitionTimeout = 0;
902 uv_timer_init(
state.loop, timer);
903 timer->data = &
state;
904 uv_update_time(
state.loop);
906 state.activeTimers.push_back(timer);
910void DataProcessingDevice::startPollers()
916 for (
auto* poller :
state.activeInputPollers) {
918 O2_SIGNPOST_START(device, sid,
"socket_state",
"Input socket waiting for connection.");
922 for (
auto& poller :
state.activeOutOfBandPollers) {
926 for (
auto* poller :
state.activeOutputPollers) {
928 O2_SIGNPOST_START(device, sid,
"socket_state",
"Output socket waiting for connection.");
935 uv_timer_init(
state.loop, deviceContext.gracePeriodTimer);
938 deviceContext.dataProcessingGracePeriodTimer->data =
new ServiceRegistryRef(mServiceRegistry);
939 uv_timer_init(
state.loop, deviceContext.dataProcessingGracePeriodTimer);
942void DataProcessingDevice::stopPollers()
947 LOGP(detail,
"Stopping {} input pollers",
state.activeInputPollers.size());
948 for (
auto* poller :
state.activeInputPollers) {
951 uv_poll_stop(poller);
954 LOGP(detail,
"Stopping {} out of band pollers",
state.activeOutOfBandPollers.size());
955 for (
auto* poller :
state.activeOutOfBandPollers) {
956 uv_poll_stop(poller);
959 LOGP(detail,
"Stopping {} output pollers",
state.activeOutOfBandPollers.size());
960 for (
auto* poller :
state.activeOutputPollers) {
963 uv_poll_stop(poller);
967 uv_timer_stop(deviceContext.gracePeriodTimer);
969 free(deviceContext.gracePeriodTimer);
970 deviceContext.gracePeriodTimer =
nullptr;
972 uv_timer_stop(deviceContext.dataProcessingGracePeriodTimer);
974 free(deviceContext.dataProcessingGracePeriodTimer);
975 deviceContext.dataProcessingGracePeriodTimer =
nullptr;
990 for (
auto&
di : distinct) {
991 auto& route = spec.inputs[
di];
992 if (route.configurator.has_value() ==
false) {
997 .
name = route.configurator->name,
999 .lifetime = route.matcher.lifetime,
1000 .creator = route.configurator->creatorConfigurator(
state, mServiceRegistry, *mConfigRegistry),
1001 .checker = route.configurator->danglingConfigurator(
state, *mConfigRegistry),
1002 .handler = route.configurator->expirationConfigurator(
state, *mConfigRegistry)};
1003 context.expirationHandlers.emplace_back(std::move(handler));
1006 if (
state.awakeMainThread ==
nullptr) {
1012 deviceContext.expectedRegionCallbacks = std::stoi(fConfig->GetValue<std::string>(
"expected-region-callbacks"));
1013 deviceContext.exitTransitionTimeout = std::stoi(fConfig->GetValue<std::string>(
"exit-transition-timeout"));
1014 deviceContext.dataProcessingTimeout = std::stoi(fConfig->GetValue<std::string>(
"data-processing-timeout"));
1016 for (
auto& channel : GetChannels()) {
1017 channel.second.at(0).Transport()->SubscribeToRegionEvents([&context = deviceContext,
1018 ®istry = mServiceRegistry,
1019 &pendingRegionInfos = mPendingRegionInfos,
1020 ®ionInfoMutex = mRegionInfoMutex](fair::mq::RegionInfo info) {
1021 std::lock_guard<std::mutex> lock(regionInfoMutex);
1022 LOG(detail) <<
">>> Region info event" << info.event;
1023 LOG(detail) <<
"id: " << info.id;
1024 LOG(detail) <<
"ptr: " << info.ptr;
1025 LOG(detail) <<
"size: " << info.size;
1026 LOG(detail) <<
"flags: " << info.flags;
1029 pendingRegionInfos.push_back(info);
1042 if (deviceContext.sigusr1Handle ==
nullptr) {
1044 deviceContext.sigusr1Handle->data = &mServiceRegistry;
1045 uv_signal_init(
state.loop, deviceContext.sigusr1Handle);
1049 for (
auto& handle :
state.activeSignals) {
1050 handle->data = &
state;
1053 deviceContext.sigusr1Handle->data = &mServiceRegistry;
1056 DataProcessingDevice::initPollers();
1064 LOG(
error) <<
"DataProcessor " <<
state.lastActiveDataProcessor.load()->spec->name <<
" was unexpectedly active";
1076 O2_SIGNPOST_END(device, cid,
"InitTask",
"Exiting InitTask callback waiting for the remaining region callbacks.");
1078 auto hasPendingEvents = [&mutex = mRegionInfoMutex, &pendingRegionInfos = mPendingRegionInfos](
DeviceContext& deviceContext) {
1079 std::lock_guard<std::mutex> lock(mutex);
1080 return (pendingRegionInfos.empty() ==
false) || deviceContext.expectedRegionCallbacks > 0;
1087 while (hasPendingEvents(deviceContext)) {
1089 uv_run(
state.loop, UV_RUN_ONCE);
1093 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1097 O2_SIGNPOST_END(device, cid,
"InitTask",
"Done waiting for registration events.");
1104 bool enableRateLimiting = std::stoi(fConfig->GetValue<std::string>(
"timeframes-rate-limit"));
1113 if (enableRateLimiting ==
false && spec.name.find(
"internal-dpl-injected-dummy-sink") != std::string::npos) {
1116 if (enableRateLimiting) {
1117 for (
auto& spec : spec.outputs) {
1118 if (spec.matcher.binding.value ==
"dpl-summary") {
1125 context.
registry = &mServiceRegistry;
1128 if (context.
error !=
nullptr) {
1142 errorCallback(errorContext);
1156 switch (deviceContext.processingPolicies.
error) {
1167 auto decideEarlyForward = [&context, &deviceContext, &spec,
this]() ->
bool {
1171 bool onlyConditions =
true;
1172 bool overriddenEarlyForward =
false;
1173 for (
auto& forwarded : spec.forwards) {
1174 if (forwarded.matcher.lifetime != Lifetime::Condition) {
1175 onlyConditions =
false;
1177#if !__has_include(<fairmq/shmem/Message.h>)
1180 overriddenEarlyForward =
true;
1187 overriddenEarlyForward =
true;
1191 if (forwarded.matcher.lifetime == Lifetime::Optional) {
1193 overriddenEarlyForward =
true;
1198 if (!overriddenEarlyForward && onlyConditions) {
1200 LOG(detail) <<
"Enabling early forwarding because only conditions to be forwarded";
1202 return canForwardEarly;
1214 state.quitRequested =
false;
1217 for (
auto& info :
state.inputChannelInfos) {
1229 for (
size_t i = 0;
i < mStreams.size(); ++
i) {
1232 context.preStartStreamCallbacks(streamRef);
1234 }
catch (std::exception& e) {
1235 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"PreRun",
"Exception of type std::exception caught in PreRun: %{public}s. Rethrowing.", e.what());
1236 O2_SIGNPOST_END(device, cid,
"PreRun",
"Exiting PreRun due to exception thrown.");
1240 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"PreRun",
"Exception of type o2::framework::RuntimeErrorRef caught in PreRun: %{public}s. Rethrowing.", err.what);
1241 O2_SIGNPOST_END(device, cid,
"PreRun",
"Exiting PreRun due to exception thrown.");
1244 O2_SIGNPOST_END(device, cid,
"PreRun",
"Unknown exception being thrown. Rethrowing.");
1252 using o2::monitoring::Metric;
1253 using o2::monitoring::Monitoring;
1254 using o2::monitoring::tags::Key;
1255 using o2::monitoring::tags::Value;
1258 monitoring.send(
Metric{(uint64_t)1,
"device_state"}.addTag(Key::Subsystem, Value::DPL));
1266 using o2::monitoring::Metric;
1267 using o2::monitoring::Monitoring;
1268 using o2::monitoring::tags::Key;
1269 using o2::monitoring::tags::Value;
1272 monitoring.send(
Metric{(uint64_t)0,
"device_state"}.addTag(Key::Subsystem, Value::DPL));
1291 bool firstLoop =
true;
1293 O2_SIGNPOST_START(device, lid,
"device_state",
"First iteration of the device loop");
1295 bool dplEnableMultithreding = getenv(
"DPL_THREADPOOL_SIZE") !=
nullptr;
1296 if (dplEnableMultithreding) {
1297 setenv(
"UV_THREADPOOL_SIZE",
"1", 1);
1301 if (
state.nextFairMQState.empty() ==
false) {
1302 (
void)this->ChangeState(
state.nextFairMQState.back());
1303 state.nextFairMQState.pop_back();
1308 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1321 state.lastActiveDataProcessor.compare_exchange_strong(lastActive,
nullptr);
1323 auto shouldNotWait = (lastActive !=
nullptr &&
1327 shouldNotWait =
true;
1330 if (lastActive !=
nullptr) {
1333 if (NewStatePending()) {
1335 shouldNotWait =
true;
1341 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"State transition requested and we are now in Idle. We can consider it to be completed.");
1344 if (
state.severityStack.empty() ==
false) {
1345 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
1346 state.severityStack.pop_back();
1352 state.firedTimers.clear();
1354 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
1355 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
1362 O2_SIGNPOST_START(device, lid,
"run_loop",
"Dropping message from slot %" PRIu64
". Forwarding as needed.", (uint64_t)slot.index);
1370 forwardInputs(registry, slot, dropped, oldestOutputInfo,
false,
true);
1375 auto oldestPossibleTimeslice = relayer.getOldestPossibleOutput();
1377 if (shouldNotWait ==
false) {
1381 O2_SIGNPOST_END(device, lid,
"run_loop",
"Run loop completed. %{}s", shouldNotWait ?
"Will immediately schedule a new one" :
"Waiting for next event.");
1382 uv_run(
state.loop, shouldNotWait ? UV_RUN_NOWAIT : UV_RUN_ONCE);
1384 if ((
state.loopReason &
state.tracingFlags) != 0) {
1385 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
1386 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
1387 }
else if (
state.severityStack.empty() ==
false) {
1388 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
1389 state.severityStack.pop_back();
1394 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"Out of band activity detected. Rescanning everything.");
1398 if (!
state.pendingOffers.empty()) {
1399 O2_SIGNPOST_EVENT_EMIT(device, lid,
"run_loop",
"Pending %" PRIu64
" offers. updating the ComputingQuotaEvaluator.", (uint64_t)
state.pendingOffers.size());
1411 std::lock_guard<std::mutex> lock(mRegionInfoMutex);
1415 assert(mStreams.size() == mHandles.size());
1418 for (
size_t ti = 0; ti < mStreams.size(); ti++) {
1419 auto& taskInfo = mStreams[ti];
1420 if (taskInfo.running) {
1424 streamRef.index = ti;
1426 using o2::monitoring::Metric;
1427 using o2::monitoring::Monitoring;
1428 using o2::monitoring::tags::Key;
1429 using o2::monitoring::tags::Value;
1432 if (streamRef.index != -1) {
1435 uv_work_t& handle = mHandles[streamRef.index];
1437 handle.data = &mStreams[streamRef.index];
1445 dpStats.processCommandQueue();
1455 struct SchedulingStats {
1456 std::atomic<size_t> lastScheduled = 0;
1457 std::atomic<size_t> numberOfUnscheduledSinceLastScheduled = 0;
1458 std::atomic<size_t> numberOfUnscheduled = 0;
1459 std::atomic<size_t> numberOfScheduled = 0;
1461 static SchedulingStats schedulingStats;
1466 stream.registry = &mServiceRegistry;
1467 schedulingStats.lastScheduled = uv_now(
state.loop);
1468 schedulingStats.numberOfScheduled++;
1469 schedulingStats.numberOfUnscheduledSinceLastScheduled = 0;
1470 O2_SIGNPOST_EVENT_EMIT(scheduling, sid,
"Run",
"Enough resources to schedule computation on stream %d", streamRef.index);
1471 if (dplEnableMultithreding) [[unlikely]] {
1479 if (schedulingStats.numberOfUnscheduledSinceLastScheduled > 100 ||
1480 (uv_now(
state.loop) - schedulingStats.lastScheduled) > 30000) {
1482 "Not enough resources to schedule computation. %zu skipped so far. Last scheduled at %zu.",
1483 schedulingStats.numberOfUnscheduledSinceLastScheduled.load(),
1484 schedulingStats.lastScheduled.load());
1487 "Not enough resources to schedule computation. %zu skipped so far. Last scheduled at %zu.",
1488 schedulingStats.numberOfUnscheduledSinceLastScheduled.load(),
1489 schedulingStats.lastScheduled.load());
1491 schedulingStats.numberOfUnscheduled++;
1492 schedulingStats.numberOfUnscheduledSinceLastScheduled++;
1499 O2_SIGNPOST_END(device, lid,
"run_loop",
"Run loop completed. Transition handling state %d.", (
int)
state.transitionHandling);
1502 for (
size_t ci = 0; ci < spec.inputChannels.size(); ++ci) {
1503 auto& info =
state.inputChannelInfos[ci];
1504 info.parts.fParts.clear();
1515 O2_SIGNPOST_START(device, dpid,
"do_prepare",
"Starting DataProcessorContext::doPrepare.");
1533 context.allDone = std::any_of(
state.inputChannelInfos.begin(),
state.inputChannelInfos.end(), [cid](
const auto& info) {
1535 O2_SIGNPOST_EVENT_EMIT(device, cid,
"do_prepare",
"Input channel %{public}s%{public}s has %zu parts left and is in state %d.",
1536 info.channel->GetName().c_str(), (info.id.value == ChannelIndex::INVALID ?
" (non DPL)" :
""), info.parts.fParts.size(), (int)info.state);
1538 O2_SIGNPOST_EVENT_EMIT(device, cid,
"do_prepare",
"External channel %d is in state %d.", info.id.value, (int)info.state);
1543 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"do_prepare",
"Processing %zu input channels.", spec.inputChannels.size());
1546 static std::vector<int> pollOrder;
1547 pollOrder.resize(
state.inputChannelInfos.size());
1548 std::iota(pollOrder.begin(), pollOrder.end(), 0);
1549 std::sort(pollOrder.begin(), pollOrder.end(), [&infos =
state.inputChannelInfos](
int a,
int b) {
1550 return infos[a].oldestForChannel.value < infos[b].oldestForChannel.value;
1554 if (pollOrder.empty()) {
1555 O2_SIGNPOST_END(device, dpid,
"do_prepare",
"Nothing to poll. Waiting for next iteration.");
1558 auto currentOldest =
state.inputChannelInfos[pollOrder.front()].oldestForChannel;
1559 auto currentNewest =
state.inputChannelInfos[pollOrder.back()].oldestForChannel;
1560 auto delta = currentNewest.value - currentOldest.value;
1561 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"do_prepare",
"Oldest possible timeframe range %" PRIu64
" => %" PRIu64
" delta %" PRIu64,
1562 (int64_t)currentOldest.value, (int64_t)currentNewest.value, (int64_t)delta);
1563 auto& infos =
state.inputChannelInfos;
1565 if (context.balancingInputs) {
1567 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));
1568 auto newEnd = std::remove_if(pollOrder.begin(), pollOrder.end(), [&infos, limitNew = currentOldest.value + ahead](
int a) ->
bool {
1569 return infos[a].oldestForChannel.value > limitNew;
1571 for (
auto it = pollOrder.begin(); it < pollOrder.end(); it++) {
1572 const auto& channelInfo =
state.inputChannelInfos[*it];
1578 bool shouldBeRunning = it < newEnd;
1579 if (running != shouldBeRunning) {
1580 uv_poll_start(poller, shouldBeRunning ? UV_READABLE | UV_DISCONNECT | UV_PRIORITIZED : 0, &
on_socket_polled);
1586 pollOrder.erase(newEnd, pollOrder.end());
1588 O2_SIGNPOST_END(device, dpid,
"do_prepare",
"%zu channels pass the channel inbalance balance check.", pollOrder.size());
1590 for (
auto sci : pollOrder) {
1591 auto& info =
state.inputChannelInfos[sci];
1592 auto& channelSpec = spec.inputChannels[sci];
1594 O2_SIGNPOST_START(device, cid,
"channels",
"Processing channel %s", channelSpec.name.c_str());
1597 context.allDone =
false;
1602 if (info.parts.Size()) {
1605 O2_SIGNPOST_END(device, cid,
"channels",
"Flushing channel %s which is in state %d and has %zu parts still pending.",
1606 channelSpec.name.c_str(), (
int)info.state, info.parts.Size());
1609 if (info.
channel ==
nullptr) {
1610 O2_SIGNPOST_END(device, cid,
"channels",
"Channel %s which is in state %d is nullptr and has %zu parts still pending.",
1611 channelSpec.name.c_str(), (
int)info.state, info.parts.Size());
1616 O2_SIGNPOST_END(device, cid,
"channels",
"Channel %s which is in state %d is not a DPL channel and has %zu parts still pending.",
1617 channelSpec.name.c_str(), (
int)info.state, info.parts.Size());
1620 auto& socket = info.
channel->GetSocket();
1625 if (info.hasPendingEvents == 0) {
1626 socket.Events(&info.hasPendingEvents);
1628 if ((info.hasPendingEvents & 1) == 0 && (info.parts.Size() == 0)) {
1629 O2_SIGNPOST_END(device, cid,
"channels",
"No pending events and no remaining parts to process for channel %{public}s", channelSpec.name.c_str());
1635 info.readPolled =
false;
1644 bool newMessages =
false;
1646 O2_SIGNPOST_EVENT_EMIT(device, cid,
"channels",
"Receiving loop called for channel %{public}s (%d) with oldest possible timeslice %zu",
1647 channelSpec.name.c_str(), info.id.value, info.oldestForChannel.value);
1648 if (info.parts.Size() < 64) {
1649 fair::mq::Parts parts;
1650 info.
channel->Receive(parts, 0);
1652 O2_SIGNPOST_EVENT_EMIT(device, cid,
"channels",
"Received %zu parts from channel %{public}s (%d).", parts.Size(), channelSpec.name.c_str(), info.id.value);
1654 for (
auto&& part : parts) {
1655 info.parts.fParts.emplace_back(std::move(part));
1657 newMessages |=
true;
1660 if (info.parts.Size() >= 0) {
1672 socket.Events(&info.hasPendingEvents);
1673 if (info.hasPendingEvents) {
1674 info.readPolled =
false;
1677 state.lastActiveDataProcessor.store(&context);
1680 O2_SIGNPOST_END(device, cid,
"channels",
"Done processing channel %{public}s (%d).",
1681 channelSpec.name.c_str(), info.id.value);
1696 context.completed.clear();
1697 context.completed.reserve(16);
1699 state.lastActiveDataProcessor.store(&context);
1703 context.preDanglingCallbacks(danglingContext);
1704 if (
state.lastActiveDataProcessor.load() ==
nullptr) {
1707 auto activity =
ref.get<
DataRelayer>().processDanglingInputs(context.expirationHandlers, *context.registry,
true);
1708 if (activity.expiredSlots > 0) {
1709 state.lastActiveDataProcessor = &context;
1712 context.completed.clear();
1714 state.lastActiveDataProcessor = &context;
1717 context.postDanglingCallbacks(danglingContext);
1725 state.lastActiveDataProcessor = &context;
1748 timingInfo.timeslice = relayer.getOldestPossibleOutput().timeslice.value;
1749 timingInfo.tfCounter = -1;
1750 timingInfo.firstTForbit = -1;
1752 timingInfo.creation = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count();
1753 O2_SIGNPOST_EVENT_EMIT(calibration, dpid,
"calibration",
"TimingInfo.keepAtEndOfStream %d", timingInfo.keepAtEndOfStream);
1757 context.preEOSCallbacks(eosContext);
1761 streamContext.postEOSCallbacks(eosContext);
1762 context.postEOSCallbacks(eosContext);
1764 for (
auto& channel : spec.outputChannels) {
1765 O2_SIGNPOST_EVENT_EMIT(device, dpid,
"state",
"Sending end of stream to %{public}s.", channel.name.c_str());
1772 if (shouldProcess) {
1773 state.lastActiveDataProcessor = &context;
1777 for (
auto& poller :
state.activeOutputPollers) {
1778 uv_poll_stop(poller);
1786 for (
auto& poller :
state.activeOutputPollers) {
1787 uv_poll_stop(poller);
1803 if (deviceContext.sigusr1Handle) {
1809 handle->data =
nullptr;
1838 auto getInputTypes = [&info, &context]() -> std::optional<std::vector<InputInfo>> {
1843 auto& parts = info.
parts;
1846 std::vector<InputInfo> results;
1848 results.reserve(parts.Size() / 2);
1849 size_t nTotalPayloads = 0;
1853 if (
type != InputType::Invalid &&
length > 1) {
1854 nTotalPayloads +=
length - 1;
1858 for (
size_t pi = 0; pi < parts.Size(); pi += 2) {
1859 auto* headerData = parts.At(pi)->GetData();
1860 auto sih = o2::header::get<SourceInfoHeader*>(headerData);
1862 O2_SIGNPOST_EVENT_EMIT(device, cid,
"handle_data",
"Got SourceInfoHeader with state %d", (
int)sih->state);
1863 info.
state = sih->state;
1864 insertInputInfo(pi, 2, InputType::SourceInfo, info.
id);
1865 state.lastActiveDataProcessor = &context;
1868 auto dih = o2::header::get<DomainInfoHeader*>(headerData);
1870 O2_SIGNPOST_EVENT_EMIT(device, cid,
"handle_data",
"Got DomainInfoHeader with oldestPossibleTimeslice %d", (
int)dih->oldestPossibleTimeslice);
1871 insertInputInfo(pi, 2, InputType::DomainInfo, info.
id);
1872 state.lastActiveDataProcessor = &context;
1875 auto dh = o2::header::get<DataHeader*>(headerData);
1877 insertInputInfo(pi, 0, InputType::Invalid, info.
id);
1881 if (dh->payloadSize > parts.At(pi + 1)->GetSize()) {
1882 insertInputInfo(pi, 0, InputType::Invalid, info.
id);
1886 auto dph = o2::header::get<DataProcessingHeader*>(headerData);
1891 O2_SIGNPOST_START(parts,
pid,
"parts",
"Processing DataHeader %{public}-4s/%{public}-16s/%d with splitPayloadParts %d and splitPayloadIndex %d",
1892 dh->dataOrigin.str, dh->dataDescription.str, dh->subSpecification, dh->splitPayloadParts, dh->splitPayloadIndex);
1894 insertInputInfo(pi, 2, InputType::Invalid, info.
id);
1898 if (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) {
1901 insertInputInfo(pi, dh->splitPayloadParts + 1, InputType::Data, info.
id);
1902 pi += dh->splitPayloadParts - 1;
1908 size_t finalSplitPayloadIndex = pi + (dh->splitPayloadParts > 0 ? dh->splitPayloadParts : 1) * 2;
1909 if (finalSplitPayloadIndex > parts.Size()) {
1911 insertInputInfo(pi, 0, InputType::Invalid, info.
id);
1914 insertInputInfo(pi, 2, InputType::Data, info.
id);
1915 for (; pi + 2 < finalSplitPayloadIndex; pi += 2) {
1916 insertInputInfo(pi + 2, 2, InputType::Data, info.
id);
1920 if (results.size() + nTotalPayloads != parts.Size()) {
1921 O2_SIGNPOST_EVENT_EMIT_ERROR(device, cid,
"handle_data",
"inconsistent number of inputs extracted. %zu vs parts (%zu)", results.size() + nTotalPayloads, parts.Size());
1922 return std::nullopt;
1927 auto reportError = [
ref](
const char*
message) {
1932 auto handleValidMessages = [&info,
ref, &reportError](std::vector<InputInfo>
const& inputInfos) {
1936 auto& parts = info.
parts;
1939 bool hasBackpressure =
false;
1940 size_t minBackpressureTimeslice = -1;
1942 size_t oldestPossibleTimeslice = -1;
1943 static std::vector<int> ordering;
1945 ordering.resize(inputInfos.size());
1946 std::iota(ordering.begin(), ordering.end(), 0);
1948 std::stable_sort(ordering.begin(), ordering.end(), [&inputInfos](
int const&
a,
int const&
b) {
1949 auto const& ai = inputInfos[a];
1950 auto const& bi = inputInfos[b];
1951 if (ai.type != bi.type) {
1952 return ai.type < bi.type;
1954 return ai.position < bi.position;
1956 for (
size_t ii = 0; ii < inputInfos.size(); ++ii) {
1957 auto const& input = inputInfos[ordering[ii]];
1958 switch (input.type) {
1959 case InputType::Data: {
1961 auto headerIndex = input.position;
1963 auto nPayloadsPerHeader = 0;
1964 if (input.size > 2) {
1966 nMessages = input.size;
1967 nPayloadsPerHeader = nMessages - 1;
1970 auto dh = o2::header::get<DataHeader*>(parts.At(headerIndex)->GetData());
1971 nMessages = dh->splitPayloadParts > 0 ? dh->splitPayloadParts * 2 : 2;
1972 nPayloadsPerHeader = 1;
1973 ii += (nMessages / 2) - 1;
1977 O2_SIGNPOST_EVENT_EMIT(async_queue, cid,
"onDrop",
"Dropping message from slot %zu. Forwarding as needed. Timeslice %zu",
1978 slot.
index, oldestOutputInfo.timeslice.value);
1985 forwardInputs(
ref, slot, dropped, oldestOutputInfo,
false,
true);
1987 auto relayed = relayer.relay(parts.At(headerIndex)->GetData(),
1988 &parts.At(headerIndex),
1993 switch (relayed.type) {
1996 LOGP(alarm,
"Backpressure on channel {}. Waiting.", info.
channel->GetName());
1997 auto& monitoring =
ref.get<o2::monitoring::Monitoring>();
1998 monitoring.send(o2::monitoring::Metric{1, fmt::format(
"backpressure_{}", info.
channel->GetName())});
2002 policy.backpressure(info);
2003 hasBackpressure =
true;
2004 minBackpressureTimeslice = std::min<size_t>(minBackpressureTimeslice, relayed.timeslice.value);
2010 LOGP(info,
"Back to normal on channel {}.", info.
channel->GetName());
2011 auto& monitoring =
ref.get<o2::monitoring::Monitoring>();
2012 monitoring.send(o2::monitoring::Metric{0, fmt::format(
"backpressure_{}", info.
channel->GetName())});
2019 case InputType::SourceInfo: {
2020 LOGP(detail,
"Received SourceInfo");
2022 state.lastActiveDataProcessor = &context;
2023 auto headerIndex = input.position;
2024 auto payloadIndex = input.position + 1;
2025 assert(payloadIndex < parts.Size());
2028 parts.At(headerIndex).reset(
nullptr);
2029 parts.At(payloadIndex).reset(
nullptr);
2036 case InputType::DomainInfo: {
2040 state.lastActiveDataProcessor = &context;
2041 auto headerIndex = input.position;
2042 auto payloadIndex = input.position + 1;
2043 assert(payloadIndex < parts.Size());
2047 auto dih = o2::header::get<DomainInfoHeader*>(parts.At(headerIndex)->GetData());
2048 if (hasBackpressure && dih->oldestPossibleTimeslice >= minBackpressureTimeslice) {
2051 oldestPossibleTimeslice = std::min(oldestPossibleTimeslice, dih->oldestPossibleTimeslice);
2052 LOGP(
debug,
"Got DomainInfoHeader, new oldestPossibleTimeslice {} on channel {}", oldestPossibleTimeslice, info.
id.
value);
2053 parts.At(headerIndex).reset(
nullptr);
2054 parts.At(payloadIndex).reset(
nullptr);
2056 case InputType::Invalid: {
2057 reportError(
"Invalid part found.");
2063 if (oldestPossibleTimeslice != (
size_t)-1) {
2066 context.domainInfoUpdatedCallback(*context.registry, oldestPossibleTimeslice, info.
id);
2068 state.lastActiveDataProcessor = &context;
2070 auto it = std::remove_if(parts.fParts.begin(), parts.fParts.end(), [](
auto&
msg) ->
bool { return msg.get() == nullptr; });
2071 parts.fParts.erase(it, parts.end());
2072 if (parts.fParts.size()) {
2073 LOG(
debug) << parts.fParts.size() <<
" messages backpressured";
2085 auto inputTypes = getInputTypes();
2086 if (
bool(inputTypes) ==
false) {
2087 reportError(
"Parts should come in couples. Dropping it.");
2090 handleValidMessages(*inputTypes);
2096struct InputLatency {
2101auto calculateInputRecordLatency(
InputRecord const& record, uint64_t currentTime) -> InputLatency
2105 for (
auto& item : record) {
2106 auto* header = o2::header::get<DataProcessingHeader*>(item.header);
2107 if (header ==
nullptr) {
2110 int64_t partLatency = (0x7fffffffffffffff & currentTime) - (0x7fffffffffffffff & header->creation);
2111 if (partLatency < 0) {
2114 result.minLatency = std::min(
result.minLatency, (uint64_t)partLatency);
2115 result.maxLatency = std::max(
result.maxLatency, (uint64_t)partLatency);
2120auto calculateTotalInputRecordSize(
InputRecord const& record) ->
int
2122 size_t totalInputSize = 0;
2123 for (
auto& item : record) {
2124 auto* header = o2::header::get<DataHeader*>(item.header);
2125 if (header ==
nullptr) {
2128 totalInputSize += header->payloadSize;
2130 return totalInputSize;
2133template <
typename T>
2134void update_maximum(std::atomic<T>& maximum_value, T
const&
value)
noexcept
2136 T prev_value = maximum_value;
2137 while (prev_value <
value &&
2138 !maximum_value.compare_exchange_weak(prev_value,
value)) {
2146 LOGP(
debug,
"DataProcessingDevice::tryDispatchComputation");
2151 std::vector<MessageSet> currentSetOfInputs;
2154 auto getInputSpan = [
ref, ¤tSetOfInputs](
TimesliceSlot slot,
bool consume =
true) {
2159 currentSetOfInputs = relayer.consumeExistingInputsForTimeslice(slot);
2161 auto getter = [¤tSetOfInputs](
size_t i,
size_t partindex) ->
DataRef {
2162 if (currentSetOfInputs[
i].getNumberOfPairs() > partindex) {
2163 const char* headerptr =
nullptr;
2164 const char* payloadptr =
nullptr;
2165 size_t payloadSize = 0;
2171 auto const& headerMsg = currentSetOfInputs[
i].associatedHeader(partindex);
2172 auto const& payloadMsg = currentSetOfInputs[
i].associatedPayload(partindex);
2173 headerptr =
static_cast<char const*
>(headerMsg->GetData());
2174 payloadptr = payloadMsg ?
static_cast<char const*
>(payloadMsg->GetData()) :
nullptr;
2175 payloadSize = payloadMsg ? payloadMsg->GetSize() : 0;
2176 return DataRef{
nullptr, headerptr, payloadptr, payloadSize};
2180 auto nofPartsGetter = [¤tSetOfInputs](
size_t i) ->
size_t {
2181 return currentSetOfInputs[
i].getNumberOfPairs();
2183#if __has_include(<fairmq/shmem/Message.h>)
2184 auto refCountGetter = [¤tSetOfInputs](
size_t idx) ->
int {
2185 auto& header =
static_cast<const fair::mq::shmem::Message&
>(*currentSetOfInputs[idx].header(0));
2186 return header.GetRefCount();
2189 std::function<
int(
size_t)> refCountGetter =
nullptr;
2191 return InputSpan{getter, nofPartsGetter, refCountGetter, currentSetOfInputs.
size()};
2206 auto timeslice = relayer.getTimesliceForSlot(
i);
2208 timingInfo.timeslice = timeslice.value;
2218 auto timeslice = relayer.getTimesliceForSlot(
i);
2220 timingInfo.globalRunNumberChanged = !
TimingInfo::timesliceIsTimer(timeslice.value) && dataProcessorContext.lastRunNumberProcessed != timingInfo.runNumber;
2222 timingInfo.globalRunNumberChanged &= (dataProcessorContext.lastRunNumberProcessed == -1 || timingInfo.runNumber != 0);
2226 timingInfo.streamRunNumberChanged = timingInfo.globalRunNumberChanged;
2234 assert(record.size() == currentSetOfInputs.size());
2235 for (
size_t ii = 0, ie = record.size(); ii < ie; ++ii) {
2239 DataRef input = record.getByPos(ii);
2243 if (input.
header ==
nullptr) {
2247 currentSetOfInputs[ii].clear();
2258 for (
size_t pi = 0, pe = record.size(); pi < pe; ++pi) {
2259 DataRef input = record.getByPos(pi);
2260 if (input.
header ==
nullptr) {
2263 auto sih = o2::header::get<SourceInfoHeader*>(input.
header);
2268 auto dh = o2::header::get<DataHeader*>(input.
header);
2278 if (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) {
2281 pi += dh->splitPayloadParts - 1;
2283 size_t pi = pi + (dh->splitPayloadParts > 0 ? dh->splitPayloadParts : 1) * 2;
2289 if (completed.empty() ==
true) {
2290 LOGP(
debug,
"No computations available for dispatching.");
2297 std::atomic_thread_fence(std::memory_order_release);
2298 char relayerSlotState[1024];
2300 char*
buffer = relayerSlotState + written;
2301 for (
size_t ai = 0; ai != record.size(); ai++) {
2302 buffer[ai] = record.isValid(ai) ?
'3' :
'0';
2304 buffer[record.size()] = 0;
2306 .size = (
int)(record.size() +
buffer - relayerSlotState),
2307 .
data = relayerSlotState});
2308 uint64_t tEnd = uv_hrtime();
2310 int64_t wallTimeMs = (tEnd - tStart) / 1000000;
2318 auto latency = calculateInputRecordLatency(record, tStartMilli);
2321 static int count = 0;
2328 std::atomic_thread_fence(std::memory_order_release);
2329 char relayerSlotState[1024];
2331 char*
buffer = strchr(relayerSlotState,
' ') + 1;
2332 for (
size_t ai = 0; ai != record.size(); ai++) {
2333 buffer[ai] = record.isValid(ai) ?
'2' :
'0';
2335 buffer[record.size()] = 0;
2353 switch (spec.completionPolicy.order) {
2355 std::sort(completed.begin(), completed.end(), [](
auto const&
a,
auto const&
b) { return a.timeslice.value < b.timeslice.value; });
2358 std::sort(completed.begin(), completed.end(), [](
auto const&
a,
auto const&
b) { return a.slot.index < b.slot.index; });
2365 for (
auto action : completed) {
2367 O2_SIGNPOST_START(device, aid,
"device",
"Processing action on slot %lu for action %{public}s", action.
slot.
index, fmt::format(
"{}", action.
op).c_str());
2391 dpContext.preProcessingCallbacks(processContext);
2394 context.postDispatchingCallbacks(processContext);
2395 if (spec.forwards.empty() ==
false) {
2397 forwardInputs(
ref, action.
slot, currentSetOfInputs, timesliceIndex.getOldestPossibleOutput(),
false);
2398 O2_SIGNPOST_END(device, aid,
"device",
"Forwarding inputs consume: %d.",
false);
2406 bool hasForwards = spec.forwards.empty() ==
false;
2409 if (context.canForwardEarly && hasForwards && consumeSomething) {
2410 O2_SIGNPOST_EVENT_EMIT(device, aid,
"device",
"Early forwainding: %{public}s.", fmt::format(
"{}", action.
op).c_str());
2414 markInputsAsDone(action.
slot);
2416 uint64_t tStart = uv_hrtime();
2418 preUpdateStats(action, record, tStart);
2420 static bool noCatch = getenv(
"O2_NO_CATCHALL_EXCEPTIONS") && strcmp(getenv(
"O2_NO_CATCHALL_EXCEPTIONS"),
"0");
2428 switch (action.
op) {
2439 if (
state.quitRequested ==
false) {
2443 streamContext.preProcessingCallbacks(processContext);
2449 if (context.statefulProcess && shouldProcess(action)) {
2453 (context.statefulProcess)(processContext);
2455 }
else if (context.statelessProcess && shouldProcess(action)) {
2457 (context.statelessProcess)(processContext);
2459 }
else if (context.statelessProcess || context.statefulProcess) {
2462 O2_SIGNPOST_EVENT_EMIT(device, pcid,
"device",
"No processing callback provided. Switching to %{public}s.",
"Idle");
2465 if (shouldProcess(action)) {
2467 if (timingInfo.globalRunNumberChanged) {
2468 context.lastRunNumberProcessed = timingInfo.runNumber;
2485 streamContext.finaliseOutputsCallbacks(processContext);
2491 streamContext.postProcessingCallbacks(processContext);
2497 state.severityStack.push_back((
int)fair::Logger::GetConsoleSeverity());
2498 fair::Logger::SetConsoleSeverity(fair::Severity::trace);
2504 (context.errorHandling)(e, record);
2509 }
catch (std::exception& ex) {
2514 (context.errorHandling)(e, record);
2516 (context.errorHandling)(e, record);
2519 if (
state.severityStack.empty() ==
false) {
2520 fair::Logger::SetConsoleSeverity((fair::Severity)
state.severityStack.back());
2521 state.severityStack.pop_back();
2524 postUpdateStats(action, record, tStart, tStartMilli);
2528 cleanupRecord(record);
2529 context.postDispatchingCallbacks(processContext);
2532 if ((context.canForwardEarly ==
false) && hasForwards && consumeSomething) {
2537 context.postForwardingCallbacks(processContext);
2539 cleanTimers(action.
slot, record);
2541 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());
2543 O2_SIGNPOST_END(device, sid,
"device",
"Start processing ready actions");
2547 LOGP(detail,
"Broadcasting end of stream");
2548 for (
auto& channel : spec.outputChannels) {
2571 cfg.getRecursive(
name);
2572 std::vector<std::unique_ptr<ParamRetriever>> retrievers;
2573 retrievers.emplace_back(std::make_unique<ConfigurationOptionsRetriever>(&cfg,
name));
2574 auto configStore = std::make_unique<ConfigParamStore>(options, std::move(retrievers));
2575 configStore->preload();
2576 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 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)
static header::DataOrigin asConcreteOrigin(InputSpec const &spec)
TimesliceIndex::OldestOutputInfo oldestTimeslice
static unsigned int pipelineLength()
get max number of timeslices in the queue
static std::unique_ptr< ConfigParamStore > getConfiguration(ServiceRegistryRef registry, const char *name, std::vector< ConfigParamSpec > const &options)
uv_signal_t * sigusr1Handle
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