Project
Loading...
Searching...
No Matches
DataInputDirector.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#include "DataInputDirector.h"
13#include "Framework/Logger.h"
17#include "Framework/Output.h"
18#include "Framework/Signpost.h"
20#include "Headers/DataHeader.h"
21#include "Monitoring/Tags.h"
22#include "Monitoring/Metric.h"
23#include "Monitoring/Monitoring.h"
24
25#include "rapidjson/document.h"
26#include "rapidjson/prettywriter.h"
27#include "rapidjson/filereadstream.h"
28
29#include "TGrid.h"
30#include "TObjString.h"
31#include "TMap.h"
32#include "TFile.h"
33
34#include <arrow/dataset/file_base.h>
35#include <arrow/dataset/dataset.h>
36#include <uv.h>
37#include <memory>
38
39#if __has_include(<TJAlienFile.h>)
40#include <TJAlienFile.h>
41
42#include <utility>
43#endif
44
45#include <dlfcn.h>
46O2_DECLARE_DYNAMIC_LOG(reader_memory_dump);
47
48namespace o2::framework
49{
50using namespace rapidjson;
51
53{
54
55 FileNameHolder holder;
56 holder.fileName = fileName;
57 return holder;
58}
59
61 : mAlienSupport(alienSupport),
62 mContext(context),
63 mLevel(level)
64{
65 std::vector<char const*> capabilitiesSpecs = {
66 "O2Framework:RNTupleObjectReadingCapability",
67 "O2Framework:TTreeObjectReadingCapability",
68 };
69
70 std::vector<LoadablePlugin> plugins;
71 for (auto spec : capabilitiesSpecs) {
72 auto morePlugins = PluginManager::parsePluginSpecString(spec);
73 for (auto& extra : morePlugins) {
74 plugins.push_back(extra);
75 }
76 }
77
78 PluginManager::loadFromPlugin<RootObjectReadingCapability, RootObjectReadingCapabilityPlugin>(plugins, mFactory.capabilities);
79}
80
82{
83 LOGP(info, "DataInputDescriptor");
84 LOGP(info, " Table name : {}", tablename);
85 LOGP(info, " Tree name : {}", treename);
86 LOGP(info, " Input files file : {}", getInputfilesFilename());
87 LOGP(info, " File name regex : {}", getFilenamesRegexString());
88 LOGP(info, " Input files : {}", mfilenames.size());
89 for (auto& fn : mfilenames) {
90 LOGP(info, " {} {}", fn.fileName, fn.numberOfTimeFrames);
91 }
92 LOGP(info, " Total number of TF: {}", getNumberTimeFrames());
93}
94
96{
97 return (minputfilesFile.empty() && minputfilesFilePtr) ? (std::string)*minputfilesFilePtr : minputfilesFile;
98}
99
101{
102 return (mFilenameRegex.empty() && mFilenameRegexPtr) ? (std::string)*mFilenameRegexPtr : mFilenameRegex;
103}
104
106{
107 return std::regex(getFilenamesRegexString());
108}
109
111{
112 // remove leading file:// from file name
113 if (fn.fileName.rfind("file://", 0) == 0) {
114 fn.fileName.erase(0, 7);
115 } else if (!mAlienSupport && fn.fileName.rfind("alien://", 0) == 0 && !gGrid) {
116 LOGP(debug, "AliEn file requested. Enabling support.");
117 TGrid::Connect("alien://");
118 mAlienSupport = true;
119 }
120
121 mtotalNumberTimeFrames += fn.numberOfTimeFrames;
122 mfilenames.emplace_back(fn);
123}
124
125bool DataInputDescriptor::setFile(int counter, int wantedParentLevel, std::string_view origin)
126{
127 // no files left
128 if (counter >= getNumberInputfiles()) {
129 return false;
130 }
131
132 // In case the origin starts with a anything but AOD, we add the origin as the suffix
133 // of the filename. In the future we might expand this for proper rewriting of the
134 // filename based on the origin and the original file information.
135 std::string filename = mfilenames[counter].fileName;
136 // In case we do not need to remap parent levels, the requested origin is what
137 // drives the filename.
138 if (wantedParentLevel == -1 && !origin.starts_with("AOD")) {
139 filename = std::regex_replace(filename, std::regex("[.]root$"), fmt::format("_{}.root", origin));
140 }
141
142 // open file
143 auto rootFS = std::dynamic_pointer_cast<TFileFileSystem>(mCurrentFilesystem);
144 if (rootFS.get()) {
145 if (rootFS->GetFile()->GetName() == filename) {
146 return true;
147 }
149 }
150
151 TFile* tfile = nullptr;
152 bool externalFile = false;
153 for (auto& [name, f] : mContext.openFiles) {
154 if (name == filename) {
155 tfile = f;
156 externalFile = true;
157 break;
158 }
159 }
160 if (tfile == nullptr) {
161 tfile = TFile::Open(filename.c_str());
162 }
163 mCurrentFilesystem = std::make_shared<TFileFileSystem>(tfile, 50 * 1024 * 1024, mFactory, !externalFile);
164 if (!mCurrentFilesystem.get()) {
165 throw std::runtime_error(fmt::format("Couldn't open file \"{}\"!", filename));
166 }
167 rootFS = std::dynamic_pointer_cast<TFileFileSystem>(mCurrentFilesystem);
169
170 // get the parent file map if exists
171 mParentFileMap = (TMap*)rootFS->GetFile()->Get("parentFiles"); // folder name (DF_XXX) --> parent file (absolute path)
172 if (mParentFileMap && !mContext.parentFileReplacement.empty()) {
173 auto pos = mContext.parentFileReplacement.find(';');
174 if (pos == std::string::npos) {
175 throw std::runtime_error(fmt::format("Invalid syntax in aod-parent-base-path-replacement: \"{}\"", mContext.parentFileReplacement.c_str()));
176 }
177 auto from = mContext.parentFileReplacement.substr(0, pos);
178 auto to = mContext.parentFileReplacement.substr(pos + 1);
179
180 auto it = mParentFileMap->MakeIterator();
181 while (auto obj = it->Next()) {
182 auto objString = (TObjString*)mParentFileMap->GetValue(obj);
183 objString->String().ReplaceAll(from.c_str(), to.c_str());
184 }
185 delete it;
186 }
187
188 // get the directory names
189 if (mfilenames[counter].numberOfTimeFrames <= 0) {
190 const std::regex TFRegex = std::regex("/?DF_([0-9]+)(|-.*)$");
191 TList* keyList = rootFS->GetFile()->GetListOfKeys();
192 std::vector<std::string> finalList;
193
194 // extract TF numbers and sort accordingly
195 // We use an extra seen set to make sure we preserve the order in which
196 // we instert things in the final list and to make sure we do not have duplicates.
197 // Multiple folder numbers can happen if we use a flat structure /DF_<df>-<tablename>
198 std::unordered_set<size_t> seen;
199 for (auto key : *keyList) {
200 std::smatch matchResult;
201 std::string keyName = ((TObjString*)key)->GetString().Data();
202 bool match = std::regex_match(keyName, matchResult, TFRegex);
203 if (match) {
204 auto folderNumber = std::stoul(matchResult[1].str());
205 if (seen.find(folderNumber) == seen.end()) {
206 seen.insert(folderNumber);
207 mfilenames[counter].listOfTimeFrameNumbers.emplace_back(folderNumber);
208 }
209 }
210 }
211
212 if (mParentFileMap != nullptr) {
213 // If we have a parent map, we should not process in DF alphabetical order but according to parent file to avoid swapping between files
214 std::ranges::sort(mfilenames[counter].listOfTimeFrameNumbers,
215 [this](long const& l1, long const& l2) -> bool {
216 auto p1 = (TObjString*)this->mParentFileMap->GetValue(("DF_" + std::to_string(l1)).c_str());
217 auto p2 = (TObjString*)this->mParentFileMap->GetValue(("DF_" + std::to_string(l2)).c_str());
218 return p1->GetString().CompareTo(p2->GetString()) < 0;
219 });
220 } else {
221 std::sort(mfilenames[counter].listOfTimeFrameNumbers.begin(), mfilenames[counter].listOfTimeFrameNumbers.end());
222 }
223
224 mfilenames[counter].alreadyRead.resize(mfilenames[counter].alreadyRead.size() + mfilenames[counter].listOfTimeFrameNumbers.size(), false);
225 mfilenames[counter].numberOfTimeFrames = mfilenames[counter].listOfTimeFrameNumbers.size();
226 }
227
228 mCurrentFileID = counter;
229 mCurrentFileStartedAt = uv_hrtime();
230 mIOTime = 0;
231
232 return true;
233}
234
235uint64_t DataInputDescriptor::getTimeFrameNumber(int counter, int numTF, int wantedParentLevel, std::string_view wantedOrigin)
236{
237
238 // open file
239 if (!setFile(counter, wantedParentLevel, wantedOrigin)) {
240 return 0ul;
241 }
242
243 // no TF left
244 if (mfilenames[counter].numberOfTimeFrames > 0 && numTF >= mfilenames[counter].numberOfTimeFrames) {
245 return 0ul;
246 }
247
248 return (mfilenames[counter].listOfTimeFrameNumbers)[numTF];
249}
250
251std::pair<std::shared_ptr<DataInputDescriptor>, int> DataInputDescriptor::navigateToLevel(int counter, int numTF, int wantedParentLevel, std::string_view wantedOrigin)
252{
253 if (!setFile(counter, wantedParentLevel, wantedOrigin)) {
254 return {nullptr, -1};
255 }
256 auto folderName = fmt::format("DF_{}", mfilenames[counter].listOfTimeFrameNumbers[numTF]);
257 auto parentFile = getParentFile(counter, numTF, "", wantedParentLevel, wantedOrigin);
258 if (parentFile == nullptr) {
259 return {nullptr, -1};
260 }
261 return {parentFile, parentFile->findDFNumber(0, folderName)};
262}
263
264arrow::dataset::FileSource DataInputDescriptor::getFileFolder(int counter, int numTF, int wantedParentLevel, std::string_view wantedOrigin)
265{
266 // If mapped to a parent level deeper than current, skip directly to the right level.
267 if ((wantedParentLevel != -1) && (mLevel < wantedParentLevel)) {
268 auto [parentFile, parentNumTF] = navigateToLevel(counter, numTF, wantedParentLevel, wantedOrigin);
269 if (parentFile == nullptr || parentNumTF == -1) {
270 return {};
271 }
272 return parentFile->getFileFolder(0, parentNumTF, wantedParentLevel, wantedOrigin);
273 }
274
275 // open file
276 if (!setFile(counter, wantedParentLevel, wantedOrigin)) {
277 return {};
278 }
279
280 // no TF left
281 if ((mfilenames[counter].numberOfTimeFrames > 0) && (numTF >= mfilenames[counter].numberOfTimeFrames)) {
282 return {};
283 }
284
285 mfilenames[counter].alreadyRead[numTF] = true;
286
287 return {fmt::format("DF_{}", mfilenames[counter].listOfTimeFrameNumbers[numTF]), mCurrentFilesystem};
288}
289
290std::shared_ptr<DataInputDescriptor> DataInputDescriptor::getParentFile(int counter, int numTF, std::string treename, int wantedParentLevel, std::string_view wantedOrigin)
291{
292 if (!mParentFileMap) {
293 // This file has no parent map
294 return nullptr;
295 }
296
297 auto folderName = fmt::format("DF_{}", mfilenames[counter].listOfTimeFrameNumbers[numTF]);
298 auto parentFileName = (TObjString*)mParentFileMap->GetValue(folderName.c_str());
299 // The current DF is not found in the parent map (this should not happen and is a fatal error)
300 auto rootFS = std::dynamic_pointer_cast<TFileFileSystem>(mCurrentFilesystem);
301 if (!parentFileName) {
302 throw std::runtime_error(fmt::format(R"(parent file map exists but does not contain the current DF "{}" in file "{}")", folderName.c_str(), rootFS->GetFile()->GetName()));
303 return nullptr;
304 }
305
306 if (mParentFile) {
307 // Is this still the corresponding to the correct file?
308 auto parentRootFS = std::dynamic_pointer_cast<TFileFileSystem>(mParentFile->mCurrentFilesystem);
309 if (parentFileName->GetString().CompareTo(parentRootFS->GetFile()->GetName()) == 0) {
310 return mParentFile;
311 } else {
312 mParentFile->closeInputFile();
313 mParentFile.reset();
314 }
315 }
316
317 if (mLevel == mContext.allowedParentLevel) {
318 throw std::runtime_error(fmt::format(R"(while looking for tree "{}", the parent file was requested but we are already at level {} of maximal allowed level {} for DF "{}" in file "{}")", treename.c_str(), mLevel, mContext.allowedParentLevel, folderName.c_str(),
319 rootFS->GetFile()->GetName()));
320 }
321
322 LOGP(info, "Opening parent file {} for DF {}", parentFileName->GetString().Data(), folderName.c_str());
323 mParentFile = std::make_shared<DataInputDescriptor>(mAlienSupport, mLevel + 1, mContext);
324 mParentFile->mdefaultFilenamesPtr.emplace_back(makeFileNameHolder(parentFileName->GetString().Data()));
325 mParentFile->fillInputfiles();
326 mParentFile->setFile(0, wantedParentLevel, wantedOrigin);
327 return mParentFile;
328}
329
331{
332 return mfilenames.at(counter).numberOfTimeFrames;
333}
334
336{
337 auto& list = mfilenames.at(counter).alreadyRead;
338 return std::count(list.begin(), list.end(), true);
339}
340
342{
343 auto rootFS = std::dynamic_pointer_cast<TFileFileSystem>(mCurrentFilesystem);
344 auto f = dynamic_cast<TFile*>(rootFS->GetFile());
345 std::string monitoringInfo(fmt::format("lfn={},size={}", f->GetName(), f->GetSize()));
346#if __has_include(<TJAlienFile.h>)
347 auto alienFile = dynamic_cast<TJAlienFile*>(f);
348 if (alienFile) {
349 monitoringInfo += fmt::format(",se={},open_time={:.1f}", alienFile->GetSE(), alienFile->GetElapsed());
350 }
351#endif
352 if (mContext.monitoring) {
353 mContext.monitoring->send(o2::monitoring::Metric{monitoringInfo, "aod-file-open-info"}.addTag(o2::monitoring::tags::Key::Subsystem, o2::monitoring::tags::Value::DPL));
354 }
355 LOGP(info, "Opening file: {}", monitoringInfo);
356}
357
359{
360 int64_t wait_time = (int64_t)uv_hrtime() - (int64_t)mCurrentFileStartedAt - (int64_t)mIOTime;
361 if (wait_time < 0) {
362 wait_time = 0;
363 }
364 auto rootFS = std::dynamic_pointer_cast<TFileFileSystem>(mCurrentFilesystem);
365 auto f = dynamic_cast<TFile*>(rootFS->GetFile());
366 std::string monitoringInfo(fmt::format("lfn={},size={},total_df={},read_df={},read_bytes={},read_calls={},io_time={:.1f},wait_time={:.1f},level={}", f->GetName(),
367 f->GetSize(), getTimeFramesInFile(mCurrentFileID), getReadTimeFramesInFile(mCurrentFileID), f->GetBytesRead(), f->GetReadCalls(),
368 ((float)mIOTime / 1e9), ((float)wait_time / 1e9), mLevel));
369#if __has_include(<TJAlienFile.h>)
370 auto alienFile = dynamic_cast<TJAlienFile*>(f);
371 if (alienFile) {
372 monitoringInfo += fmt::format(",se={},open_time={:.1f}", alienFile->GetSE(), alienFile->GetElapsed());
373 }
374#endif
375 if (mContext.monitoring) {
376 mContext.monitoring->send(o2::monitoring::Metric{monitoringInfo, "aod-file-read-info"}.addTag(o2::monitoring::tags::Key::Subsystem, o2::monitoring::tags::Value::DPL));
377 }
378 LOGP(info, "Read info: {}", monitoringInfo);
379}
380
382{
383 if (mCurrentFilesystem.get()) {
384 if (mParentFile) {
385 mParentFile->closeInputFile();
386 mParentFile.reset();
387 }
388
389 delete mParentFileMap;
390 mParentFileMap = nullptr;
391
393 mCurrentFilesystem.reset();
394 }
395}
396
398{
399 if (getNumberInputfiles() > 0) {
400 // 1. mfilenames
401 return getNumberInputfiles();
402 }
403
404 auto fileName = getInputfilesFilename();
405 if (!fileName.empty()) {
406 // 2. getFilenamesRegex() @ getInputfilesFilename()
407 try {
408 std::ifstream filelist(fileName);
409 if (!filelist.is_open()) {
410 throw std::runtime_error(fmt::format(R"(Couldn't open file "{}")", fileName));
411 }
412 while (std::getline(filelist, fileName)) {
413 // remove white spaces, empty lines are skipped
414 fileName.erase(std::remove_if(fileName.begin(), fileName.end(), ::isspace), fileName.end());
415 if (!fileName.empty() && (getFilenamesRegexString().empty() ||
416 std::regex_match(fileName, getFilenamesRegex()))) {
418 }
419 }
420 } catch (...) {
421 LOGP(error, "Check the input files file! Unable to process \"{}\"!", getInputfilesFilename());
422 return 0;
423 }
424 } else {
425 // 3. getFilenamesRegex() @ mdefaultFilenamesPtr
426 if (!mdefaultFilenamesPtr.empty()) {
427 for (auto& fileNameHolder : mdefaultFilenamesPtr) {
428 if (getFilenamesRegexString().empty() ||
429 std::regex_match(fileNameHolder.fileName, getFilenamesRegex())) {
430 addFileNameHolder(fileNameHolder);
431 }
432 }
433 }
434 }
435
436 return getNumberInputfiles();
437}
438
439int DataInputDescriptor::findDFNumber(int file, std::string dfName)
440{
441 auto dfList = mfilenames[file].listOfTimeFrameNumbers;
442 auto it = std::find_if(dfList.begin(), dfList.end(), [dfName](size_t i) { return fmt::format("DF_{}", i) == dfName; });
443 if (it == dfList.end()) {
444 return -1;
445 }
446 return it - dfList.begin();
447}
448
451 : mTarget(target)
452 {
453 start = uv_hrtime();
454 }
456 {
457 if (!active) {
458 return;
459 }
460 O2_SIGNPOST_ACTION(reader_memory_dump, [](void*) {
461 void (*dump_)(const char*);
462 if (void* sym = dlsym(nullptr, "igprof_dump_now")) {
463 dump_ = __extension__(void (*)(const char*)) sym;
464 if (dump_) {
465 std::string filename = fmt::format("reader-memory-dump-{}.gz", uv_hrtime());
466 dump_(filename.c_str());
467 }
468 }
469 });
470 mTarget += (uv_hrtime() - start);
471 }
472
474 {
475 active = false;
476 }
477
478 bool active = true;
479 uint64_t& mTarget;
480 uint64_t start;
481 uint64_t stop;
482};
483
484bool DataInputDescriptor::readTree(DataAllocator& outputs, header::DataHeader dh, int counter, int numTF, std::string treename, size_t& totalSizeCompressed, size_t& totalSizeUncompressed)
485{
486 CalculateDelta t(mIOTime);
487 std::string wantedOrigin = dh.dataOrigin.as<std::string>();
488 int wantedLevel = mContext.levelForOrigin(wantedOrigin);
489
490 // If this origin is mapped to a parent level deeper than current, skip directly without
491 // attempting to read from this level.
492 if (wantedLevel != -1 && mLevel < wantedLevel) {
493 auto [parentFile, parentNumTF] = navigateToLevel(counter, numTF, wantedLevel, wantedOrigin);
494 if (parentFile == nullptr) {
495 auto rootFS = std::dynamic_pointer_cast<TFileFileSystem>(mCurrentFilesystem);
496 throw std::runtime_error(fmt::format(R"(No parent file found for "{}" while looking for level {} in "{}")", treename, wantedLevel, rootFS->GetFile()->GetName()));
497 }
498 if (parentNumTF == -1) {
499 auto parentRootFS = std::dynamic_pointer_cast<TFileFileSystem>(parentFile->mCurrentFilesystem);
500 throw std::runtime_error(fmt::format(R"(DF not found in parent file "{}")", parentRootFS->GetFile()->GetName()));
501 }
502 t.deactivate();
503 return parentFile->readTree(outputs, dh, 0, parentNumTF, treename, totalSizeCompressed, totalSizeUncompressed);
504 }
505
506 auto folder = getFileFolder(counter, numTF, wantedLevel, wantedOrigin);
507 if (!folder.filesystem()) {
508 t.deactivate();
509 return false;
510 }
511
512 auto rootFS = std::dynamic_pointer_cast<TFileFileSystem>(folder.filesystem());
513
514 if (!rootFS) {
515 t.deactivate();
516 throw std::runtime_error(fmt::format(R"(Not a TFile filesystem!)"));
517 }
518 // FIXME: Ugly. We should detect the format from the treename, good enough for now.
519 std::shared_ptr<arrow::dataset::FileFormat> format;
520 FragmentToBatch::StreamerCreator creator = nullptr;
521
522 auto fullpath = arrow::dataset::FileSource{folder.path() + "/" + treename, folder.filesystem()};
523
524 for (auto& capability : mFactory.capabilities) {
525 auto objectPath = capability.lfn2objectPath(fullpath.path());
526 void* handle = capability.getHandle(rootFS, objectPath);
527 if (handle) {
528 format = capability.factory().format();
529 creator = capability.factory().deferredOutputStreamer;
530 break;
531 }
532 }
533
534 // FIXME: we should distinguish between an actually missing object and one which has a non compatible
535 // format.
536 if (!format) {
537 t.deactivate();
538 LOGP(debug, "Could not find tree {}. Trying in parent file.", fullpath.path());
539 auto parentFile = getParentFile(counter, numTF, treename, wantedLevel, wantedOrigin);
540 if (parentFile != nullptr) {
541 int parentNumTF = parentFile->findDFNumber(0, folder.path());
542 if (parentNumTF == -1) {
543 auto parentRootFS = std::dynamic_pointer_cast<TFileFileSystem>(parentFile->mCurrentFilesystem);
544 throw std::runtime_error(fmt::format(R"(DF {} listed in parent file map but not found in the corresponding file "{}")", folder.path(), parentRootFS->GetFile()->GetName()));
545 }
546 // first argument is 0 as the parent file object contains only 1 file
547 return parentFile->readTree(outputs, dh, 0, parentNumTF, treename, totalSizeCompressed, totalSizeUncompressed);
548 }
549 auto rootFS = std::dynamic_pointer_cast<TFileFileSystem>(mCurrentFilesystem);
550 throw std::runtime_error(fmt::format(R"(Couldn't get TTree "{}" from "{}". Please check https://aliceo2group.github.io/analysis-framework/docs/troubleshooting/#tree-not-found for more information.)", fullpath.path(), rootFS->GetFile()->GetName()));
551 }
552
553 auto schemaOpt = format->Inspect(fullpath);
554 auto physicalSchema = schemaOpt;
555 std::vector<std::shared_ptr<arrow::Field>> fields;
556 for (auto& original : (*schemaOpt)->fields()) {
557 if (original->name().ends_with("_size")) {
558 continue;
559 }
560 fields.push_back(original);
561 }
562 auto datasetSchema = std::make_shared<arrow::Schema>(fields);
563
564 auto fragment = format->MakeFragment(fullpath, {}, *physicalSchema);
565
566 // create table output
567 auto o = Output(dh);
568
569 // FIXME: This should allow me to create a memory pool
570 // which I can then use to scan the dataset.
571 auto f2b = outputs.make<FragmentToBatch>(o, creator, *fragment);
572
575 f2b->setLabel(treename.c_str());
576 f2b->fill(datasetSchema, format);
577
578 return true;
579}
580
581DataInputDirector::DataInputDirector(std::vector<std::string> inputFiles, DataInputDirectorContext&& context)
582 : mContext{context}
583{
584 if (inputFiles.size() == 1 && !inputFiles[0].empty() && inputFiles[0][0] == '@') {
585 setInputfilesFile(inputFiles.back().substr(1, -1));
586 } else {
587 for (auto inputFile : inputFiles) {
588 mdefaultInputFiles.emplace_back(makeFileNameHolder(inputFile));
589 }
590 }
591
593}
594
596{
597 mdefaultInputFiles.clear();
598 mdefaultDataInputDescriptor = nullptr;
599
600 mdataInputDescriptors.clear();
601}
602
604{
605 mdataInputDescriptors.clear();
606 mdefaultInputFiles.clear();
607 mFilenameRegex = std::string("");
608};
609
611{
612 if (mdefaultDataInputDescriptor) {
613 mdefaultDataInputDescriptor.reset();
614 }
615 mdefaultDataInputDescriptor = std::make_shared<DataInputDescriptor>(mAlienSupport, 0, mContext);
616
617 mdefaultDataInputDescriptor->setInputfilesFile(minputfilesFile);
618 mdefaultDataInputDescriptor->setFilenamesRegex(mFilenameRegex);
619 mdefaultDataInputDescriptor->setDefaultInputfiles(mdefaultInputFiles);
620 mdefaultDataInputDescriptor->tablename = "any";
621 mdefaultDataInputDescriptor->treename = "any";
622 mdefaultDataInputDescriptor->fillInputfiles();
623
624 mAlienSupport &= mdefaultDataInputDescriptor->isAlienSupportOn();
625}
626
627bool DataInputDirector::readJson(std::string const& fnjson)
628{
629 // open the file
630 FILE* f = fopen(fnjson.c_str(), "r");
631 if (!f) {
632 LOGP(error, "Could not open JSON file \"{}\"!", fnjson);
633 return false;
634 }
635
636 // create streamer
637 char readBuffer[65536];
638 FileReadStream inputStream(f, readBuffer, sizeof(readBuffer));
639
640 // parse the json file
641 Document jsonDoc;
642 jsonDoc.ParseStream(inputStream);
643 auto status = readJsonDocument(&jsonDoc);
644
645 // clean up
646 fclose(f);
647
648 return status;
649}
650
651bool DataInputDirector::readJsonDocument(Document* jsonDoc)
652{
653 // initialisations
654 std::string fileName("");
655 const char* itemName;
656
657 // is it a proper json document?
658 if (jsonDoc->HasParseError()) {
659 LOGP(error, "Check the JSON document! There is a problem with the format!");
660 return false;
661 }
662
663 // InputDirector
664 itemName = "InputDirector";
665 const Value& didirItem = (*jsonDoc)[itemName];
666 if (!didirItem.IsObject()) {
667 LOGP(info, "No \"{}\" object found in the JSON document!", itemName);
668 return true;
669 }
670
671 // now read various items
672 itemName = "debugmode";
673 if (didirItem.HasMember(itemName)) {
674 if (didirItem[itemName].IsBool()) {
675 mDebugMode = (didirItem[itemName].GetBool());
676 } else {
677 LOGP(error, "Check the JSON document! Item \"{}\" must be a boolean!", itemName);
678 return false;
679 }
680 } else {
681 mDebugMode = false;
682 }
683
684 if (mDebugMode) {
685 StringBuffer buffer;
686 buffer.Clear();
687 PrettyWriter<StringBuffer> writer(buffer);
688 didirItem.Accept(writer);
689 LOGP(info, "InputDirector object: {}", std::string(buffer.GetString()));
690 }
691
692 itemName = "fileregex";
693 if (didirItem.HasMember(itemName)) {
694 if (didirItem[itemName].IsString()) {
695 setFilenamesRegex(didirItem[itemName].GetString());
696 } else {
697 LOGP(error, "Check the JSON document! Item \"{}\" must be a string!", itemName);
698 return false;
699 }
700 }
701
702 itemName = "resfiles";
703 if (didirItem.HasMember(itemName)) {
704 if (didirItem[itemName].IsString()) {
705 fileName = didirItem[itemName].GetString();
706 if (fileName.size() && fileName[0] == '@') {
707 fileName.erase(0, 1);
708 setInputfilesFile(fileName);
709 } else {
711 mdefaultInputFiles.emplace_back(makeFileNameHolder(fileName));
712 }
713 } else if (didirItem[itemName].IsArray()) {
715 auto fns = didirItem[itemName].GetArray();
716 for (auto& fn : fns) {
717 mdefaultInputFiles.emplace_back(makeFileNameHolder(fn.GetString()));
718 }
719 } else {
720 LOGP(error, "Check the JSON document! Item \"{}\" must be a string or an array!", itemName);
721 return false;
722 }
723 }
724
725 itemName = "InputDescriptors";
726 if (didirItem.HasMember(itemName)) {
727 if (!didirItem[itemName].IsArray()) {
728 LOGP(error, "Check the JSON document! Item \"{}\" must be an array!", itemName);
729 return false;
730 }
731
732 // loop over DataInputDescriptors
733 for (auto& didescItem : didirItem[itemName].GetArray()) {
734 if (!didescItem.IsObject()) {
735 LOGP(error, "Check the JSON document! \"{}\" must be objects!", itemName);
736 return false;
737 }
738 // create a new dataInputDescriptor
739 auto didesc = DataInputDescriptor(mAlienSupport, 0, mContext);
740 didesc.setDefaultInputfiles(mdefaultInputFiles);
741
742 itemName = "table";
743 if (didescItem.HasMember(itemName)) {
744 if (didescItem[itemName].IsString()) {
745 didesc.tablename = didescItem[itemName].GetString();
746 didesc.matcher = DataDescriptorQueryBuilder::buildNode(didesc.tablename);
747 } else {
748 LOGP(error, "Check the JSON document! Item \"{}\" must be a string!", itemName);
749 return false;
750 }
751 } else {
752 LOGP(error, "Check the JSON document! Item \"{}\" is missing!", itemName);
753 return false;
754 }
755
756 itemName = "treename";
757 if (didescItem.HasMember(itemName)) {
758 if (didescItem[itemName].IsString()) {
759 didesc.treename = didescItem[itemName].GetString();
760 } else {
761 LOGP(error, "Check the JSON document! Item \"{}\" must be a string!", itemName);
762 return false;
763 }
764 } else {
765 auto m = DataDescriptorQueryBuilder::getTokens(didesc.tablename);
766 didesc.treename = m[2];
767 }
768
769 itemName = "fileregex";
770 if (didescItem.HasMember(itemName)) {
771 if (didescItem[itemName].IsString()) {
772 if (didesc.getNumberInputfiles() == 0) {
773 didesc.setFilenamesRegex(didescItem[itemName].GetString());
774 }
775 } else {
776 LOGP(error, "Check the JSON document! Item \"{}\" must be a string!", itemName);
777 return false;
778 }
779 } else {
780 if (didesc.getNumberInputfiles() == 0) {
781 didesc.setFilenamesRegex(mFilenameRegexPtr);
782 }
783 }
784
785 itemName = "resfiles";
786 if (didescItem.HasMember(itemName)) {
787 if (didescItem[itemName].IsString()) {
788 fileName = didescItem[itemName].GetString();
789 if (fileName.size() && fileName[0] == '@') {
790 didesc.setInputfilesFile(fileName.erase(0, 1));
791 } else {
792 if (didesc.getFilenamesRegexString().empty() ||
793 std::regex_match(fileName, didesc.getFilenamesRegex())) {
794 didesc.addFileNameHolder(makeFileNameHolder(fileName));
795 }
796 }
797 } else if (didescItem[itemName].IsArray()) {
798 auto fns = didescItem[itemName].GetArray();
799 for (auto& fn : fns) {
800 if (didesc.getFilenamesRegexString().empty() ||
801 std::regex_match(fn.GetString(), didesc.getFilenamesRegex())) {
802 didesc.addFileNameHolder(makeFileNameHolder(fn.GetString()));
803 }
804 }
805 } else {
806 LOGP(error, "Check the JSON document! Item \"{}\" must be a string or an array!", itemName);
807 return false;
808 }
809 } else {
810 didesc.setInputfilesFile(minputfilesFilePtr);
811 }
812
813 // fill mfilenames and add InputDescriptor to InputDirector
814 if (didesc.fillInputfiles() > 0) {
815 mdataInputDescriptors.emplace_back(didesc);
816 } else {
817 didesc.printOut();
818 LOGP(info, "This DataInputDescriptor is ignored because its file list is empty!");
819 }
820 mAlienSupport &= didesc.isAlienSupportOn();
821 }
822 }
823
824 // add a default DataInputDescriptor
826
827 // check that all DataInputDescriptors have the same number of input files
828 if (!isValid()) {
829 printOut();
830 return false;
831 }
832
833 // print the DataIputDirector
834 if (mDebugMode) {
835 printOut();
836 }
837
838 return true;
839}
840
842{
843 // compute list of matching outputs
845
846 for (auto& didesc : mdataInputDescriptors) {
847 if (didesc.matcher->match(dh, context)) {
848 return &didesc;
849 }
850 }
851
852 return nullptr;
853}
854
855arrow::dataset::FileSource DataInputDirector::getFileFolder(header::DataHeader dh, int counter, int numTF)
856{
857 auto didesc = getDataInputDescriptor(dh);
858 // if NOT match then use defaultDataInputDescriptor
859 if (!didesc) {
860 didesc = mdefaultDataInputDescriptor.get();
861 }
862 std::string origin = dh.dataOrigin.as<std::string>();
863 int wantedLevel = mContext.levelForOrigin(origin);
864
865 return didesc->getFileFolder(counter, numTF, wantedLevel, origin);
866}
867
869{
870 auto didesc = getDataInputDescriptor(dh);
871 // if NOT match then use defaultDataInputDescriptor
872 if (!didesc) {
873 didesc = mdefaultDataInputDescriptor.get();
874 }
875
876 return didesc->getTimeFramesInFile(counter);
877}
878
880{
881 auto didesc = getDataInputDescriptor(dh);
882 // if NOT match then use defaultDataInputDescriptor
883 if (!didesc) {
884 didesc = mdefaultDataInputDescriptor.get();
885 }
886 std::string origin = dh.dataOrigin.as<std::string>();
887 int wantedLevel = mContext.levelForOrigin(origin);
888
889 return didesc->getTimeFrameNumber(counter, numTF, wantedLevel, origin);
890}
891
892bool DataInputDirector::readTree(DataAllocator& outputs, header::DataHeader dh, int counter, int numTF, size_t& totalSizeCompressed, size_t& totalSizeUncompressed, bool wasAOD)
893{
894 std::string treename;
895
896 auto didesc = getDataInputDescriptor(dh);
897 if (didesc) {
898 // if match then use filename and treename from DataInputDescriptor
899 treename = didesc->treename;
900 } else {
901 // if NOT match then use
902 // . filename from defaultDataInputDescriptor
903 // . treename from DataHeader
904 didesc = mdefaultDataInputDescriptor.get();
905 treename = aod::datamodel::getTreeName(dh, wasAOD);
906 }
907 std::string origin = dh.dataOrigin.as<std::string>();
908
909 auto result = didesc->readTree(outputs, dh, counter, numTF, treename, totalSizeCompressed, totalSizeUncompressed);
910 return result;
911}
912
914{
915 mdefaultDataInputDescriptor->closeInputFile();
916 for (auto& didesc : mdataInputDescriptors) {
917 didesc.closeInputFile();
918 }
919}
920
921bool DataInputDirector::isValid()
922{
923 bool status = true;
924 int numberFiles = mdefaultDataInputDescriptor->getNumberInputfiles();
925 for (auto& didesc : mdataInputDescriptors) {
926 status &= didesc.getNumberInputfiles() == numberFiles;
927 }
928
929 return status;
930}
931
933{
934 bool status = mdefaultDataInputDescriptor->getNumberInputfiles() <= counter;
935 for (auto& didesc : mdataInputDescriptors) {
936 status &= (didesc.getNumberInputfiles() <= counter);
937 }
938
939 return status;
940}
941
943{
944 LOGP(info, "DataInputDirector");
945 LOGP(info, " Default input files file : {}", minputfilesFile);
946 LOGP(info, " Default file name regex : {}", mFilenameRegex);
947 LOGP(info, " Default file names : {}", mdefaultInputFiles.size());
948 for (auto const& fn : mdefaultInputFiles) {
949 LOGP(info, " {} {}", fn.fileName, fn.numberOfTimeFrames);
950 }
951 LOGP(info, " Default DataInputDescriptor:");
952 mdefaultDataInputDescriptor->printOut();
953 LOGP(info, " DataInputDescriptors : {}", getNumberInputDescriptors());
954 for (auto const& didesc : mdataInputDescriptors) {
955 didesc.printOut();
956 }
957}
958
960{
961 return mContext.levelForOrigin(origin.as<std::string>());
962}
963
964} // namespace o2::framework
header::DataOrigin origin
o2::monitoring::tags::Value Value
std::vector< std::shared_ptr< arrow::Field > > fields
std::ostringstream debug
int32_t i
constexpr int p2()
constexpr int p1()
constexpr to accelerate the coordinates changing
uint16_t pos
Definition RawData.h:3
#define O2_DECLARE_DYNAMIC_LOG(name)
Definition Signpost.h:490
#define O2_SIGNPOST_ACTION(log, callback)
Definition Signpost.h:511
StringRef key
decltype(auto) make(const Output &spec, Args... args)
uint64_t getTimeFrameNumber(int counter, int numTF, int wantedParentLevel, std::string_view wantedOrigin)
std::shared_ptr< DataInputDescriptor > getParentFile(int counter, int numTF, std::string treename, int wantedParentLevel, std::string_view wantedOrigin)
bool readTree(DataAllocator &outputs, header::DataHeader dh, int counter, int numTF, std::string treename, size_t &totalSizeCompressed, size_t &totalSizeUncompressed)
arrow::dataset::FileSource getFileFolder(int counter, int numTF, int wantedParentLevel, std::string_view wantedOrigin)
DataInputDescriptor(bool alienSupport, int level, DataInputDirectorContext &context)
void addFileNameHolder(FileNameHolder fn)
bool setFile(int counter, int wantedParentLevel, std::string_view wantedOrigin)
int findDFNumber(int file, std::string dfName)
std::pair< std::shared_ptr< DataInputDescriptor >, int > navigateToLevel(int counter, int numTF, int wantedParentLevel, std::string_view wantedOrigin)
DataInputDescriptor * getDataInputDescriptor(header::DataHeader dh)
DataInputDirector(std::vector< std::string > inputFiles, DataInputDirectorContext &&context)
arrow::dataset::FileSource getFileFolder(header::DataHeader dh, int counter, int numTF)
void setInputfilesFile(std::string iffn)
int getTimeFramesInFile(header::DataHeader dh, int counter)
uint64_t getTimeFrameNumber(header::DataHeader dh, int counter, int numTF)
int getLevelForOrigin(header::DataOrigin origin) const
void setFilenamesRegex(std::string dfn)
bool readJson(std::string const &fnjson)
bool readTree(DataAllocator &outputs, header::DataHeader dh, int counter, int numTF, size_t &totalSizeCompressed, size_t &totalSizeUncompressed, bool wasAOD)
std::function< std::shared_ptr< arrow::io::OutputStream >(std::shared_ptr< arrow::dataset::FileFragment >, const std::shared_ptr< arrow::ResizableBuffer > &buffer)> StreamerCreator
void setLabel(const char *label)
bool match(const std::vector< std::string > &queries, const char *pattern)
Definition dcs-ccdb.cxx:229
const GLfloat * m
Definition glcorearb.h:4066
GLuint64EXT * result
Definition glcorearb.h:5662
GLuint buffer
Definition glcorearb.h:655
GLuint const GLchar * name
Definition glcorearb.h:781
GLdouble f
Definition glcorearb.h:310
GLenum target
Definition glcorearb.h:1641
typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode)
GLuint start
Definition glcorearb.h:469
GLint GLint GLsizei GLint GLenum format
Definition glcorearb.h:275
GLuint counter
Definition glcorearb.h:3987
std::string getTreeName(header::DataHeader dh, bool wasAOD)
Defining ITS Vertex explicitly as messageable.
Definition Cartesian.h:288
FileNameHolder makeFileNameHolder(std::string fileName)
std::string to_string(gsl::span< T, Size > span)
Definition common.h:52
std::string filename()
void empty(int)
static std::unique_ptr< data_matcher::DataDescriptorMatcher > buildNode(std::string const &nodeString)
static std::vector< std::string > getTokens(std::string const &nodeString)
o2::monitoring::Monitoring * monitoring
std::vector< std::pair< std::string, TFile * > > openFiles
int levelForOrigin(std::string_view origin) const
static std::vector< LoadablePlugin > parsePluginSpecString(char const *str)
Parse a comma separated list of <library>:<plugin-name> plugin declarations.
std::vector< RootObjectReadingCapability > capabilities
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
const std::string str