42#include "Monitoring/Monitoring.h"
44#include <fairmq/Parts.h>
45#include <fairmq/Device.h>
51#include <unordered_map>
77 constexpr auto index = 0;
78 LOG(
debug) <<
"sending " << messages.Size() <<
" messages on " << channel;
80 const int maxTimeout = 10000;
92 }
else if (
timeout < maxTimeout) {
95 LOG(alarm) <<
"Cannot dispatch to channel " << channel <<
" due to DOWNSTREAM BACKPRESSURE. NO DATA IS DROPPED,"
96 <<
" will keep retrying. This is only a problem if downstream congestion does not resolve by itself.";
102 if (
device.NewStatePending()) {
103 LOG(alarm) <<
"Device state change is requested, dropping " << messages.Size() <<
" pending message(s) "
104 <<
"on channel " << channel <<
". "
105 <<
"ATTENTION: DATA IS LOST! Could not dispatch data to downstream consumer(s), check if "
106 <<
"consumers have been terminated too early";
115 LOG(warning) <<
"dispatching on channel " << channel <<
" was delayed by " <<
timeout / 1000.f <<
" s";
122 messages.fParts.clear();
129 auto channel = channelRetriever(spec, tslice);
130 if (channel.empty()) {
139 const auto* dph = o2::header::get<DataProcessingHeader*>(headerStack.data());
141 LOG(
error) <<
"Header Stack does not follow the O2 data model, DataProcessingHeader missing";
144 auto channelName = channelRetriever(spec, dph->startTime);
145 constexpr auto index = 0;
146 if (channelName.empty()) {
150 for (
auto& channelInfo :
device.GetChannels()) {
151 if (channelInfo.first != channelName) {
154 assert(channelInfo.second.size() == 1);
156 auto channelAlloc = o2::pmr::getTransportAllocator(channelInfo.second[
index].Transport());
157 fair::mq::MessagePtr headerMessage =
o2::pmr::getMessage(std::move(headerStack), channelAlloc);
160 out.AddPart(std::move(headerMessage));
161 out.AddPart(std::move(payloadMessage));
165 LOG(
error) <<
"internal mismatch, can not find channel " << channelName <<
" in the list of channel infos of the device";
171 const auto* dph = o2::header::get<DataProcessingHeader*>(headerMessage->GetData());
173 LOG(
error) <<
"Header does not follow the O2 data model, DataProcessingHeader missing";
176 auto tslice = dph->startTime;
178 out.AddPart(std::move(headerMessage));
179 out.AddPart(std::move(payloadMessage));
185 auto channelName = channelRetriever(spec, timeSliceID);
186 constexpr auto index = 0;
187 if (channelName.empty()) {
191 for (
auto& channelInfo :
device.GetChannels()) {
192 if (channelInfo.first != channelName) {
195 assert(channelInfo.second.size() == 1);
197 auto channelAlloc = o2::pmr::getTransportAllocator(channelInfo.second[
index].Transport());
198 fair::mq::MessagePtr headerMessage =
o2::pmr::getMessage(std::move(headerStack), channelAlloc);
201 messageCache.AddPart(std::move(headerMessage));
202 messageCache.AddPart(std::move(payloadMessage));
205 LOG(
error) <<
"internal mismatch, can not find channel " << channelName <<
" in the list of channel infos of the device";
212 for (
int i = 0;
i < parts.Size() / 2; ++
i) {
213 auto dh = o2::header::get<DataHeader*>(parts.At(
i * 2)->GetData());
217 sendOnChannel(*
device, std::move(headerStack), std::move(parts.At(
i * 2 + 1)), spec, channelRetriever);
219 return parts.Size() > 0;
225 size_t finalBlockIndex = 0;
226 if (dh.splitPayloadParts > 0 && dh.splitPayloadParts == dh.splitPayloadIndex) {
230 finalBlockIndex = msgidx + dh.splitPayloadParts + 1;
236 finalBlockIndex = msgidx + (dh.splitPayloadParts > 0 ? dh.splitPayloadParts : 1) * 2;
238 assert(finalBlockIndex >= msgidx + 2);
239 return finalBlockIndex;
245 static std::vector<bool> present;
246 static std::vector<bool> ignored;
247 static std::vector<size_t> dataSizes;
248 static std::vector<bool> showSize;
250 present.resize(
routes.size(),
false);
252 ignored.resize(
routes.size(),
false);
254 dataSizes.resize(
routes.size(), 0);
256 showSize.resize(
routes.size(),
false);
258 static std::vector<size_t> unmatchedDescriptions;
259 unmatchedDescriptions.clear();
265 size_t expectedDataSpecs = 0;
266 for (
size_t pi = 0; pi < present.size(); ++pi) {
267 auto& spec =
routes[pi].matcher;
272 if (
routes[pi].timeslice == 0) {
277 size_t foundDataSpecs = 0;
278 bool skipAsAllFound =
false;
279 for (
int msgidx = 0; msgidx < parts.Size(); msgidx += 2) {
280 bool allFound =
true;
282 const auto dh = o2::header::get<DataHeader*>(parts.At(msgidx)->GetData());
283 auto const sih = o2::header::get<SourceInfoHeader*>(parts.At(msgidx)->GetData());
284 if (sih !=
nullptr) {
288 if (parts.At(msgidx).get() ==
nullptr) {
289 LOG(
error) <<
"unexpected nullptr found. Skipping message pair.";
293 LOG(
error) <<
"data on input " << msgidx <<
" does not follow the O2 data model, DataHeader missing";
299 if (firstDH ==
nullptr) {
301 if (doPrintSizes && firstDH->
tfCounter % doPrintSizes != 0) {
306 if (dph ==
nullptr) {
307 dph = o2::header::get<DataProcessingHeader*>(parts.At(msgidx)->GetData());
308 for (
size_t pi = 0; pi < present.size(); ++pi) {
314 for (
size_t pi = 0; pi < present.size(); ++pi) {
315 if ((present[pi] || ignored[pi]) && !doPrintSizes) {
324 auto& spec =
routes[pi].matcher;
325 OutputSpec query{dh->dataOrigin, dh->dataDescription, dh->subSpecification};
327 if (!present[pi] && !ignored[pi]) {
337 if (addToSize >= 0) {
338 int increment = (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) ? 1 : 2;
339 for (
int msgidx2 = msgidx + 1; msgidx2 < msgidxLast; msgidx2 += increment) {
340 dataSizes[addToSize] += parts.At(msgidx2)->GetSize();
344 msgidx = msgidxLast - 2;
345 if (allFound && !doPrintSizes) {
346 skipAsAllFound =
true;
352 for (
size_t pi = 0; pi < present.size(); ++pi) {
353 if (present[pi] && !ignored[pi]) {
356 if (!present[pi] && !ignored[pi]) {
358 unmatchedDescriptions.push_back(pi);
361 int timeframeCompleteness = emptyTf ? 0 : (unmatchedDescriptions.size() ? -1 : 1);
362 (
void)timeframeCompleteness;
364 if (skipAsAllFound && !doPrintSizes) {
368 if (firstDH && doPrintSizes) {
369 std::string
sizes =
"";
370 size_t totalSize = 0;
371 for (
size_t pi = 0; pi < present.size(); ++pi) {
373 totalSize += dataSizes[pi];
374 auto& spec =
routes[pi].matcher;
378 LOGP(important,
"RAW {} size report:{}- Total:{}", firstDH->
tfCounter,
sizes, fmt::group_digits(totalSize));
381 if (!doInjectMissingData) {
385 if (unmatchedDescriptions.size() > 0) {
388 LOG(
error) <<
"Received an EndOfStream message together with data. This should not happen.";
390 LOG(detail) <<
"This is an End Of Stream message. Not injecting anything.";
393 if (firstDH ==
nullptr) {
394 LOG(
error) <<
"Input proxy received incomplete data without any data header. This should not happen! Cannot inject missing data as requsted.";
397 if (dph ==
nullptr) {
398 LOG(
error) <<
"Input proxy received incomplete data without any data processing header. This should happen! Cannot inject missing data as requsted.";
401 std::string missing =
"";
402 bool showAlarm =
false;
405 runNumber = strtoul(
device.fConfig->GetProperty<std::string>(
"runNumber",
"").c_str(),
nullptr, 10);
408 for (
auto mi : unmatchedDescriptions) {
409 auto& spec =
routes[mi].matcher;
415 if (subSpec == std::nullopt) {
416 *subSpec = 0xDEADBEEF;
421 dh.subSpecification = *subSpec;
423 dh.runNumber = runNumber;
424 dh.splitPayloadParts = 0;
425 dh.splitPayloadIndex = 0;
428 auto& channelName =
routes[mi].channel;
429 auto& channelInfo =
device.GetChannel(channelName);
430 auto channelAlloc = o2::pmr::getTransportAllocator(channelInfo.Transport());
432 parts.AddPart(std::move(headerMessage));
434 parts.AddPart(
device.NewMessageFor(channelName, 0, 0));
439 static int maxWarn = 10;
440 static int contDeadBeef = 0;
441 if (showAlarm && ++contDeadBeef <= maxWarn) {
442 LOGP(alarm,
"Found {}/{} data specs, missing data specs: {}, injecting 0xDEADBEEF{}", foundDataSpecs, expectedDataSpecs, missing, contDeadBeef == maxWarn ?
" - disabling alarm now to stop flooding the log" :
"");
451 class DroppedDataSpecs
454 DroppedDataSpecs() =
default;
460 [[nodiscard]]
bool find(std::string
const& desc)
const
462 return descriptions.find(desc) != std::string::npos;
465 void add(std::string
const& desc)
467 descriptions +=
"\n " + desc;
472 if (not descriptions.empty()) {
473 LOG(warning) <<
"Some input data could not be matched by filter rules to output specs\n"
474 <<
"Active rules: " << descriptions <<
"\n"
475 <<
"DROPPING OF THESE MESSAGES HAS BEEN ENABLED BY CONFIGURATION";
480 std::string descriptions;
483 return [filterSpecs = std::move(filterSpecs), throwOnUnmatchedInputs, droppedDataSpecs = std::make_shared<DroppedDataSpecs>()](
TimingInfo& timingInfo,
ServiceRegistryRef const& services, fair::mq::Parts& parts,
ChannelRetriever channelRetriever,
size_t newTimesliceId,
bool& stop) {
485 std::unordered_map<std::string, fair::mq::Parts> outputs;
486 std::vector<std::string> unmatchedDescriptions;
489 static bool override_creation_env = getenv(
"DPL_RAWPROXY_OVERRIDE_ORBITRESET");
490 bool override_creation =
false;
492 if (override_creation_env) {
493 static uint64_t creationValBase = std::stoul(getenv(
"DPL_RAWPROXY_OVERRIDE_ORBITRESET"));
494 creationVal = creationValBase;
495 override_creation =
true;
497 auto orbitResetTimeUrl =
device->fConfig->GetProperty<std::string>(
"orbit-reset-time",
"ccdb://CTP/Calib/OrbitResetTime");
499 creationVal = std::strtoll(orbitResetTimeUrl.c_str(), &err, 10);
500 if (err && *err == 0 && creationVal) {
501 override_creation =
true;
505 int fmqRunNumber = -1;
507 fmqRunNumber = atoi(
device->fConfig->GetProperty<std::string>(
"runNumber",
"").c_str());
511 for (
int msgidx = 0; msgidx < parts.Size(); msgidx += 2) {
512 if (parts.At(msgidx).get() ==
nullptr) {
513 LOG(
error) <<
"unexpected nullptr found. Skipping message pair.";
516 auto*
header = parts.At(msgidx)->GetData();
517 const auto dh = o2::header::get<DataHeader*>(
header);
519 LOG(
error) <<
"data on input " << msgidx <<
" does not follow the O2 data model, DataHeader missing";
525 auto dph = o2::header::get<DataProcessingHeader*>(
header);
527 LOG(
error) <<
"data on input " << msgidx <<
" does not follow the O2 data model, DataProcessingHeader missing";
531 if (override_creation) {
532 const_cast<DataProcessingHeader*
>(dph)->creation = creationVal + (dh->firstTForbit * o2::constants::lhc::LHCOrbitNS * 0.000001f);
535 timingInfo.creation = dph->creation;
536 timingInfo.firstTForbit = dh->firstTForbit;
537 timingInfo.runNumber = dh->runNumber;
538 timingInfo.tfCounter = dh->tfCounter;
539 LOG(
debug) << msgidx <<
": " <<
DataSpecUtils::describe(
OutputSpec{dh->dataOrigin, dh->dataDescription, dh->subSpecification}) <<
" part " << dh->splitPayloadIndex <<
" of " << dh->splitPayloadParts <<
" payload " << parts.At(msgidx + 1)->GetSize();
541 LOG(
error) <<
"INVALID runNumber / tfCounter: runNumber " << dh->runNumber
542 <<
", tfCounter " << dh->tfCounter <<
", FMQ runNumber " << fmqRunNumber
543 <<
" for msgidx " << msgidx <<
": " <<
DataSpecUtils::describe(
OutputSpec{dh->dataOrigin, dh->dataDescription, dh->subSpecification}) <<
" part " << dh->splitPayloadIndex <<
" of " << dh->splitPayloadParts <<
" payload " << parts.At(msgidx + 1)->GetSize();
546 OutputSpec query{dh->dataOrigin, dh->dataDescription, dh->subSpecification};
547 LOG(
debug) <<
"processing " <<
DataSpecUtils::describe(
OutputSpec{dh->dataOrigin, dh->dataDescription, dh->subSpecification}) <<
" time slice " << dph->startTime <<
" part " << dh->splitPayloadIndex <<
" of " << dh->splitPayloadParts;
548 int finalBlockIndex = 0;
549 std::string channelName =
"";
551 for (
auto const& spec : filterSpecs) {
555 channelName = channelRetriever(query, dph->startTime);
564 if (finalBlockIndex > parts.Size()) {
570 if (!channelName.empty()) {
584 LOGP(
debug,
"associating {} part(s) at index {} to channel {} ({})", finalBlockIndex - msgidx, msgidx, channelName, outputs[channelName].
Size());
585 for (; msgidx < finalBlockIndex; ++msgidx) {
586 outputs[channelName].AddPart(std::move(parts.At(msgidx)));
590 msgidx = finalBlockIndex - 2;
597 bool didSendParts =
false;
598 for (
auto& [channelName, channelParts] : outputs) {
599 if (channelParts.Size() == 0) {
605 if (not unmatchedDescriptions.empty()) {
606 if (throwOnUnmatchedInputs) {
607 std::string descriptions;
608 for (
auto const& desc : unmatchedDescriptions) {
609 descriptions +=
"\n " + desc;
611 throw std::runtime_error(
"No matching filter rule for input data " + descriptions +
612 "\n Add appropriate matcher(s) to dataspec definition or allow to drop unmatched data");
614 bool changed =
false;
615 for (
auto const& desc : unmatchedDescriptions) {
616 if (not droppedDataSpecs->find(desc)) {
618 droppedDataSpecs->add(desc);
623 droppedDataSpecs->warning();
633 auto timesliceId = std::make_shared<size_t>(startTime);
638 runNumber = strtoul(
device->fConfig->GetProperty<std::string>(
"runNumber",
"").c_str(),
nullptr, 10);
643 for (
int i = 0;
i < parts.Size(); ++
i) {
656 if (*timesliceId != newTimesliceId) {
657 LOG(fatal) <<
"Time slice ID provided from oldestPossible mechanism " << newTimesliceId <<
" is out of sync with expected value " << *timesliceId;
659 *timesliceId += step;
670 std::vector<OutputSpec>
const& outputs,
671 char const* defaultChannelConfig,
675 bool doInjectMissingData,
676 unsigned int doPrintSizes)
682 static std::vector<std::string>
channels;
683 static std::vector<int> numberOfEoS(
channels.size(), 0);
684 static std::vector<int> eosPeersCount(
channels.size(), 0);
692 auto outputChannels = ctx.services().get<
RawDeviceService>().spec().outputChannels;
701 auto channelConfigurationChecker = [
device, deviceName, services = ctx.services()]() {
705 eosPeersCount.clear();
708 if (strncmp(channelName.c_str(), deviceName.c_str(), deviceName.size()) == 0) {
713 LOGP(detail,
"Injecting channel '{}' into DPL configuration", channel);
718 .hasPendingEvents =
false,
720 .channel = &channelPtr,
725 numberOfEoS.resize(
channels.size(), 0);
726 eosPeersCount.resize(
channels.size(), 0);
734 static bool wasRunning =
false;
735 if (fair::mq::State{
state} == fair::mq::State::Running) {
738 if (fair::mq::State{
state} != fair::mq::State::Ready || !wasRunning) {
741 uv_update_time(deviceState.loop);
746 int64_t cleanupCount = deviceState.cleanupCount.load();
751 doDrain =
device->NewStatePending() ==
false && deviceState.cleanupCount == cleanupCount;
752 fair::mq::Parts parts;
753 for (
size_t ci = 0; ci < deviceState.inputChannelInfos.size(); ++ci) {
754 auto& info = deviceState.inputChannelInfos[ci];
759 info.channel->Receive(parts, 10);
762 uv_run(deviceState.loop, UV_RUN_NOWAIT);
766 ctx.services().get<
CallbackService>().set<CallbackService::Id::Start>(channelConfigurationChecker);
767 if (ctx.options().get<std::string>(
"ready-state-policy") ==
"drain") {
768 LOG(info) <<
"Drain mode requested while in Ready state";
769 ctx.services().get<
CallbackService>().set<CallbackService::Id::DeviceStateChanged>(drainMessages);
772 static auto countEoS = [](fair::mq::Parts& inputs) ->
int {
774 for (
int msgidx = 0; msgidx < inputs.Size() / 2; ++msgidx) {
777 if (inputs.At(msgidx * 2).get() ==
nullptr) {
780 auto const sih = o2::header::get<SourceInfoHeader*>(inputs.At(msgidx * 2)->GetData());
789 auto dataHandler = [converter, doInjectMissingData, doPrintSizes,
790 outputRoutes = std::move(outputRoutes),
794 outputChannels = std::move(outputChannels)](
ServiceRegistryRef ref,
TimingInfo& timingInfo, fair::mq::Parts& inputs, int,
size_t ci,
bool newRun) ->
bool {
798 static std::string emptyChannel =
"";
799 for (
auto& route : outputRoutes) {
801 if (
DataSpecUtils::match(route.matcher, query) && ((timeslice % route.maxTimeslices) == route.timeslice)) {
802 return route.channel;
808 std::string
const& channel =
channels[ci];
810 int nEos = countEoS(inputs);
812 std::fill(numberOfEoS.begin(), numberOfEoS.end(), 0);
813 std::fill(eosPeersCount.begin(), eosPeersCount.end(), 0);
815 numberOfEoS[ci] += nEos;
816 if (numberOfEoS[ci]) {
817 eosPeersCount[ci] = std::max<int>(eosPeersCount[ci],
device->GetNumberOfConnectedPeers(channel));
820 bool shouldstop =
false;
821 if (doInjectMissingData) {
824 bool didSendParts = converter(timingInfo,
ref, inputs, channelRetriever, timesliceIndex->getOldestPossibleOutput().timeslice.value, shouldstop);
832 bool everyEoS = shouldstop;
833 if (!shouldstop && nEos) {
835 for (
unsigned int i = 0;
i < numberOfEoS.size();
i++) {
836 if (numberOfEoS[
i] < eosPeersCount[
i]) {
844 LOG(info) <<
"Received (on channel " << ci <<
") " << numberOfEoS[ci] <<
" end-of-stream from " << eosPeersCount[ci] <<
" peers, forwarding end-of-stream (shouldstop " << (int)shouldstop <<
", nEos " << nEos <<
", newRun " << (
int)newRun <<
")";
846 for (
auto& info : deviceState->inputChannelInfos) {
849 std::fill(numberOfEoS.begin(), numberOfEoS.end(), 0);
850 std::fill(eosPeersCount.begin(), eosPeersCount.end(), 0);
851 control->endOfStream();
858 static size_t currentRunNumber = -1;
859 static bool inStopTransition =
false;
862 if (limiter.
check(ctx, std::stoi(
device->fConfig->GetValue<std::string>(
"timeframes-rate-limit")), minSHM)) {
863 inStopTransition =
true;
866 bool didSendParts =
false;
867 for (
size_t ci = 0; ci <
channels.size(); ++ci) {
869 if (ci > 0 && ci % 10 == 0) {
872 std::string
const& channel =
channels[ci];
873 int waitTime =
channels.size() == 1 ? -1 : 1;
875 while (maxRead-- > 0) {
876 fair::mq::Parts parts;
877 auto res =
device->Receive(parts, channel, 0, waitTime);
878 if (
res == (
size_t)fair::mq::TransferCode::error) {
879 LOGP(
error,
"Error while receiving on channel {}", channel);
882 unsigned int nReceived = parts.Size();
883 if (nReceived != 0) {
884 auto const dh = o2::header::get<DataHeader*>(parts.At(0)->GetData());
885 auto& timingInfo = ctx.services().get<
TimingInfo>();
887 if (currentRunNumber != -1 && dh->runNumber != 0 && dh->runNumber != currentRunNumber) {
889 inStopTransition =
false;
891 if (currentRunNumber == -1 || dh->runNumber != 0) {
894 timingInfo.runNumber = dh->runNumber;
895 timingInfo.firstTForbit = dh->firstTForbit;
896 timingInfo.tfCounter = dh->tfCounter;
898 auto const dph = o2::header::get<DataProcessingHeader*>(parts.At(0)->GetData());
899 if (dph !=
nullptr) {
900 timingInfo.timeslice = dph->startTime;
901 timingInfo.creation = dph->creation;
903 if (!inStopTransition) {
904 didSendParts |= dataHandler(ctx.services(), timingInfo, parts, 0, ci, newRun);
907 ctx.services().get<o2::monitoring::Monitoring>().send(o2::monitoring::Metric{(
uint64_t)timingInfo.tfCounter,
"df-sent"}.addTag(o2::monitoring::tags::Key::Subsystem, o2::monitoring::tags::Value::DPL));
910 if (nReceived == 0 ||
channels.size() == 1) {
923 decongestion.nextEnumerationTimeslice -= 1;
929 const char*
d = strdup(((std::string(defaultChannelConfig).find(
"name=") == std::string::npos ? (std::string(
"name=") +
name +
",") :
"") + std::string(defaultChannelConfig)).c_str());
944 const char* defaultChannelConfig)
955 auto channelConfig = options.
get<std::string>(
"channel-config");
956 std::regex
r{R
"(name=([^,]*))"};
957 std::vector<std::string> values{std::sregex_token_iterator{std::begin(channelConfig), std::end(channelConfig), r, 1},
958 std::sregex_token_iterator{}};
960 throw std::runtime_error(
"failed to extract channel name from channel configuration parameter '" + channelConfig +
"'");
962 std::string outputChannelName =
values[0];
968 auto channelConfigurationChecker = [inputSpecs = std::move(inputSpecs),
device, outputChannelName]() {
969 LOG(info) <<
"checking channel configuration";
970 if (
device->GetChannels().count(outputChannelName) == 0) {
971 throw std::runtime_error(
"no corresponding output channel found for input '" + outputChannelName +
"'");
975 auto lastDataProcessingHeader = std::make_shared<DataProcessingHeader>(0, 0);
977 auto& spec =
const_cast<DeviceSpec&
>(deviceSpec);
979 for (
auto const& inputSpec : inputSpecs) {
985 .matcher = inputSpec,
986 .channel = outputChannelName,
988 spec.forwards.emplace_back(route);
995 for (
auto& channelInfo :
device->GetChannels()) {
996 auto& channelName = channelInfo.first;
997 if (channelName != outputChannelName) {
1003 runNumber = strtoul(
device->fConfig->GetProperty<std::string>(
"runNumber",
"").c_str(),
nullptr, 10);
1018 auto channelAlloc = o2::pmr::getTransportAllocator(channelInfo.second[0].Transport());
1020 fair::mq::Parts out;
1021 out.AddPart(std::move(headerMessage));
1023 out.AddPart(
device->NewMessageFor(channelName, 0, 0));
1030 for (
auto it = inputs.
begin(); it != inputs.
end(); it++) {
1031 for (
auto const& part : it.parts()) {
1032 const auto* dph = o2::header::get<DataProcessingHeader*>(part.header);
1035 lastDataProcessingHeader->startTime = dph->startTime;
1036 lastDataProcessingHeader->duration = dph->duration;
1037 lastDataProcessingHeader->creation = dph->creation;
1043 const char*
d = strdup(((std::string(defaultChannelConfig).find(
"name=") == std::string::npos ? (std::string(
"name=") +
name +
",") :
"") + std::string(defaultChannelConfig)).c_str());
1053 Inputs const& inputSpecs,
1054 const char* defaultChannelConfig,
1061 spec.
inputs = inputSpecs;
1069 auto channelNames = std::make_shared<std::vector<std::string>>();
1070 auto channelConfigurationInitializer = [&proxy, inputSpecs = std::move(inputSpecs),
device, channelSelector, &deviceSpec, channelNames]() {
1071 channelNames->clear();
1072 auto& mutableDeviceSpec =
const_cast<DeviceSpec&
>(deviceSpec);
1073 for (
auto const& spec : inputSpecs) {
1074 auto channel = channelSelector(spec,
device->GetChannels());
1075 if (
device->GetChannels().count(channel) == 0) {
1076 throw std::runtime_error(
"no corresponding output channel found for input '" + channel +
"'");
1089 mutableDeviceSpec.forwards.emplace_back(route);
1091 channelNames->emplace_back(std::move(channel));
1093 std::function<fair::mq::Channel&(std::string
const&)> bindByName = [
device](std::string
const& channelName) -> fair::mq::Channel& {
1094 auto channel =
device->GetChannels().find(channelName);
1095 if (channel ==
device->GetChannels().end()) {
1096 LOGP(fatal,
"Expected channel {} not configured.", channelName);
1098 return channel->second.at(0);
1101 std::function<bool()> newStateCallback = [
device]() ->
bool {
1102 return device->NewStatePending();
1104 proxy.
bind(mutableDeviceSpec.outputs, mutableDeviceSpec.inputs, mutableDeviceSpec.forwards, bindByName, newStateCallback);
1107 auto channelConfigurationDisposer = [&deviceSpec]() {
1108 auto& mutableDeviceSpec =
const_cast<DeviceSpec&
>(deviceSpec);
1109 mutableDeviceSpec.
forwards.clear();
1114 auto lastDataProcessingHeader = std::make_shared<DataProcessingHeader>(0, 0);
1119 for (
auto& channelInfo :
device->GetChannels()) {
1120 auto& channelName = channelInfo.first;
1121 auto checkChannel = [channelNames = std::move(*channelNames)](std::string
const&
name) ->
bool {
1122 for (
auto const&
n : channelNames) {
1129 if (!checkChannel(channelName)) {
1134 runNumber = strtoul(
device->fConfig->GetProperty<std::string>(
"runNumber",
"").c_str(),
nullptr, 10);
1149 auto channelAlloc = o2::pmr::getTransportAllocator(channelInfo.second[0].Transport());
1151 fair::mq::Parts out;
1152 out.AddPart(std::move(headerMessage));
1154 out.AddPart(
device->NewMessageFor(channelName, 0, 0));
1155 LOGP(detail,
"Forwarding EoS to {}", channelName);
1165 for (
auto it = inputs.
begin(); it != inputs.
end(); it++) {
1166 for (
auto const& part : it.parts()) {
1167 const auto* dph = o2::header::get<DataProcessingHeader*>(part.header);
1170 lastDataProcessingHeader->startTime = dph->startTime;
1171 lastDataProcessingHeader->duration = dph->duration;
1172 lastDataProcessingHeader->creation = dph->creation;
1178 const char*
d = strdup(((std::string(defaultChannelConfig).find(
"name=") == std::string::npos ? (std::string(
"name=") +
name +
",") :
"") + std::string(defaultChannelConfig)).c_str());
header::DataDescription description
std::vector< OutputRoute > routes
std::vector< std::string > header
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error First event to Number of events to Number of iterations to Number of iterations to Number of initial iterations excluded from const char Directory with events to Events directory is and not inside events Show standalone event Run event generator maximum time bin of continuous for triggered for automatic continuous for automatic continuous triggered uint64_t
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error First event to Number of events to Number of iterations to Number of iterations to Number of initial iterations excluded from const char Directory with events to Events directory is and not inside events d
configStandalone Reconstruction rec_tpc multiplier for the combined cluster track error during track following area in cm for the search of for z only used if decrease removal by when above this local occupancy rowx Shift of TPC revert cluster flag edge bit distance to edge exceeds this ZOffset for secondary multiple of radius max P of electron K BB bands crossing max P of electron p BB bands crossing max P of electron d BB bands crossing max P of electron t BB bands crossing min accepted dEdxMaxTPC of the track Additive extra cluster error for Y2 if edge flag set Additive extra cluster error for Y2 if single set Additive extra cluster error for Y2 if or single set Additive extra cluster error for Z2 if or single set Extra errors to add to track when crossing depending on addErrorsCECrossing Inner portion of y range in sector that is not used in searching for extrapolated track candidates factor2YS for track merging factor2K for track merging Margin in cm of Y position when rejecting edge clusters based on uncorrected track Y Max fraction of shared clusters for tracklet Except pad from cluster finding if total number of charges in a fragment is above this Except pad from cluster finding if number of consecutive charges in a fragment is above this Threshold where a timebin is considered disabling the noisy pad check for that pad Treat signal above this minimum as saturated Smoothing factor for the exponential Highly Ionising Particle tail filter Number of timebins to use for the averaging Add additional custom track errors when crossing relative as fraction of Do N fit passes in final fit of< 0:reject at max -n hits") AddOptionRTC(rejectIFCLowRadiusCluster, uint8_t, 1, "", 0, "Reject clusters that get the IFC mask error during refit") AddOptionRTC(dEdxTruncLow, uint8_t, 2, "", 0, "Low truncation threshold, fraction of 128") AddOptionRTC(dEdxTruncHigh, uint8_t, 77, "", 0, "High truncation threshold, fraction of 128") AddOptionRTC(extrapolationTracking, int8_t, 1, "", 0, "Enable Extrapolation Tracking(prolong tracks to adjacent sectors to find short segments)") AddOptionRTC(disableRefitAttachment, uint8_t, 0, "", 0, "Bitmask to disable certain attachment steps during refit(1:attachment, 2:propagation, 4:loop following, 8:mirroring)") AddOptionRTC(rejectionStrategy, uint8_t, o2::gpu::GPUSettings::RejectionStrategyA, "", 0, "Enable rejection of TPC clusters for compression(0=no, 1=strategy A, 2=strategy B)") AddOptionRTC(mergeLoopersAfterburner, uint8_t, 1, "", 0, "Run afterburner for additional looper merging") AddOptionRTC(compressionTypeMask, uint8_t, o2::gpu::GPUSettings::CompressionFull, "", 0, "TPC Compression mode bits(1=truncate charge/width LSB, 2=differences, 4=track-model)") AddOptionRTC(compressionSortOrder, uint8_t, o2::gpu::GPUSettings::SortTime, "", 0, "Sort order of TPC compression(0=time, 1=pad, 2=Z-time-pad, 3=Z-pad-time, 4=no sorting(use incoming order))") AddOptionRTC(sigBitsCharge, uint8_t, 4, "", 0, "Number of significant bits for TPC cluster charge in compression mode 1") AddOptionRTC(sigBitsWidth, uint8_t, 3, "", 0, "Number of significant bits for TPC cluster width in compression mode 1") AddOptionRTC(dropLoopers, uint8_t, 0, "", 0, "Drop looping tracks starting from second loop") AddOptionRTC(mergerInterpolateErrors, uint8_t, 1, "", 0, "Use interpolation instead of extrapolation for chi2 based cluster rejection") AddOptionRTC(mergerInterpolateRejectAlsoOnCurrentPosition, uint8_t, 1, "", 0, "When using mergerInterpolateErrors, reject based on chi2 twice computed with interpolated and current track position starting from NDF > mergerNonInterpolateRejectMinNDF Merge tracks accross the central electrode Enable PID response Add sub threshold clusters in TPC dEdx computation OR mask of TPC flags that will reject the cluster in alternative dEdx Reject edge clusters based on uncorrected track Y during track fit Increase decrease removal by when on this number of pads from the edge h configStandalone Reconstruction rec_trd Max chi2 for TRD tracklets to be matched to a track Chi2 cut for strict matching mode Number of sigmas for ITS TPC track time error estimate Addition to search road around track prolongation along Y in cm Optimal tracklet rphi resolution in maximum chi2 per attached tracklet for TRD tracks take into account the full likelihood of the slope including exponential tails Tracks with less attached tracklets are discarded after the tracking Post trigger Pile up integration time in BCs fits all iterations but the last one in projections Use material lookup table for TPC refit Apply workarounds to avoid cyclic merge should not be needed tpc dyn configStandalone Processing proc_rtc Replace constant variables static by constexpr expressions Compile RTC in deterministic with NO_FAST_MATH flags and GPUCA_DETERMINISTIC_MODE define Use RTC to optimize GPU code h configStandalone Processing proc_rtctech Use a file lock to serialize access to the cache folder Print launch bounds used for RTC code as debugging for exit after Allow RTC with slave GPUReconstruction instances with optConstexpr and optSpecialcode Maximum number of RTC cache files per backend in the cache the oldest are Prepend RTC compilation commands by this string Load a parameter object containing the launch bounds from a file h configStandalone Processing proc_param TPC Cluster Z Error Parameterization h configStandalone Processing settings for neural network proc_nn std::string Specify inference device(cpu(default), rocm, cuda)") AddOption(nnInferenceDeviceId
char error[CURL_ERROR_SIZE]
Header to collect LHC related constants.
T get(const char *key) const
void bind(std::vector< OutputRoute > const &outputs, std::vector< InputRoute > const &inputs, std::vector< ForwardRoute > const &forwards, std::function< fair::mq::Channel &(std::string const &)> bindChannelByName, std::function< bool(void)> newStateRequestedCallback)
int check(ProcessingContext &ctx, int maxInFlight, size_t minSHM)
virtual fair::mq::Device * device()=0
GLuint GLsizei const GLuint const GLintptr const GLsizeiptr * sizes
GLuint const GLchar * name
GLenum GLsizei GLsizei GLint * values
typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode)
GLbitfield GLuint64 timeout
constexpr o2::header::DataOrigin gDataOriginPHS
constexpr o2::header::DataOrigin gDataOriginHMP
constexpr o2::header::DataDescription gDataDescriptionEos
constexpr o2::header::DataOrigin gDataOriginEMC
constexpr o2::header::DataOrigin gDataOriginAny
constexpr o2::header::DataDescription gDataDescriptionAny
Defining ITS Vertex explicitly as messageable.
void injectMissingData(fair::mq::Device &device, fair::mq::Parts &parts, std::vector< OutputRoute > const &routes, bool doInjectMissingData, unsigned int doPrintSizes)
DataProcessorSpec specifyExternalFairMQDeviceProxy(char const *label, std::vector< OutputSpec > const &outputs, const char *defaultChannelConfig, InjectorFunction converter, uint64_t minSHM=0, bool sendTFcounter=false, bool doInjectMissingData=false, unsigned int doPrintSizes=0)
@ RAWFMQ
A raw FairMQ channel which is not accounted by the framework.
std::function< std::string(InputSpec const &input, const std::unordered_map< std::string, std::vector< fair::mq::Channel > > &channels)> ChannelSelector
std::function< bool(TimingInfo &, ServiceRegistryRef const &services, fair::mq::Parts &inputs, ChannelRetriever, size_t newTimesliceId, bool &stop)> InjectorFunction
DataProcessorSpec specifyFairMQDeviceMultiOutputProxy(char const *label, Inputs const &inputSpecs, const char *defaultChannelConfig, ChannelSelector channelSelector=defaultOutputProxyChannelSelector)
InjectorFunction dplModelAdaptor(std::vector< OutputSpec > const &specs={{header::gDataOriginAny, header::gDataDescriptionAny}}, DPLModelAdapterConfig config=DPLModelAdapterConfig{})
InjectorFunction o2DataModelAdaptor(OutputSpec const &spec, uint64_t startTime, uint64_t step)
DataProcessorSpec specifyFairMQDeviceOutputProxy(char const *label, Inputs const &inputSpecs, const char *defaultChannelConfig)
void sendOnChannel(fair::mq::Device &device, o2::header::Stack &&headerStack, fair::mq::MessagePtr &&payloadMessage, OutputSpec const &spec, ChannelRetriever &channelRetriever)
@ Completed
The channel was signaled it will not receive any data.
@ Running
The channel is actively receiving data.
std::string formatExternalChannelConfiguration(InputChannelSpec const &)
helper method to format a configuration string for an external channel
std::function< std::string const &(OutputSpec const &, DataProcessingHeader::StartTime)> ChannelRetriever
AlgorithmSpec::ProcessCallback adaptStateless(LAMBDA l)
std::string defaultOutputProxyChannelSelector(InputSpec const &input, const std::unordered_map< std::string, std::vector< fair::mq::Channel > > &channels)
Default way to select an output channel for multi-output proxy.
auto getFinalIndex(DataHeader const &dh, size_t msgidx) -> size_t
std::vector< InputSpec > Inputs
void appendForSending(fair::mq::Device &device, o2::header::Stack &&headerStack, size_t timeSliceID, fair::mq::MessagePtr &&payloadMessage, OutputSpec const &spec, fair::mq::Parts &messageCache, ChannelRetriever &channelRetriever)
AlgorithmSpec::InitCallback adaptStateful(LAMBDA l)
InjectorFunction incrementalConverter(OutputSpec const &spec, o2::header::SerializationMethod method, uint64_t startTime, uint64_t step)
fair::mq::MessagePtr getMessage(ContainerT &&container, FairMQMemoryResource *targetResource=nullptr)
static constexpr int INVALID
header::DataDescription description
header::DataHeader::SubSpecificationType subSpec
header::DataOrigin origin
header::DataOrigin origin
header::DataDescription description
bool throwOnUnmatchedInputs
throw runtime error if an input message is not matched by filter rules
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
A label that can be associated to a DataProcessorSpec.
std::vector< DataProcessorLabel > labels
static std::string describe(InputSpec const &spec)
static ConcreteDataTypeMatcher asConcreteDataTypeMatcher(OutputSpec const &spec)
static ConcreteDataMatcher asConcreteDataMatcher(InputSpec const &input)
static std::optional< header::DataHeader::SubSpecificationType > getOptionalSubSpec(OutputSpec const &spec)
Get the subspec, if available.
static bool match(InputSpec const &spec, ConcreteDataMatcher const &target)
bool nextEnumerationTimesliceRewinded
static DeploymentMode deploymentMode()
static std::string inputChannel2String(const InputChannelSpec &channel)
Helper to provide the channel configuration string for an input channel.
static std::string outputChannel2String(const OutputChannelSpec &channel)
Helper to provide the channel configuration string for an output channel.
std::vector< ForwardRoute > forwards
Running state information of a given device.
static ForwardingPolicy createDefaultForwardingPolicy()
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"
std::vector< ChannelData > channels