242 static std::vector<bool> present;
243 static std::vector<bool> ignored;
244 static std::vector<size_t> dataSizes;
245 static std::vector<bool> showSize;
247 present.resize(routes.size(),
false);
249 ignored.resize(routes.size(),
false);
251 dataSizes.resize(routes.size(), 0);
253 showSize.resize(routes.size(),
false);
255 static std::vector<size_t> unmatchedDescriptions;
256 unmatchedDescriptions.clear();
262 size_t expectedDataSpecs = 0;
263 for (
size_t pi = 0; pi < present.size(); ++pi) {
264 auto& spec = routes[pi].matcher;
269 if (routes[pi].timeslice == 0) {
274 size_t foundDataSpecs = 0;
275 bool skipAsAllFound =
false;
276 for (
int msgidx = 0; msgidx < parts.Size(); msgidx += 2) {
277 bool allFound =
true;
279 const auto dh = o2::header::get<DataHeader*>(parts.At(msgidx)->GetData());
280 auto const sih = o2::header::get<SourceInfoHeader*>(parts.At(msgidx)->GetData());
281 if (sih !=
nullptr) {
285 if (parts.At(msgidx).get() ==
nullptr) {
286 LOG(error) <<
"unexpected nullptr found. Skipping message pair.";
290 LOG(error) <<
"data on input " << msgidx <<
" does not follow the O2 data model, DataHeader missing";
296 if (firstDH ==
nullptr) {
298 if (doPrintSizes && firstDH->
tfCounter % doPrintSizes != 0) {
303 if (dph ==
nullptr) {
304 dph = o2::header::get<DataProcessingHeader*>(parts.At(msgidx)->GetData());
305 for (
size_t pi = 0; pi < present.size(); ++pi) {
306 if (routes[pi].timeslice != (dph->
startTime % routes[pi].maxTimeslices)) {
311 for (
size_t pi = 0; pi < present.size(); ++pi) {
312 if ((present[pi] || ignored[pi]) && !doPrintSizes) {
316 if (routes[pi].timeslice != (dph->
startTime % routes[pi].maxTimeslices)) {
321 auto& spec = routes[pi].matcher;
322 OutputSpec query{dh->dataOrigin, dh->dataDescription, dh->subSpecification};
324 if (!present[pi] && !ignored[pi]) {
334 if (addToSize >= 0) {
335 int increment = (dh->splitPayloadParts > 0 && dh->splitPayloadParts == dh->splitPayloadIndex) ? 1 : 2;
336 for (
int msgidx2 = msgidx + 1; msgidx2 < msgidxLast; msgidx2 += increment) {
337 dataSizes[addToSize] += parts.At(msgidx2)->GetSize();
341 msgidx = msgidxLast - 2;
342 if (allFound && !doPrintSizes) {
343 skipAsAllFound =
true;
349 for (
size_t pi = 0; pi < present.size(); ++pi) {
350 if (present[pi] && !ignored[pi]) {
353 if (!present[pi] && !ignored[pi]) {
355 unmatchedDescriptions.push_back(pi);
358 int timeframeCompleteness = emptyTf ? 0 : (unmatchedDescriptions.size() ? -1 : 1);
359 (
void)timeframeCompleteness;
361 if (skipAsAllFound && !doPrintSizes) {
365 if (firstDH && doPrintSizes) {
366 std::string
sizes =
"";
367 size_t totalSize = 0;
368 for (
size_t pi = 0; pi < present.size(); ++pi) {
370 totalSize += dataSizes[pi];
371 auto& spec = routes[pi].matcher;
375 LOGP(important,
"RAW {} size report:{}- Total:{}", firstDH->
tfCounter,
sizes, fmt::group_digits(totalSize));
378 if (!doInjectMissingData) {
382 if (unmatchedDescriptions.size() > 0) {
385 LOG(error) <<
"Received an EndOfStream message together with data. This should not happen.";
387 LOG(detail) <<
"This is an End Of Stream message. Not injecting anything.";
390 if (firstDH ==
nullptr) {
391 LOG(error) <<
"Input proxy received incomplete data without any data header. This should not happen! Cannot inject missing data as requsted.";
394 if (dph ==
nullptr) {
395 LOG(error) <<
"Input proxy received incomplete data without any data processing header. This should happen! Cannot inject missing data as requsted.";
398 std::string missing =
"";
399 bool showAlarm =
false;
400 for (
auto mi : unmatchedDescriptions) {
401 auto& spec = routes[mi].matcher;
407 if (subSpec == std::nullopt) {
408 *subSpec = 0xDEADBEEF;
413 dh.subSpecification = *subSpec;
415 dh.splitPayloadParts = 0;
416 dh.splitPayloadIndex = 0;
419 auto& channelName = routes[mi].channel;
420 auto& channelInfo = device.GetChannel(channelName);
421 auto channelAlloc = o2::pmr::getTransportAllocator(channelInfo.Transport());
423 parts.AddPart(std::move(headerMessage));
425 parts.AddPart(device.NewMessageFor(channelName, 0, 0));
430 static int maxWarn = 10;
431 static int contDeadBeef = 0;
432 if (showAlarm && ++contDeadBeef <= maxWarn) {
433 LOGP(alarm,
"Found {}/{} data specs, missing data specs: {}, injecting 0xDEADBEEF{}", foundDataSpecs, expectedDataSpecs, missing, contDeadBeef == maxWarn ?
" - disabling alarm now to stop flooding the log" :
"");
442 class DroppedDataSpecs
445 DroppedDataSpecs() =
default;
451 [[nodiscard]]
bool find(std::string
const& desc)
const
453 return descriptions.find(desc) != std::string::npos;
456 void add(std::string
const& desc)
458 descriptions +=
"\n " + desc;
463 if (not descriptions.empty()) {
464 LOG(warning) <<
"Some input data could not be matched by filter rules to output specs\n"
465 <<
"Active rules: " << descriptions <<
"\n"
466 <<
"DROPPING OF THESE MESSAGES HAS BEEN ENABLED BY CONFIGURATION";
471 std::string descriptions;
474 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) {
476 std::unordered_map<std::string, fair::mq::Parts> outputs;
477 std::vector<std::string> unmatchedDescriptions;
480 static bool override_creation_env = getenv(
"DPL_RAWPROXY_OVERRIDE_ORBITRESET");
481 bool override_creation =
false;
482 uint64_t creationVal = 0;
483 if (override_creation_env) {
484 static uint64_t creationValBase = std::stoul(getenv(
"DPL_RAWPROXY_OVERRIDE_ORBITRESET"));
485 creationVal = creationValBase;
486 override_creation =
true;
488 auto orbitResetTimeUrl = device->fConfig->GetProperty<std::string>(
"orbit-reset-time",
"ccdb://CTP/Calib/OrbitResetTime");
490 creationVal = std::strtoll(orbitResetTimeUrl.c_str(), &err, 10);
491 if (err && *err == 0 && creationVal) {
492 override_creation =
true;
496 for (
int msgidx = 0; msgidx < parts.Size(); msgidx += 2) {
497 if (parts.At(msgidx).get() ==
nullptr) {
498 LOG(error) <<
"unexpected nullptr found. Skipping message pair.";
501 const auto dh = o2::header::get<DataHeader*>(parts.At(msgidx)->GetData());
503 LOG(error) <<
"data on input " << msgidx <<
" does not follow the O2 data model, DataHeader missing";
509 auto dph = o2::header::get<DataProcessingHeader*>(parts.At(msgidx)->GetData());
511 LOG(error) <<
"data on input " << msgidx <<
" does not follow the O2 data model, DataProcessingHeader missing";
515 if (override_creation) {
519 timingInfo.creation = dph->creation;
520 timingInfo.firstTForbit = dh->firstTForbit;
521 timingInfo.runNumber = dh->runNumber;
522 timingInfo.tfCounter = dh->tfCounter;
523 LOG(
debug) << msgidx <<
": " <<
DataSpecUtils::describe(
OutputSpec{dh->dataOrigin, dh->dataDescription, dh->subSpecification}) <<
" part " << dh->splitPayloadIndex <<
" of " << dh->splitPayloadParts <<
" payload " << parts.At(msgidx + 1)->GetSize();
525 OutputSpec query{dh->dataOrigin, dh->dataDescription, dh->subSpecification};
526 LOG(
debug) <<
"processing " <<
DataSpecUtils::describe(
OutputSpec{dh->dataOrigin, dh->dataDescription, dh->subSpecification}) <<
" time slice " << dph->startTime <<
" part " << dh->splitPayloadIndex <<
" of " << dh->splitPayloadParts;
527 int finalBlockIndex = 0;
528 std::string channelName =
"";
530 for (
auto const& spec : filterSpecs) {
534 channelName = channelRetriever(query, dph->startTime);
543 if (finalBlockIndex > parts.Size()) {
549 if (!channelName.empty()) {
563 LOGP(
debug,
"associating {} part(s) at index {} to channel {} ({})", finalBlockIndex - msgidx, msgidx, channelName, outputs[channelName].
Size());
564 for (; msgidx < finalBlockIndex; ++msgidx) {
565 outputs[channelName].AddPart(std::move(parts.At(msgidx)));
569 msgidx = finalBlockIndex - 2;
576 bool didSendParts =
false;
577 for (
auto& [channelName, channelParts] : outputs) {
578 if (channelParts.Size() == 0) {
582 sendOnChannel(*device, channelParts, channelName, newTimesliceId);
584 if (not unmatchedDescriptions.empty()) {
585 if (throwOnUnmatchedInputs) {
586 std::string descriptions;
587 for (
auto const& desc : unmatchedDescriptions) {
588 descriptions +=
"\n " + desc;
590 throw std::runtime_error(
"No matching filter rule for input data " + descriptions +
591 "\n Add appropriate matcher(s) to dataspec definition or allow to drop unmatched data");
593 bool changed =
false;
594 for (
auto const& desc : unmatchedDescriptions) {
595 if (not droppedDataSpecs->find(desc)) {
597 droppedDataSpecs->add(desc);
602 droppedDataSpecs->warning();
643 std::vector<OutputSpec>
const& outputs,
644 char const* defaultChannelConfig,
648 bool doInjectMissingData,
649 unsigned int doPrintSizes)
655 static std::vector<std::string>
channels;
656 static std::vector<int> numberOfEoS(
channels.size(), 0);
657 static std::vector<int> eosPeersCount(
channels.size(), 0);
665 auto outputChannels = ctx.services().get<
RawDeviceService>().spec().outputChannels;
674 auto channelConfigurationChecker = [device, deviceName, services = ctx.services()]() {
678 eosPeersCount.clear();
679 for (
auto& [channelName, _] : services.get<
RawDeviceService>().device()->GetChannels()) {
681 if (strncmp(channelName.c_str(), deviceName.c_str(), deviceName.size()) == 0) {
686 LOGP(detail,
"Injecting channel '{}' into DPL configuration", channel);
688 auto& channelPtr = services.get<
RawDeviceService>().device()->GetChannel(channel, 0);
691 .hasPendingEvents =
false,
693 .channel = &channelPtr,
698 numberOfEoS.resize(
channels.size(), 0);
699 eosPeersCount.resize(
channels.size(), 0);
707 static bool wasRunning =
false;
708 if (fair::mq::State{
state} == fair::mq::State::Running) {
711 if (fair::mq::State{
state} != fair::mq::State::Ready || !wasRunning) {
714 uv_update_time(deviceState.loop);
719 int64_t cleanupCount = deviceState.cleanupCount.load();
724 doDrain = device->NewStatePending() ==
false && deviceState.cleanupCount == cleanupCount;
725 fair::mq::Parts parts;
726 for (
size_t ci = 0; ci < deviceState.inputChannelInfos.size(); ++ci) {
727 auto& info = deviceState.inputChannelInfos[ci];
732 info.channel->Receive(parts, 10);
735 uv_run(deviceState.loop, UV_RUN_NOWAIT);
739 ctx.services().get<
CallbackService>().set<CallbackService::Id::Start>(channelConfigurationChecker);
740 if (ctx.options().get<std::string>(
"ready-state-policy") ==
"drain") {
741 LOG(info) <<
"Drain mode requested while in Ready state";
742 ctx.services().get<
CallbackService>().set<CallbackService::Id::DeviceStateChanged>(drainMessages);
745 static auto countEoS = [](fair::mq::Parts& inputs) ->
int {
747 for (
int msgidx = 0; msgidx < inputs.Size() / 2; ++msgidx) {
750 if (inputs.At(msgidx * 2).get() ==
nullptr) {
753 auto const sih = o2::header::get<SourceInfoHeader*>(inputs.At(msgidx * 2)->GetData());
762 auto dataHandler = [converter, doInjectMissingData, doPrintSizes,
763 outputRoutes = std::move(outputRoutes),
771 static std::string emptyChannel =
"";
772 for (
auto& route : outputRoutes) {
774 if (
DataSpecUtils::match(route.matcher, query) && ((timeslice % route.maxTimeslices) == route.timeslice)) {
775 return route.channel;
781 std::string
const& channel =
channels[ci];
783 int nEos = countEoS(inputs);
785 std::fill(numberOfEoS.begin(), numberOfEoS.end(), 0);
786 std::fill(eosPeersCount.begin(), eosPeersCount.end(), 0);
788 numberOfEoS[ci] += nEos;
789 if (numberOfEoS[ci]) {
790 eosPeersCount[ci] = std::max<int>(eosPeersCount[ci], device->GetNumberOfConnectedPeers(channel));
793 bool shouldstop =
false;
794 if (doInjectMissingData) {
795 injectMissingData(*device, inputs, outputRoutes, doInjectMissingData, doPrintSizes);
797 bool didSendParts = converter(timingInfo,
ref, inputs, channelRetriever, timesliceIndex->getOldestPossibleOutput().timeslice.value, shouldstop);
805 bool everyEoS = shouldstop;
806 if (!shouldstop && nEos) {
808 for (
unsigned int i = 0;
i < numberOfEoS.size();
i++) {
809 if (numberOfEoS[
i] < eosPeersCount[
i]) {
817 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 <<
")";
819 for (
auto& info : deviceState->inputChannelInfos) {
822 std::fill(numberOfEoS.begin(), numberOfEoS.end(), 0);
823 std::fill(eosPeersCount.begin(), eosPeersCount.end(), 0);
824 control->endOfStream();
831 static size_t currentRunNumber = -1;
832 static bool inStopTransition =
false;
835 if (limiter.
check(ctx, std::stoi(device->fConfig->GetValue<std::string>(
"timeframes-rate-limit")), minSHM)) {
836 inStopTransition =
true;
839 bool didSendParts =
false;
840 for (
size_t ci = 0; ci <
channels.size(); ++ci) {
841 std::string
const& channel =
channels[ci];
842 int waitTime =
channels.size() == 1 ? -1 : 1;
844 while (maxRead-- > 0) {
845 fair::mq::Parts parts;
846 auto res = device->Receive(parts, channel, 0, waitTime);
847 if (
res == (
size_t)fair::mq::TransferCode::error) {
848 LOGP(error,
"Error while receiving on channel {}", channel);
851 unsigned int nReceived = parts.Size();
852 if (nReceived != 0) {
853 auto const dh = o2::header::get<DataHeader*>(parts.At(0)->GetData());
854 auto& timingInfo = ctx.services().get<
TimingInfo>();
856 if (currentRunNumber != -1 && dh->runNumber != 0 && dh->runNumber != currentRunNumber) {
858 inStopTransition =
false;
860 if (currentRunNumber == -1 || dh->runNumber != 0) {
863 timingInfo.runNumber = dh->runNumber;
864 timingInfo.firstTForbit = dh->firstTForbit;
865 timingInfo.tfCounter = dh->tfCounter;
867 auto const dph = o2::header::get<DataProcessingHeader*>(parts.At(0)->GetData());
868 if (dph !=
nullptr) {
869 timingInfo.timeslice = dph->startTime;
870 timingInfo.creation = dph->creation;
872 if (!inStopTransition) {
873 didSendParts |= dataHandler(ctx.services(), timingInfo, parts, 0, ci, newRun);
876 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));
879 if (nReceived == 0 ||
channels.size() == 1) {
892 decongestion.nextEnumerationTimeslice -= 1;
898 const char* d = strdup(((std::string(defaultChannelConfig).find(
"name=") == std::string::npos ? (std::string(
"name=") +
name +
",") :
"") + std::string(defaultChannelConfig)).c_str());
913 const char* defaultChannelConfig)
924 auto channelConfig = options.
get<std::string>(
"channel-config");
925 std::regex
r{R
"(name=([^,]*))"};
926 std::vector<std::string> values{std::sregex_token_iterator{std::begin(channelConfig), std::end(channelConfig), r, 1},
927 std::sregex_token_iterator{}};
929 throw std::runtime_error(
"failed to extract channel name from channel configuration parameter '" + channelConfig +
"'");
931 std::string outputChannelName =
values[0];
933 auto* device = rds.
device();
937 auto channelConfigurationChecker = [inputSpecs = std::move(inputSpecs), device, outputChannelName]() {
938 LOG(info) <<
"checking channel configuration";
939 if (device->GetChannels().count(outputChannelName) == 0) {
940 throw std::runtime_error(
"no corresponding output channel found for input '" + outputChannelName +
"'");
944 auto lastDataProcessingHeader = std::make_shared<DataProcessingHeader>(0, 0);
946 auto& spec =
const_cast<DeviceSpec&
>(deviceSpec);
948 for (
auto const& inputSpec : inputSpecs) {
954 .matcher = inputSpec,
955 .channel = outputChannelName,
957 spec.forwards.emplace_back(route);
960 auto forwardEos = [device, lastDataProcessingHeader, outputChannelName](
EndOfStreamContext&) {
964 for (
auto& channelInfo : device->GetChannels()) {
965 auto& channelName = channelInfo.first;
966 if (channelName != outputChannelName) {
980 auto channelAlloc = o2::pmr::getTransportAllocator(channelInfo.second[0].Transport());
983 out.AddPart(std::move(headerMessage));
985 out.AddPart(device->NewMessageFor(channelName, 0, 0));
992 for (
size_t ii = 0; ii != inputs.
size(); ++ii) {
993 for (
size_t pi = 0; pi < inputs.
getNofParts(ii); ++pi) {
994 auto part = inputs.
getByPos(ii, pi);
995 const auto* dph = o2::header::get<DataProcessingHeader*>(part.header);
998 lastDataProcessingHeader->startTime = dph->startTime;
999 lastDataProcessingHeader->duration = dph->duration;
1000 lastDataProcessingHeader->creation = dph->creation;
1006 const char* d = strdup(((std::string(defaultChannelConfig).find(
"name=") == std::string::npos ? (std::string(
"name=") +
name +
",") :
"") + std::string(defaultChannelConfig)).c_str());
1015 Inputs const& inputSpecs,
1016 const char* defaultChannelConfig,
1023 spec.
inputs = inputSpecs;
1026 auto device = rds.
device();
1031 auto channelNames = std::make_shared<std::vector<std::string>>();
1032 auto channelConfigurationInitializer = [&proxy, inputSpecs = std::move(inputSpecs), device, channelSelector, &deviceSpec, channelNames]() {
1033 channelNames->clear();
1034 auto& mutableDeviceSpec =
const_cast<DeviceSpec&
>(deviceSpec);
1035 for (
auto const& spec : inputSpecs) {
1036 auto channel = channelSelector(spec, device->GetChannels());
1037 if (device->GetChannels().count(channel) == 0) {
1038 throw std::runtime_error(
"no corresponding output channel found for input '" + channel +
"'");
1051 mutableDeviceSpec.forwards.emplace_back(route);
1053 channelNames->emplace_back(std::move(channel));
1055 proxy.
bind(mutableDeviceSpec.outputs, mutableDeviceSpec.inputs, mutableDeviceSpec.forwards, *device);
1058 auto channelConfigurationDisposer = [&deviceSpec]() {
1059 auto& mutableDeviceSpec =
const_cast<DeviceSpec&
>(deviceSpec);
1060 mutableDeviceSpec.
forwards.clear();
1065 auto lastDataProcessingHeader = std::make_shared<DataProcessingHeader>(0, 0);
1066 auto forwardEos = [device, lastDataProcessingHeader, channelNames](
EndOfStreamContext&) {
1070 for (
auto& channelInfo : device->GetChannels()) {
1071 auto& channelName = channelInfo.first;
1072 auto checkChannel = [channelNames = std::move(*channelNames)](std::string
const&
name) ->
bool {
1073 for (
auto const&
n : channelNames) {
1080 if (!checkChannel(channelName)) {
1094 auto channelAlloc = o2::pmr::getTransportAllocator(channelInfo.second[0].Transport());
1096 fair::mq::Parts out;
1097 out.AddPart(std::move(headerMessage));
1099 out.AddPart(device->NewMessageFor(channelName, 0, 0));
1100 LOGP(detail,
"Forwarding EoS to {}", channelName);
1110 for (
size_t ii = 0; ii != inputs.
size(); ++ii) {
1111 for (
size_t pi = 0; pi < inputs.
getNofParts(ii); ++pi) {
1112 auto part = inputs.
getByPos(ii, pi);
1113 const auto* dph = o2::header::get<DataProcessingHeader*>(part.header);
1116 lastDataProcessingHeader->startTime = dph->startTime;
1117 lastDataProcessingHeader->duration = dph->duration;
1118 lastDataProcessingHeader->creation = dph->creation;
1124 const char* d = strdup(((std::string(defaultChannelConfig).find(
"name=") == std::string::npos ? (std::string(
"name=") +
name +
",") :
"") + std::string(defaultChannelConfig)).c_str());