Project
Loading...
Searching...
No Matches
AODJAlienReaderHelpers.cxx
Go to the documentation of this file.
1// Copyright 2019-2020 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
13#include <algorithm>
14#include <charconv>
15#include <cctype>
16#include <cstdlib>
17#include <exception>
18#include <memory>
19#include <ranges>
20#include <string>
21#include <string_view>
22#include <vector>
37#include "Framework/Signpost.h"
40#include "DataInputDirector.h"
43#include "Framework/Logger.h"
44
45#if __has_include(<TJAlienFile.h>)
46#include <TJAlienFile.h>
47#endif
48#include <TGrid.h>
49#include <TFile.h>
50#include <TTreeCache.h>
51#include <TSystem.h>
52
53#include <arrow/ipc/reader.h>
54#include <arrow/ipc/writer.h>
55#include <arrow/io/interfaces.h>
56#include <arrow/table.h>
57#include <arrow/util/key_value_metadata.h>
58#include <arrow/dataset/dataset.h>
59#include <arrow/dataset/file_base.h>
60
61using namespace o2;
62using namespace o2::aod;
63
65
68 uint64_t startTime;
69 uint64_t lastTime;
70 double runTime;
71 uint64_t runTimeLimit;
72
73 RuntimeWatchdog(Long64_t limit)
74 {
76 startTime = uv_hrtime();
78 runTime = 0.;
79 runTimeLimit = limit;
80 }
81
82 bool update()
83 {
85 if (runTimeLimit <= 0) {
86 return true;
87 }
88
89 auto nowTime = uv_hrtime();
90
91 // time spent to process the time frame
92 double time_spent = numberTimeFrames < 1 ? (double)(nowTime - lastTime) / 1.E9 : 0.;
93 runTime += time_spent;
94 lastTime = nowTime;
95
96 return ((double)(lastTime - startTime) / 1.E9 + runTime / (numberTimeFrames + 1)) < runTimeLimit;
97 }
98
99 void printOut()
100 {
101 LOGP(info, "RuntimeWatchdog");
102 LOGP(info, " run time limit: {}", runTimeLimit);
103 LOGP(info, " number of time frames: {}", numberTimeFrames);
104 LOGP(info, " estimated run time per time frame: {}", (numberTimeFrames >= 0) ? runTime / (numberTimeFrames + 1) : 0.);
105 LOGP(info, " estimated total run time: {}", (double)(lastTime - startTime) / 1.E9 + ((numberTimeFrames >= 0) ? runTime / (numberTimeFrames + 1) : 0.));
106 }
107};
108
109using o2::monitoring::Metric;
110using o2::monitoring::Monitoring;
111using o2::monitoring::tags::Key;
112using o2::monitoring::tags::Value;
113
115{
116static bool shouldSkipInvalidReads()
117{
118 auto const* envValue = getenv("DPL_AOD_READER_SKIP_INVALID");
119 if (envValue == nullptr) {
120 return false;
121 }
122
123 std::string value{envValue};
124 std::ranges::transform(value, value.begin(), [](unsigned char c) { return std::tolower(c); });
125 return !value.empty() && value != "0" && value != "false";
126}
127
128static std::string describeException(std::exception const& exception)
129{
130 std::string description{exception.what()};
131 try {
132 std::rethrow_if_nested(exception);
133 } catch (std::exception const& nested) {
134 description += ": " + describeException(nested);
135 } catch (...) {
136 description += ": unknown exception";
137 }
138 return description;
139}
140
142{
143 // aod-parent-base-path-replacement is now a workflow option, so it needs to be
144 // retrieved from the ConfigContext. This is because we do not allow workflow options
145 // to change over start-stop-start because they can affect the topology generation.
146 std::string parentFileReplacement;
147 if (ctx.options().isSet("aod-parent-base-path-replacement")) {
148 parentFileReplacement = ctx.options().get<std::string>("aod-parent-base-path-replacement");
149 }
150 int parentAccessLevel = 0;
151 if (ctx.options().isSet("aod-parent-access-level")) {
152 parentAccessLevel = ctx.options().get<int>("aod-parent-access-level");
153 }
154 std::vector<std::pair<std::string, int>> originLevelMapping;
155 if (ctx.options().isSet("aod-origin-level-mapping")) {
156 auto originLevelMappingStr = ctx.options().get<std::string>("aod-origin-level-mapping");
157 for (auto pairRange : originLevelMappingStr | std::views::split(',')) {
158 std::string_view pair{pairRange.begin(), pairRange.end()};
159 auto colonPos = pair.find(':');
160 if (colonPos == std::string_view::npos) {
161 LOGP(fatal, "Badly formatted aod-origin-level-mapping entry: \"{}\"", pair);
162 continue;
163 }
164 std::string key(pair.substr(0, colonPos));
165 std::string_view valueStr = pair.substr(colonPos + 1);
166 int value{};
167 auto [ptr, ec] = std::from_chars(valueStr.data(), valueStr.data() + valueStr.size(), value);
168 if (ec == std::errc{}) {
169 originLevelMapping.emplace_back(std::move(key), value);
170 } else {
171 LOGP(fatal, "Unable to parse level in aod-origin-level-mapping entry: \"{}\"", pair);
172 }
173 }
174 }
175 auto callback = AlgorithmSpec{adaptStateful([parentFileReplacement, parentAccessLevel, originLevelMapping](ConfigParamRegistry const& options,
176 DeviceSpec const& spec,
177 Monitoring& monitoring,
178 DataProcessingStats& stats) {
179 // FIXME: not actually needed, since data processing stats can specify that we should
180 // send the initial value.
181 stats.updateStats({static_cast<short>(ProcessingStatsId::ARROW_BYTES_CREATED), DataProcessingStats::Op::Set, 0});
182 stats.updateStats({static_cast<short>(ProcessingStatsId::ARROW_MESSAGES_CREATED), DataProcessingStats::Op::Set, 0});
183 stats.updateStats({static_cast<short>(ProcessingStatsId::ARROW_BYTES_DESTROYED), DataProcessingStats::Op::Set, 0});
184 stats.updateStats({static_cast<short>(ProcessingStatsId::ARROW_MESSAGES_DESTROYED), DataProcessingStats::Op::Set, 0});
185 stats.updateStats({static_cast<short>(ProcessingStatsId::ARROW_BYTES_EXPIRED), DataProcessingStats::Op::Set, 0});
186 stats.updateStats({static_cast<short>(ProcessingStatsId::CONSUMED_TIMEFRAMES), DataProcessingStats::Op::Set, 0});
187
188 if (!options.isSet("aod-file-private")) {
189 LOGP(fatal, "No input file defined!");
190 throw std::runtime_error("Processing is stopped!");
191 }
192
193 auto filename = options.get<std::string>("aod-file-private");
194
195 auto maxRate = options.get<float>("aod-max-io-rate");
196
197 // create a DataInputDirector
198 auto didir = std::make_shared<DataInputDirector>(std::vector<std::string>{filename}, DataInputDirectorContext{&monitoring, parentAccessLevel, parentFileReplacement, originLevelMapping});
199 if (options.isSet("aod-reader-json")) {
200 auto jsonFile = options.get<std::string>("aod-reader-json");
201 if (!didir->readJson(jsonFile)) {
202 LOGP(error, "Check the JSON document! Can not be properly parsed!");
203 }
204 }
205
206 // get the run time watchdog
207 auto* watchdog = new RuntimeWatchdog(options.get<int64_t>("time-limit"));
208
209 // selected the TFN input and
210 // create list of requested tables
211 bool reportTFN = false;
212 bool reportTFFileName = false;
213 header::DataHeader TFNumberHeader;
214 header::DataHeader TFFileNameHeader;
215 std::vector<OutputRoute> requestedTables;
216 std::vector<OutputRoute> routes(spec.outputs);
217 for (auto route : routes) {
218 if (DataSpecUtils::partialMatch(route.matcher, header::DataOrigin("TFN"))) {
219 auto concrete = DataSpecUtils::asConcreteDataMatcher(route.matcher);
220 TFNumberHeader = header::DataHeader(concrete.description, concrete.origin, concrete.subSpec);
221 reportTFN = true;
222 } else if (DataSpecUtils::partialMatch(route.matcher, header::DataOrigin("TFF"))) {
223 auto concrete = DataSpecUtils::asConcreteDataMatcher(route.matcher);
224 TFFileNameHeader = header::DataHeader(concrete.description, concrete.origin, concrete.subSpec);
225 reportTFFileName = true;
226 } else {
227 requestedTables.emplace_back(route);
228 }
229 }
230 int level = originLevelMapping.empty() ? -1 : 0;
231 auto fileCounter = std::make_shared<int>(0);
232 auto numTF = std::make_shared<int>(-1);
233 bool const skipInvalidReads = shouldSkipInvalidReads();
234 return adaptStateless([TFNumberHeader,
235 TFFileNameHeader,
236 requestedTables,
237 fileCounter,
238 numTF,
239 watchdog,
240 maxRate,
241 skipInvalidReads,
242 didir, reportTFN, reportTFFileName, level](Monitoring& monitoring, DataAllocator& outputs, ControlService& control, DeviceSpec const& device, DataProcessingStats& dpstats, ArrowContext& arrowContext, MessageContext& messageContext, StringContext& stringContext) {
243 // Each parallel reader device.inputTimesliceId reads the files fileCounter*device.maxInputTimeslices+device.inputTimesliceId
244 // the TF to read is numTF
245 assert(device.inputTimesliceId < device.maxInputTimeslices);
246 int fcnt = (*fileCounter * device.maxInputTimeslices) + device.inputTimesliceId;
247 int ntf = *numTF + 1;
248 static int currentFileCounter = -1;
249 static int filesProcessed = 0;
250 if (currentFileCounter != *fileCounter) {
251 currentFileCounter = *fileCounter;
252 monitoring.send(Metric{(uint64_t)++filesProcessed, "files-opened"}.addTag(Key::Subsystem, monitoring::tags::Value::DPL));
253 }
254
255 // loop over requested tables
256 static size_t totalSizeUncompressed = 0;
257 static size_t totalSizeCompressed = 0;
258 static uint64_t totalDFSent = 0;
259 static uint64_t totalInvalidReadSkipped = 0;
260
261 // check if RuntimeLimit is reached
262 if (!watchdog->update()) {
263 LOGP(info, "Run time exceeds run time limit of {} seconds. Exiting gracefully...", watchdog->runTimeLimit);
264 LOGP(info, "Stopping reader {} after time frame {}.", device.inputTimesliceId, watchdog->numberTimeFrames - 1);
265 didir->closeInputFiles();
266 monitoring.flushBuffer();
267 control.endOfStream();
269 return;
270 }
271
272 int64_t startTime = uv_hrtime();
273 int64_t startSize = totalSizeCompressed;
274 auto skipInvalidRead = [&](ConcreteDataMatcher const& concrete, InvalidAODReadError const& e) {
275 auto skippedTimeframes = ++totalInvalidReadSkipped;
276 LOGP(error, "Invalid AOD read for table {}: fileCounter {}, timeFrame {}. Skipping timeframe (skipped timeframes: {}). Reason: {}",
277 concrete.origin.as<std::string>(), fcnt, ntf, skippedTimeframes, describeException(e));
278 didir->markTimeFrameSkipped(header::DataHeader(concrete.description, concrete.origin, concrete.subSpec), ntf);
279 arrowContext.clear();
280 messageContext.discard();
281 stringContext.clear();
283 *fileCounter = (fcnt - device.inputTimesliceId) / device.maxInputTimeslices;
284 *numTF = ntf;
285 };
286 enum class TFReaderState {
287 READ_FIRST_TABLE,
288 READ_FIRST_TABLE_FROM_NEXT_FILE,
289 READ_NEXT_TABLE,
290 TRY_NEXT_FILE,
291 TIMEFRAME_READ,
292 INVALID_TIMEFRAME,
293 };
294 auto readState = TFReaderState::READ_FIRST_TABLE;
295 [[maybe_unused]] auto stateName = [](TFReaderState state) -> char const* {
296 switch (state) {
297 case TFReaderState::READ_FIRST_TABLE:
298 return "READ_FIRST_TABLE";
299 case TFReaderState::READ_FIRST_TABLE_FROM_NEXT_FILE:
300 return "READ_FIRST_TABLE_FROM_NEXT_FILE";
301 case TFReaderState::READ_NEXT_TABLE:
302 return "READ_NEXT_TABLE";
303 case TFReaderState::TRY_NEXT_FILE:
304 return "TRY_NEXT_FILE";
305 case TFReaderState::TIMEFRAME_READ:
306 return "TIMEFRAME_READ";
307 case TFReaderState::INVALID_TIMEFRAME:
308 return "INVALID_TIMEFRAME";
309 }
310 return "UNKNOWN";
311 };
312 O2_SIGNPOST_ID_FROM_POINTER(readerStateId, aod_reader, &readState);
313 auto transitionTo = [&](TFReaderState nextState) {
314 O2_SIGNPOST_EVENT_EMIT(aod_reader, readerStateId, "state transition",
315 "%{public}s -> %{public}s (fileCounter %d, timeFrame %d)",
316 stateName(readState), stateName(nextState), fcnt, ntf);
317 readState = nextState;
318 };
319 size_t routeIndex = 0;
320 auto reportTimeframe = [&didir, &fcnt, &ntf, &outputs, &TFNumberHeader, &TFFileNameHeader, reportTFN, reportTFFileName](header::DataHeader const& dh) {
321 if (reportTFN) {
322 // TF number
323 auto timeFrameNumber = didir->getTimeFrameNumber(dh, fcnt, ntf);
324 auto o = Output(TFNumberHeader);
325 outputs.make<uint64_t>(o) = timeFrameNumber;
326 }
327
328 if (reportTFFileName) {
329 // Origin file name for derived output map
330 auto o2 = Output(TFFileNameHeader);
331 auto fileAndFolder = didir->getFileFolder(dh, fcnt, ntf);
332 auto rootFS = std::dynamic_pointer_cast<TFileFileSystem>(fileAndFolder.filesystem());
333 auto* f = dynamic_cast<TFile*>(rootFS->GetFile());
334 std::string currentFilename(f->GetFile()->GetName());
335 if (strcmp(f->GetEndpointUrl()->GetProtocol(), "file") == 0 && f->GetEndpointUrl()->GetFile()[0] != '/') {
336 // This is not an absolute local path. Make it absolute.
337 static std::string pwd = gSystem->pwd() + std::string("/");
338 currentFilename = pwd + std::string(f->GetName());
339 }
340 outputs.make<std::string>(o2) = currentFilename;
341 }
342 };
343 auto tryReadTable = [&device, &didir, &fcnt, &ntf, &outputs, &reportTimeframe, &requestedTables, &routeIndex, &skipInvalidRead, skipInvalidReads](TFReaderState currentState) -> TFReaderState {
344 while (routeIndex < requestedTables.size() &&
345 (device.inputTimesliceId % requestedTables[routeIndex].maxTimeslices) != requestedTables[routeIndex].timeslice) {
346 ++routeIndex;
347 }
348 if (routeIndex == requestedTables.size()) {
349 return TFReaderState::TIMEFRAME_READ;
350 }
351
352 auto& route = requestedTables[routeIndex];
353 auto concrete = DataSpecUtils::asConcreteDataMatcher(route.matcher);
354 auto dh = header::DataHeader(concrete.description, concrete.origin, concrete.subSpec);
355 bool wasAOD = std::ranges::any_of(route.matcher.metadata, [](ConfigParamSpec const& p) { return p.name.starts_with("aod-origin-replaced"); });
356
357 try {
358 if (!didir->readTree(outputs, dh, fcnt, ntf, totalSizeCompressed, totalSizeUncompressed, wasAOD)) {
359 return TFReaderState::TRY_NEXT_FILE;
360 }
361 } catch (InvalidAODReadError const& e) {
362 if (!skipInvalidReads) {
363 throw;
364 }
365 skipInvalidRead(concrete, e);
366 return TFReaderState::INVALID_TIMEFRAME;
367 }
368
369 if (currentState == TFReaderState::READ_FIRST_TABLE || currentState == TFReaderState::READ_FIRST_TABLE_FROM_NEXT_FILE) {
370 reportTimeframe(dh);
371 }
372 ++routeIndex;
373 return TFReaderState::READ_NEXT_TABLE;
374 };
375 while (readState != TFReaderState::TIMEFRAME_READ) {
376 switch (readState) {
377 case TFReaderState::READ_FIRST_TABLE:
378 transitionTo(tryReadTable(readState));
379 break;
380 case TFReaderState::READ_FIRST_TABLE_FROM_NEXT_FILE:
381 case TFReaderState::READ_NEXT_TABLE:
382 transitionTo(tryReadTable(readState));
383 if (readState == TFReaderState::TRY_NEXT_FILE) {
384 // Once a file has been selected, every requested table must exist.
385 auto concrete = DataSpecUtils::asConcreteDataMatcher(requestedTables[routeIndex].matcher);
386 LOGP(fatal, "Can not retrieve tree for table {}: fileCounter {}, timeFrame {}", concrete.origin.as<std::string>(), fcnt, ntf);
387 throw std::runtime_error("Processing is stopped!");
388 }
389 break;
390 case TFReaderState::TRY_NEXT_FILE:
391 fcnt += device.maxInputTimeslices;
392 if (didir->atEnd(fcnt)) {
393 LOGP(info, "No input files left to read for reader {}!", device.inputTimesliceId);
394 didir->closeInputFiles();
395 monitoring.flushBuffer();
396 control.endOfStream();
398 return;
399 }
400 ntf = 0;
401 routeIndex = 0;
402 transitionTo(TFReaderState::READ_FIRST_TABLE_FROM_NEXT_FILE);
403 break;
404 case TFReaderState::INVALID_TIMEFRAME:
405 return;
406 case TFReaderState::TIMEFRAME_READ:
407 break;
408 }
409 }
410 int64_t stopSize = totalSizeCompressed;
411 int64_t bytesDelta = stopSize - startSize;
412 int64_t stopTime = uv_hrtime();
413 float currentDelta = float(stopTime - startTime) / 1000000000; // in s
414 if (ceil(maxRate) > 0.) {
415 float extraTime = (bytesDelta / 1000000 - currentDelta * maxRate) / maxRate;
416 // We only sleep if we read faster than the max-read-rate.
417 if (extraTime > 0.) {
418 LOGP(info, "Read {} MB in {} s. Sleeping for {} seconds to stay within {} MB/s limit.", bytesDelta / 1000000, currentDelta, extraTime, maxRate);
419 uv_sleep(extraTime * 1000); // in milliseconds
420 }
421 }
422 totalDFSent++;
423
424 // Use the new API for sending TIMESLICE_NUMBER_STARTED
426 dpstats.processCommandQueue();
427 monitoring.send(Metric{(uint64_t)totalDFSent, "df-sent"}.addTag(Key::Subsystem, monitoring::tags::Value::DPL));
428 monitoring.send(Metric{(uint64_t)totalSizeUncompressed / 1000, "aod-bytes-read-uncompressed"}.addTag(Key::Subsystem, monitoring::tags::Value::DPL));
429 monitoring.send(Metric{(uint64_t)totalSizeCompressed / 1000, "aod-bytes-read-compressed"}.addTag(Key::Subsystem, monitoring::tags::Value::DPL));
430
431 // save file number and time frame
432 *fileCounter = (fcnt - device.inputTimesliceId) / device.maxInputTimeslices;
433 *numTF = ntf;
434
435 // Check if the next timeframe is available or
436 // if there are more files to be processed. If not, simply exit.
437 ntf = *numTF + 1;
438 // first route with level 0 or -1 if no mapping requested
439 auto firstRoute = std::ranges::find_if(requestedTables, [&didir, level](auto const& route) {
440 auto concrete = DataSpecUtils::asConcreteDataMatcher(route.matcher);
441 return didir->getLevelForOrigin(concrete.origin) == level;
442 });
443 auto concrete = DataSpecUtils::asConcreteDataMatcher(firstRoute->matcher);
444 auto dh = header::DataHeader(concrete.description, concrete.origin, concrete.subSpec);
445 auto fileAndFolder = didir->getFileFolder(dh, fcnt, ntf);
446
447 // In case the filesource is empty, move to the next one.
448 if (fileAndFolder.filesystem() == nullptr) {
449 fcnt += 1;
450 ntf = 0;
451 if (didir->atEnd(fcnt)) {
452 LOGP(info, "No input files left to read for reader {}!", device.inputTimesliceId);
453 didir->closeInputFiles();
454 monitoring.flushBuffer();
455 control.endOfStream();
457 return;
458 }
459 }
460 });
461 })};
462
463 return callback;
464}
465
466} // namespace o2::framework::readers
header::DataDescription description
benchmark::State & state
std::vector< OutputRoute > routes
o2::monitoring::Metric Metric
uint32_t c
Definition RawData.h:2
#define O2_DECLARE_DYNAMIC_LOG(name)
Definition Signpost.h:490
#define O2_SIGNPOST_ID_FROM_POINTER(name, log, pointer)
Definition Signpost.h:506
#define O2_SIGNPOST_EVENT_EMIT(log, id, name, format,...)
Definition Signpost.h:523
TBranch * ptr
o2::monitoring::Monitoring Monitoring
StringRef key
void readyToQuit(bool all)
Compatibility with old API.
void endOfStream()
Signal that we are done with the current stream.
GLdouble f
Definition glcorearb.h:310
GLsizei const GLfloat * value
Definition glcorearb.h:819
GLint level
Definition glcorearb.h:275
constexpr framework::ConcreteDataMatcher matcher()
Definition ASoA.h:388
@ Me
Only quit this data processor.
AlgorithmSpec::ProcessCallback adaptStateless(LAMBDA l)
AlgorithmSpec::InitCallback adaptStateful(LAMBDA l)
a couple of static helper functions to create timestamp values for CCDB queries or override obsolete ...
std::string filename()
RuntimeWatchdog(Long64_t limit)
header::DataHeader::SubSpecificationType subSpec
Helper struct to hold statistics about the data processing happening.
@ Add
Update the rate of the metric given the amount since the last time.
static bool partialMatch(InputSpec const &spec, o2::header::DataOrigin const &origin)
static ConcreteDataMatcher asConcreteDataMatcher(InputSpec const &input)
size_t maxInputTimeslices
The maximum number of time pipelining for this device.
Definition DeviceSpec.h:70
size_t inputTimesliceId
The time pipelining id of this particular device.
Definition DeviceSpec.h:68
std::vector< OutputRoute > outputs
Definition DeviceSpec.h:63
static AlgorithmSpec rootFileReaderCallback(ConfigContext const &context)
the main header struct
Definition DataHeader.h:620
std::enable_if_t< std::is_same< T, std::string >::value==true, T > as() const
get the descriptor as std::string
Definition DataHeader.h:301