Project
Loading...
Searching...
No Matches
AnalysisCCDBHelpers.cxx
Go to the documentation of this file.
1// Copyright 2019-2025 CERN and copyright holders of ALICE O2.
2// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
3// All rights not expressly granted are reserved.
4//
5// This software is distributed under the terms of the GNU General Public
6// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
7//
8// In applying this license CERN does not waive the privileges and immunities
9// granted to it by virtue of its status as an Intergovernmental Organization
10// or submit itself to any jurisdiction.
11
12#include "AnalysisCCDBHelpers.h"
13#include "CCDBFetcherHelper.h"
21#include "Framework/Output.h"
22#include "Framework/Signpost.h"
26#include <fairmq/Version.h>
27#include <arrow/array/builder_binary.h>
28#include <arrow/type.h>
29#include <arrow/type_fwd.h>
30#include <arrow/util/key_value_metadata.h>
31#include <arrow/table.h>
32#include <arrow/array.h>
33#include <arrow/builder.h>
34#include <fmt/base.h>
35#include <ctime>
36#include <memory>
37#include <unordered_map>
38
40
41namespace o2::framework
42{
43// Fill valid routes. Notice that for analysis the timestamps are associated to
44// a ATIM table and there might be multiple CCDB objects of the same kind for
45// dataframe.
46// For this reason rather than matching the Lifetime::Condition, we match the
47// origin.
48namespace
49{
50void fillValidRoutes(CCDBFetcherHelper& helper, std::vector<o2::framework::OutputRoute> const& outputRoutes, std::unordered_map<std::string, int>& bindings)
51{
52 for (auto& route : outputRoutes) {
53 if (std::ranges::none_of(route.matcher.metadata, [](auto const& m) { return m.name.starts_with("ccdb:"); })) {
54 continue;
55 }
56 auto specStr = DataSpecUtils::describe(route.matcher);
57 if (bindings.find(specStr) != bindings.end()) {
58 continue;
59 }
60 bindings[specStr] = helper.routes.size();
61 helper.routes.push_back(route);
62 LOGP(info, "The following route needs condition objects {} ", DataSpecUtils::describe(route.matcher));
63 for (auto& metadata : route.matcher.metadata) {
64 if (metadata.type == VariantType::String) {
65 LOGP(info, "- {}: {}", metadata.name, metadata.defaultValue.asString());
66 }
67 }
68 }
69}
70} // namespace
71
73{
74 return adaptStateful([](ConfigParamRegistry const& options, DeviceSpec const& spec, InitContext& ic) {
75 auto& dec = ic.services().get<DanglingEdgesContext>();
76 // The effective default for each ccdb: option was already resolved at topology
77 // time by ArrowSupport (consulting task Configurables) and registered on this
78 // device's options. Here we just read the final value — honouring any further
79 // runtime override supplied via CLI or JSON config.
80 std::unordered_map<std::string, std::string> ccdbUrls;
81 for (auto& input : dec.analysisCCDBInputs) {
82 for (auto& m : input.metadata) {
83 if (!m.name.starts_with("ccdb:") || ccdbUrls.count(m.name)) {
84 continue;
85 }
86 std::string url = m.defaultValue.asString();
87 if (ConfigParamsHelper::hasOption(spec.options, m.name)) {
88 url = options.get<std::string>(m.name.c_str());
89 }
90 LOGP(info, "CCDB path resolved for {}: {}", m.name, url);
91 ccdbUrls.emplace(m.name, std::move(url));
92 }
93 }
94 std::vector<std::shared_ptr<arrow::Schema>> schemas;
95 for (auto& input : dec.analysisCCDBInputs) {
96 auto schemaMetadata = std::make_shared<arrow::KeyValueMetadata>();
97 std::vector<std::shared_ptr<arrow::Field>> fields;
98 schemaMetadata->Append("outputRoute", DataSpecUtils::describe(input));
99 schemaMetadata->Append("outputBinding", input.binding);
100 for (auto& m : input.metadata) {
101 if (m.name.starts_with("input:")) {
102 auto name = m.name.substr(6);
103 schemaMetadata->Append("sourceTable", name);
104 schemaMetadata->Append("sourceMatcher", DataSpecUtils::describe(std::get<ConcreteDataMatcher>(DataSpecUtils::fromMetadataString(m.defaultValue.get<std::string>()).matcher)));
105 continue;
106 }
107 if (!m.name.starts_with("ccdb:")) {
108 continue;
109 }
110 auto fieldMetadata = std::make_shared<arrow::KeyValueMetadata>();
111 auto it = ccdbUrls.find(m.name);
112 fieldMetadata->Append("url", it != ccdbUrls.end() ? it->second : m.defaultValue.asString());
113 auto columnName = m.name.substr(strlen("ccdb:"));
114#if (FAIRMQ_VERSION_DEC >= 111000)
115 fields.emplace_back(std::make_shared<arrow::Field>(columnName, soa::asArrowDataType<int64_t[3]>(), false, fieldMetadata));
116#else
117 fields.emplace_back(std::make_shared<arrow::Field>(columnName, arrow::binary_view(), false, fieldMetadata));
118#endif
119 }
120 schemas.emplace_back(std::make_shared<arrow::Schema>(fields, schemaMetadata));
121 }
122
123#if (FAIRMQ_VERSION_DEC >= 111000)
124 std::vector<std::pair<uint32_t, std::shared_ptr<arrow::FixedSizeListBuilder>>> allbuilders;
125#else
126 std::vector<std::pair<uint32_t, std::shared_ptr<arrow::BinaryViewBuilder>>> allbuilders;
127#endif
128 allbuilders.resize([&schemas]() { size_t size = 0; for (auto& schema : schemas) { size += schema->num_fields(); }; return size; }());
129 auto* pool = arrow::default_memory_pool();
130
131 int idx = 0;
132 int sidx = 0;
133 for (auto const& schema : schemas) {
134 for (auto const& _ : schema->fields()) {
135#if (FAIRMQ_VERSION_DEC >= 111000)
136 auto value_builder = std::make_shared<arrow::Int64Builder>();
137 allbuilders[idx] = std::make_pair(sidx, std::make_shared<arrow::FixedSizeListBuilder>(pool, std::move(value_builder), 3));
138#else
139 allbuilders[idx] = std::make_pair(sidx, std::make_shared<arrow::BinaryViewBuilder>());
140#endif
141 ++idx;
142 }
143 ++sidx;
144 }
145
146 std::shared_ptr<CCDBFetcherHelper> helper = std::make_shared<CCDBFetcherHelper>();
147 CCDBFetcherHelper::initialiseHelper(*helper, options);
148 std::unordered_map<std::string, int> bindings;
149 fillValidRoutes(*helper, spec.outputs, bindings);
150
151 return adaptStateless([schemas, bindings, helper, allbuilders](InputRecord& inputs, DataTakingContext& dtc, DataAllocator& allocator, TimingInfo& timingInfo, DataProcessingStats& stats) {
152 O2_SIGNPOST_ID_GENERATE(sid, ccdb);
153 O2_SIGNPOST_START(ccdb, sid, "fetchFromAnalysisCCDB", "Fetching CCDB objects for analysis%" PRIu64, (uint64_t)timingInfo.timeslice);
154 std::ranges::for_each(allbuilders, [](auto& builder) { builder.second->Reset(); });
155 for (auto i = 0U; i < schemas.size(); ++i) {
156 auto& schema = schemas[i];
157 std::vector<CCDBFetcherHelper::FetchOp> ops;
158 auto inputBinding = *schema->metadata()->Get("sourceTable");
159 auto inputMatcher = DataSpecUtils::fromString(*schema->metadata()->Get("sourceMatcher"));
160 auto outRouteDesc = *schema->metadata()->Get("outputRoute");
161 std::string outBinding = *schema->metadata()->Get("outputBinding");
162 O2_SIGNPOST_EVENT_EMIT_INFO(ccdb, sid, "fetchFromAnalysisCCDB",
163 "Fetching CCDB objects for %{public}s's columns with timestamps from %{public}s and putting them in route %{public}s",
164 outBinding.c_str(), inputBinding.c_str(), outRouteDesc.c_str());
165 auto table = inputs.get<TableConsumer>(inputMatcher)->asArrowTable();
166 // FIXME: make the fTimestamp column configurable.
167 auto timestampColumn = table->GetColumnByName("fTimestamp");
168 auto reserveSize = timestampColumn->length();
169 O2_SIGNPOST_EVENT_EMIT_INFO(ccdb, sid, "fetchFromAnalysisCCDB",
170 "There are %zu bindings available", bindings.size());
171 for (auto const& binding : bindings) {
172 O2_SIGNPOST_EVENT_EMIT_INFO(ccdb, sid, "fetchFromAnalysisCCDB",
173 "* %{public}s: %d",
174 binding.first.c_str(), binding.second);
175 }
176 int outputRouteIndex = bindings.at(outRouteDesc);
177 auto& spec = helper->routes[outputRouteIndex].matcher;
178 auto concrete = DataSpecUtils::asConcreteDataMatcher(spec);
179 Output output{concrete.origin, concrete.description, concrete.subSpec};
180 auto builders = allbuilders | std::views::filter([&i](auto const& builder) { return builder.first == i; });
181 unsigned int numBuilders = std::ranges::count_if(allbuilders, [&i](auto const& builder) { return builder.first == i; });
182 arrow::Status status;
183 std::ranges::for_each(builders, [&status, &reserveSize](auto& builder) {
184 if (reserveSize > builder.second->capacity()) {
185 status &= builder.second->Reserve(reserveSize - builder.second->capacity());
186 }
187 });
188 if (!status.ok()) {
189 throw framework::runtime_error_f("Failed to reserve arrays: ", status.ToString().c_str());
190 }
191
192 std::vector<DataAllocator::CacheId> lastIds(numBuilders, DataAllocator::CacheId{.value = -1, .handle = -1, .segment = -1});
193
194 for (auto ci = 0; ci < timestampColumn->num_chunks(); ++ci) {
195 std::shared_ptr<arrow::Array> chunk = timestampColumn->chunk(ci);
196 auto const* timestamps = chunk->data()->GetValuesSafe<size_t>(1);
197
198 for (int64_t ri = 0; ri < chunk->data()->length; ri++) {
199 ops.clear();
200 int64_t timestamp = timestamps[ri];
201 for (auto& field : schema->fields()) {
202 auto url = *field->metadata()->Get("url");
203 // Time to actually populate the blob
204 ops.push_back({
205 .spec = spec,
206 .url = url,
207 .timestamp = timestamp,
208 .runNumber = 1,
209 .runDependent = 0,
210 .queryRate = 0,
211 });
212 }
213 auto responses = CCDBFetcherHelper::populateCacheWith(helper, ops, timingInfo, dtc, allocator);
214 O2_SIGNPOST_START(ccdb, sid, "handlingResponses",
215 "Got %zu responses from server.",
216 responses.size());
217 if (numBuilders != responses.size()) {
218 LOGP(fatal, "Not enough responses (expected {}, found {})", numBuilders, responses.size());
219 }
220 arrow::Status result;
221
222 int bi = 0;
223 for (auto& builder : builders) {
224 auto& response = responses[bi];
225 auto& lastId = lastIds[bi];
226 if (response.id.value != lastId.value) {
227 lastId.value = response.id.value;
229 }
230#if (FAIRMQ_VERSION_DEC >= 111000)
231 result &= builder.second->Append();
232 auto* value_builder = dynamic_cast<arrow::Int64Builder*>(builder.second->value_builder());
233 result &= value_builder->Append(response.id.handle);
234 result &= value_builder->Append(response.id.segment);
235 result &= value_builder->Append(response.size);
236#else
237 char const* address = reinterpret_cast<char const*>(response.id.value);
238 result &= builder.second->Append(std::string_view(address, response.size));
239#endif
240 ++bi;
241 }
242 if (!result.ok()) {
243 LOGP(fatal, "Error adding results from CCDB");
244 }
245 O2_SIGNPOST_END(ccdb, sid, "handlingResponses", "Done processing responses");
246 }
247 }
248 arrow::ArrayVector arrays;
249 std::ranges::for_each(builders, [&arrays](auto& builder) { arrays.push_back(*builder.second->Finish()); });
250 auto outTable = arrow::Table::Make(schema, arrays);
251 allocator.adopt(output, outTable);
252 }
253
254 stats.updateStats({(int)ProcessingStatsId::CCDB_CACHE_FETCHED_BYTES, DataProcessingStats::Op::Set, (int64_t)helper->totalFetchedBytes});
255 stats.updateStats({(int)ProcessingStatsId::CCDB_CACHE_REQUESTED_BYTES, DataProcessingStats::Op::Set, (int64_t)helper->totalRequestedBytes});
256 O2_SIGNPOST_END(ccdb, sid, "fetchFromAnalysisCCDB", "Fetching CCDB objects");
257 });
258 });
259}
260
261} // namespace o2::framework
std::string binding
std::string url
std::shared_ptr< arrow::Schema > schema
std::vector< std::shared_ptr< arrow::Field > > fields
int32_t i
void output(const std::map< std::string, ChannelStat > &channels)
Definition rawdump.cxx:197
#define O2_DECLARE_DYNAMIC_LOG(name)
Definition Signpost.h:490
#define O2_SIGNPOST_EVENT_EMIT_INFO(log, id, name, format,...)
Definition Signpost.h:532
#define O2_SIGNPOST_END(log, id, name, format,...)
Definition Signpost.h:609
#define O2_SIGNPOST_ID_GENERATE(name, log)
Definition Signpost.h:507
#define O2_SIGNPOST_START(log, id, name, format,...)
Definition Signpost.h:603
void adopt(const Output &spec, std::string *)
void adoptFromCache(Output const &spec, CacheId id, header::SerializationMethod method=header::gSerializationMethodNone)
Adopt an already cached message, using an already provided CacheId.
ServiceRegistryRef services()
Definition InitContext.h:34
The input API of the Data Processing Layer This class holds the inputs which are valid for processing...
decltype(auto) get(R binding, int part=0) const
const GLfloat * m
Definition glcorearb.h:4066
GLuint GLuint64EXT address
Definition glcorearb.h:5846
GLuint64EXT * result
Definition glcorearb.h:5662
GLsizeiptr size
Definition glcorearb.h:659
GLuint const GLchar * name
Definition glcorearb.h:781
const GLuint * arrays
Definition glcorearb.h:1314
constexpr framework::ConcreteDataMatcher matcher()
Definition ASoA.h:390
Defining ITS Vertex explicitly as messageable.
Definition Cartesian.h:288
AlgorithmSpec::ProcessCallback adaptStateless(LAMBDA l)
RuntimeErrorRef runtime_error_f(const char *,...)
AlgorithmSpec::InitCallback adaptStateful(LAMBDA l)
constexpr o2::header::SerializationMethod gSerializationMethodCCDB
Definition DataHeader.h:329
std::shared_ptr< arrow::DataType > asArrowDataType(int list_size=1)
Definition ArrowTypes.h:174
static AlgorithmSpec fetchFromCCDB(ConfigContext const &)
static auto populateCacheWith(std::shared_ptr< CCDBFetcherHelper > const &helper, std::vector< FetchOp > const &ops, TimingInfo &timingInfo, DataTakingContext &dtc, DataAllocator &allocator) -> std::vector< Response >
static void initialiseHelper(CCDBFetcherHelper &helper, ConfigParamRegistry const &options)
static bool hasOption(const std::vector< ConfigParamSpec > &specs, const std::string &optName)
Check if option is defined.
Helper struct to hold statistics about the data processing happening.
static InputSpec fromMetadataString(std::string s)
Create an InputSpec from metadata string.
static std::string describe(InputSpec const &spec)
static ConcreteDataMatcher asConcreteDataMatcher(InputSpec const &input)
static ConcreteDataMatcher fromString(std::string s)
Create a concrete data matcher from serialized string.
std::vector< ConfigParamSpec > options
Definition DeviceSpec.h:57
std::vector< OutputRoute > outputs
Definition DeviceSpec.h:63
std::variant< ConcreteDataMatcher, data_matcher::DataDescriptorMatcher > matcher
The actual matcher for the input spec.
Definition InputSpec.h:70
header::DataOrigin origin
Definition Output.h:28