Project
Loading...
Searching...
No Matches
CCDBFetcherHelper.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#include "CCDBFetcherHelper.h"
12#include "CCDBHelpers.h"
14#include "Framework/Signpost.h"
17#include <TError.h>
18#include <TMemFile.h>
19
21
22namespace o2::framework
23{
24
26{
27 // find the first = sign in the string. If present drop everything after it
28 // and between it and the previous /.
29 auto pos = path.find('=');
30 if (pos == std::string::npos) {
31 auto entry = remappings.find(path);
32 return apis[entry == remappings.end() ? "" : entry->second];
33 }
34 auto pos2 = path.rfind('/', pos);
35 if (pos2 == std::string::npos || pos2 == pos - 1 || pos2 == 0) {
36 throw runtime_error_f("Malformed path %s", path.c_str());
37 }
38 auto entry = remappings.find(path.substr(0, pos2));
39 return apis[entry == remappings.end() ? "" : entry->second];
40}
41
42namespace
43{
44bool isOnlineRun(DataTakingContext const& dtc)
45{
47}
48} // namespace
49
51{
52 auto defHost = options.get<std::string>("condition-backend");
53 auto checkRate = options.get<int>("condition-tf-per-query");
54 auto checkMult = options.get<int>("condition-tf-per-query-multiplier");
55 helper.useTFSlice = options.get<int>("condition-use-slice-for-prescaling");
56 helper.timeToleranceMS = options.get<int64_t>("condition-time-tolerance");
57 helper.queryPeriodGlo = checkRate > 0 ? checkRate : std::numeric_limits<int>::max();
58 helper.queryPeriodFactor = checkMult == 0 ? 1 : checkMult;
59 std::string extraCond{};
60 if (helper.useTFSlice) {
61 extraCond = ". Use TFSlice";
62 if (helper.useTFSlice > 0) {
63 extraCond += fmt::format(" + max TFcounter jump <= {}", helper.useTFSlice);
64 }
65 }
66 LOGP(info, "CCDB Backend at: {}, validity check for every {} TF{}{}", defHost, helper.queryPeriodGlo,
67 helper.queryPeriodFactor == 1 ? std::string{} : (helper.queryPeriodFactor > 0 ? fmt::format(", (query for high-rate objects downscaled by {})", helper.queryPeriodFactor) : fmt::format(", (query downscaled as TFcounter%{})", -helper.queryPeriodFactor)),
68 extraCond);
69 LOGP(info, "Hook to enable signposts for CCDB messages at {}", (void*)&private_o2_log_ccdb->stacktrace);
70 auto remapString = options.get<std::string>("condition-remap");
71 ParserResult result = parseRemappings(remapString.c_str());
72 if (!result.error.empty()) {
73 throw runtime_error_f("Error while parsing remapping string %s", result.error.c_str());
74 }
75 helper.remappings = result.remappings;
76 helper.apis[""].init(defHost); // default backend
77 LOGP(info, "Initialised default CCDB host {}", defHost);
78 //
79 for (auto& entry : helper.remappings) { // init api instances for every host seen in the remapping
80 if (helper.apis.find(entry.second) == helper.apis.end()) {
81 helper.apis[entry.second].init(entry.second);
82 LOGP(info, "Initialised custom CCDB host {}", entry.second);
83 }
84 LOGP(info, "{} is remapped to {}", entry.first, entry.second);
85 }
86 helper.createdNotBefore = std::to_string(options.get<int64_t>("condition-not-before"));
87 helper.createdNotAfter = std::to_string(options.get<int64_t>("condition-not-after"));
88}
89
91{
92 std::unordered_map<std::string, std::string> remappings;
93 std::string currentUrl = "";
94
95 enum ParsingStates {
96 IN_BEGIN,
97 IN_BEGIN_URL,
98 IN_BEGIN_TARGET,
99 IN_END_TARGET,
100 IN_END_URL
101 };
102 ParsingStates state = IN_BEGIN;
103
104 while (true) {
105 switch (state) {
106 case IN_BEGIN: {
107 if (*str == 0) {
108 return {remappings, ""};
109 }
110 state = IN_BEGIN_URL;
111 }
112 case IN_BEGIN_URL: {
113 if ((strncmp("http://", str, 7) != 0) && (strncmp("https://", str, 8) != 0 && (strncmp("file://", str, 7) != 0))) {
114 return {remappings, "URL should start with either http:// or https:// or file://"};
115 }
116 state = IN_END_URL;
117 } break;
118 case IN_END_URL: {
119 char const* c = strchr(str, '=');
120 if (c == nullptr) {
121 return {remappings, "Expecting at least one target path, missing `='?"};
122 }
123 if ((c - str) == 0) {
124 return {remappings, "Empty url"};
125 }
126 currentUrl = std::string_view(str, c - str);
127 state = IN_BEGIN_TARGET;
128 str = c + 1;
129 } break;
130 case IN_BEGIN_TARGET: {
131 if (*str == 0) {
132 return {remappings, "Empty target"};
133 }
134 state = IN_END_TARGET;
135 } break;
136 case IN_END_TARGET: {
137 char const* c = strpbrk(str, ",;");
138 if (c == nullptr) {
139 if (remappings.count(str)) {
140 return {remappings, fmt::format("Path {} requested more than once.", str)};
141 }
142 remappings[std::string(str)] = currentUrl;
143 return {remappings, ""};
144 }
145 if ((c - str) == 0) {
146 return {remappings, "Empty target"};
147 }
148 auto key = std::string(str, c - str);
149 if (remappings.count(str)) {
150 return {remappings, fmt::format("Path {} requested more than once.", key)};
151 }
152 remappings[key] = currentUrl;
153 if (*c == ';') {
154 state = IN_BEGIN_URL;
155 } else {
156 state = IN_BEGIN_TARGET;
157 }
158 str = c + 1;
159 } break;
160 }
161 }
162}
163
164auto CCDBFetcherHelper::populateCacheWith(std::shared_ptr<CCDBFetcherHelper> const& helper,
165 std::vector<CCDBFetcherHelper::FetchOp> const& ops,
166 TimingInfo& timingInfo,
168 DataAllocator& allocator) -> std::vector<CCDBFetcherHelper::Response>
169{
170 // We use the timeslice, so that we hook into the same interval as the rest of the
171 // callback.
172 static bool isOnline = isOnlineRun(dtc);
173
174 auto sid = _o2_signpost_id_t{(int64_t)timingInfo.timeslice};
175 O2_SIGNPOST_START(ccdb, sid, "populateCacheWith", "Starting to populate cache with CCDB objects");
176 std::vector<Response> responses;
177 for (auto const& op : ops) {
178 int64_t timestampToUse = op.timestamp;
179 O2_SIGNPOST_EVENT_EMIT(ccdb, sid, "populateCacheWith", "Fetching object for route %{public}s", DataSpecUtils::describe(op.spec).data());
180 auto concrete = DataSpecUtils::asConcreteDataMatcher(op.spec);
181 Output output{concrete.origin, concrete.description, concrete.subSpec};
182 std::map<std::string, std::string> metadata;
183 std::map<std::string, std::string> headers;
184 std::string path = op.url;
185 std::string etag = "";
186 int chRate = helper->queryPeriodGlo;
187 bool checkValidity = false;
188 if (op.runDependent > 0) {
189 if (op.runDependent == 1) {
190 metadata["runNumber"] = std::format("{}", op.runNumber);
191 } else if (op.runDependent == 2) {
192 timestampToUse = op.runNumber;
193 } else {
194 LOGP(fatal, "Undefined ccdb-run-dependent option {} for spec {}/{}/{}", op.runDependent,
195 concrete.origin.as<std::string>(), concrete.description.as<std::string>(), int(concrete.subSpec));
196 }
197 }
198 for (auto const& m : op.metadata) {
199 O2_SIGNPOST_EVENT_EMIT(ccdb, sid, "populateCacheWith", "Adding metadata %{public}s: %{public}s to the request", m.key.data(), m.value.data());
200 metadata[m.key] = m.value;
201 }
202 if (op.queryRate != 0) {
203 chRate = op.queryRate * helper->queryPeriodFactor;
204 }
205
206 const auto url2uuid = helper->mapURL2UUID.find(path);
207 if (url2uuid != helper->mapURL2UUID.end()) {
208 etag = url2uuid->second.etag;
209 // We check validity every chRate timeslices or if the cache is expired
210 uint64_t validUntil = url2uuid->second.cacheValidUntil;
211 // When the cache was populated. If the cache was populated after the timestamp, we need to check validity.
212 uint64_t cachePopulatedAt = url2uuid->second.cachePopulatedAt;
213 // If timestamp is before the time the element was cached or after the claimed validity, we need to check validity, again
214 // when online.
215 bool cacheExpired = (validUntil <= (uint64_t)timestampToUse) || ((uint64_t)op.timestamp < cachePopulatedAt);
216 if (isOnline || cacheExpired) {
217 if (!helper->useTFSlice) {
218 checkValidity = chRate > 0 ? (std::abs(int(timingInfo.tfCounter - url2uuid->second.lastCheckedTF)) >= chRate) : (timingInfo.tfCounter % -chRate) == 0;
219 } else {
220 checkValidity = chRate > 0 ? (std::abs(int(timingInfo.timeslice - url2uuid->second.lastCheckedSlice)) >= chRate) : (timingInfo.timeslice % -chRate) == 0;
221 if (!checkValidity && helper->useTFSlice > std::abs(chRate)) { // make sure the interval is tolerated unless the check rate itself is too large
222 checkValidity = std::abs(int(timingInfo.tfCounter) - url2uuid->second.lastCheckedTF) > helper->useTFSlice;
223 }
224 }
225 }
226 } else {
227 checkValidity = true; // never skip check if the cache is empty
228 }
229
230 O2_SIGNPOST_EVENT_EMIT(ccdb, sid, "populateCacheWith", "checkValidity is %{public}s for tf%{public}s %zu of %{public}s", checkValidity ? "true" : "false", helper->useTFSlice ? "ID" : "Slice", helper->useTFSlice ? timingInfo.timeslice : timingInfo.tfCounter, path.data());
231
232 const auto& api = helper->getAPI(path);
233 if (checkValidity && (!api.isSnapshotMode() || etag.empty())) { // in the snapshot mode the object needs to be fetched only once
234 auto&& v = allocator.makeVector<char>(output);
235 LOGP(detail, "Loading {} for timestamp {}", path, timestampToUse);
236 api.loadFileToMemory(v, path, metadata, timestampToUse, &headers, etag, helper->createdNotAfter, helper->createdNotBefore);
237 if ((headers.count("Error") != 0) || (etag.empty() && v.empty())) {
238 LOGP(fatal, "Unable to find CCDB object {}/{}", path, timestampToUse);
239 // FIXME: I should send a dummy message.
240 continue;
241 }
242 // printing in case we find a default entry
243 if (headers.find("default") != headers.end()) {
244 LOGP(detail, "******** Default entry used for {} ********", path);
245 }
246 helper->mapURL2UUID[path].lastCheckedTF = timingInfo.tfCounter;
247 helper->mapURL2UUID[path].lastCheckedSlice = timingInfo.timeslice;
248 if (etag.empty()) {
249 helper->mapURL2UUID[path].etag = headers["ETag"]; // update uuid
250 helper->mapURL2UUID[path].cachePopulatedAt = timestampToUse;
251 helper->mapURL2UUID[path].cacheMiss++;
252 helper->mapURL2UUID[path].size = v.size();
253 helper->mapURL2UUID[path].minSize = std::min(v.size(), helper->mapURL2UUID[path].minSize);
254 helper->mapURL2UUID[path].maxSize = std::max(v.size(), helper->mapURL2UUID[path].maxSize);
255 auto size = v.size();
256 helper->totalFetchedBytes += size;
257 helper->totalRequestedBytes += size;
258 api.appendFlatHeader(v, headers);
260 helper->mapURL2DPLCache[path] = cacheId;
261 responses.emplace_back(Response{.id = cacheId, .size = size, .request = nullptr});
262 O2_SIGNPOST_EVENT_EMIT(ccdb, sid, "populateCacheWith", "Caching %{public}s for %{public}s (DPL id %" PRIu64 ", size %zu)", path.data(), headers["ETag"].data(), cacheId.value, size);
263 continue;
264 }
265 if (v.size()) { // but should be overridden by fresh object
266 helper->mapURL2UUID[path].etag = headers["ETag"]; // update uuid
267 helper->mapURL2UUID[path].cachePopulatedAt = timestampToUse;
268 helper->mapURL2UUID[path].cacheValidUntil = headers["Cache-Valid-Until"].empty() ? 0 : std::stoul(headers["Cache-Valid-Until"]);
269 helper->mapURL2UUID[path].cacheMiss++;
270 helper->mapURL2UUID[path].size = v.size();
271 helper->mapURL2UUID[path].minSize = std::min(v.size(), helper->mapURL2UUID[path].minSize);
272 helper->mapURL2UUID[path].maxSize = std::max(v.size(), helper->mapURL2UUID[path].maxSize);
273 auto size = v.size();
274 helper->totalFetchedBytes += size;
275 helper->totalRequestedBytes += size;
276 api.appendFlatHeader(v, headers);
278 helper->mapURL2DPLCache[path] = cacheId;
279 responses.emplace_back(Response{.id = cacheId, .size = size, .request = nullptr});
280 O2_SIGNPOST_EVENT_EMIT(ccdb, sid, "populateCacheWith", "Caching %{public}s for %{public}s (DPL id %" PRIu64 ")", path.data(), headers["ETag"].data(), cacheId.value);
281 continue;
282 } else {
283 // Only once the etag is actually used, we get the information on how long the object is valid
284 helper->mapURL2UUID[path].cacheValidUntil = headers["Cache-Valid-Until"].empty() ? 0 : std::stoul(headers["Cache-Valid-Until"]);
285 }
286 }
287 // cached object is fine
288 auto cacheId = helper->mapURL2DPLCache[path];
289 O2_SIGNPOST_EVENT_EMIT(ccdb, sid, "populateCacheWith", "Reusing %{public}s for %{public}s (DPL id %" PRIu64 ")", path.data(), headers["ETag"].data(), cacheId.value);
290 helper->mapURL2UUID[path].cacheHit++;
291 responses.emplace_back(Response{.id = cacheId, .size = helper->mapURL2UUID[path].size, .request = nullptr});
292 // allocator.adoptFromCache(output, cacheId, header::gSerializationMethodCCDB);
293 // the outputBuffer was not used, can we destroy it?
294 }
295 O2_SIGNPOST_END(ccdb, sid, "populateCacheWith", "Finished populating cache with CCDB objects");
296 return responses;
297};
298
299} // namespace o2::framework
size_t cachePopulatedAt
std::string etag
uint32_t op
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
SurfaceTrackState state
void output(const std::map< std::string, ChannelStat > &channels)
Definition rawdump.cxx:197
uint16_t pos
Definition RawData.h:3
uint32_t c
Definition RawData.h:2
#define O2_DECLARE_DYNAMIC_LOG(name)
Definition Signpost.h:490
#define O2_SIGNPOST_END(log, id, name, format,...)
Definition Signpost.h:609
#define O2_SIGNPOST_EVENT_EMIT(log, id, name, format,...)
Definition Signpost.h:523
#define O2_SIGNPOST_START(log, id, name, format,...)
Definition Signpost.h:603
StringRef key
@ CacheOnly
Cache the message without sending it. Use adoptFromCache to send it.
const GLfloat * m
Definition glcorearb.h:4066
GLuint64EXT * result
Definition glcorearb.h:5662
GLsizeiptr size
Definition glcorearb.h:659
const GLdouble * v
Definition glcorearb.h:832
GLsizei const GLchar *const * path
Definition glcorearb.h:3591
Defining ITS Vertex explicitly as messageable.
Definition Cartesian.h:288
bool isOnlineRun(DataTakingContext const &dtc)
RuntimeErrorRef runtime_error_f(const char *,...)
constexpr o2::header::SerializationMethod gSerializationMethodCCDB
Definition DataHeader.h:332
std::string to_string(gsl::span< T, Size > span)
Definition common.h:52
o2::ccdb::CcdbApi & getAPI(const std::string &path)
std::unordered_map< std::string, std::string > remappings
static auto populateCacheWith(std::shared_ptr< CCDBFetcherHelper > const &helper, std::vector< FetchOp > const &ops, TimingInfo &timingInfo, DataTakingContext &dtc, DataAllocator &allocator) -> std::vector< Response >
std::unordered_map< std::string, o2::ccdb::CcdbApi > apis
static void initialiseHelper(CCDBFetcherHelper &helper, ConfigParamRegistry const &options)
static ParserResult parseRemappings(char const *)
static DataAllocator::CacheId adoptAndReplaceCachedMessage(DataAllocator &allocator, std::unordered_map< std::string, DataAllocator::CacheId > const &cache, std::string const &path, Output const &output, o2::pmr::vector< char > &&v, o2::header::SerializationMethod method, DataAllocator::CacheStrategy strategy=DataAllocator::CacheStrategy::Always)
static std::string describe(InputSpec const &spec)
static ConcreteDataMatcher asConcreteDataMatcher(InputSpec const &input)
DeploymentMode deploymentMode
Where we thing this is running.
header::DataOrigin origin
Definition Output.h:28
const std::string str