Project
Loading...
Searching...
No Matches
AODWriterHelpers.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.
14#include "AODWriterHelpers.h"
24
25#include <TFile.h>
26#include <TFile.h>
27#include <TTree.h>
28#include <TMap.h>
29#include <TObjString.h>
30#include <arrow/table.h>
31
33{
34
43
45 TClass* kind = nullptr;
46 void* obj = nullptr;
47 std::string name;
48 int count = -1;
49};
50
51const static std::unordered_map<OutputObjHandlingPolicy, std::string> ROOTfileNames = {{OutputObjHandlingPolicy::AnalysisObject, "AnalysisResults.root"},
52 {OutputObjHandlingPolicy::QAObject, "QAResults.root"}};
53
55{
56 auto& ac = ctx.services().get<AnalysisContext>();
58 int compressionLevel = 505;
59 if (ctx.options().hasOption("aod-writer-compression")) {
60 compressionLevel = ctx.options().get<int>("aod-writer-compression");
61 }
62 return AlgorithmSpec{[dod, outputInputs = ac.outputsInputsAOD, compressionLevel](InitContext& ic) -> std::function<void(ProcessingContext&)> {
63 LOGP(debug, "======== getGlobalAODSink::Init ==========");
64
65 // find out if any table needs to be saved
66 bool hasOutputsToWrite = false;
67 for (auto& outobj : outputInputs) {
68 auto ds = dod->getDataOutputDescriptors(outobj);
69 if (ds.size() > 0) {
70 hasOutputsToWrite = true;
71 break;
72 }
73 }
74
75 // if nothing needs to be saved then return a trivial functor
76 // this happens when nothing needs to be saved but there are dangling outputs
77 if (!hasOutputsToWrite) {
78 return [](ProcessingContext&) mutable -> void {
79 static bool once = false;
80 if (!once) {
81 LOG(info) << "No AODs to be saved.";
82 once = true;
83 }
84 };
85 }
86
87 // end of data functor is called at the end of the data stream
88 auto endofdatacb = [dod](EndOfStreamContext& context) {
89 dod->closeDataFiles();
90 context.services().get<ControlService>().readyToQuit(QuitRequest::Me);
91 };
92
93 auto& callbacks = ic.services().get<CallbackService>();
94 callbacks.set<CallbackService::Id::EndOfStream>(endofdatacb);
95
96 // prepare map<uint64_t, uint64_t>(startTime, tfNumber)
97 std::map<uint64_t, uint64_t> tfNumbers;
98 std::map<uint64_t, std::string> tfFilenames;
99
100 std::vector<TString> aodMetaDataKeys;
101 std::vector<TString> aodMetaDataVals;
102
103 // this functor is called once per time frame
104 return [dod, tfNumbers, tfFilenames, aodMetaDataKeys, aodMetaDataVals, compressionLevel](ProcessingContext& pc) mutable -> void {
105 LOGP(debug, "======== getGlobalAODSink::processing ==========");
106 LOGP(debug, " processing data set with {} entries", pc.inputs().size());
107
108 // return immediately if pc.inputs() is empty. This should never happen!
109 if (pc.inputs().size() == 0) {
110 LOGP(info, "No inputs available!");
111 return;
112 }
113
114 // update tfNumbers
115 uint64_t startTime = 0;
116 uint64_t tfNumber = 0;
117 auto ref = pc.inputs().get("tfn");
118 if (ref.spec && ref.payload) {
119 startTime = DataRefUtils::getHeader<DataProcessingHeader*>(ref)->startTime;
120 tfNumber = pc.inputs().get<uint64_t>("tfn");
121 tfNumbers.insert(std::pair<uint64_t, uint64_t>(startTime, tfNumber));
122 }
123 // update tfFilenames
124 std::string aodInputFile;
125 auto ref2 = pc.inputs().get("tff");
126 if (ref2.spec && ref2.payload) {
127 startTime = DataRefUtils::getHeader<DataProcessingHeader*>(ref2)->startTime;
128 aodInputFile = pc.inputs().get<std::string>("tff");
129 tfFilenames.insert(std::pair<uint64_t, std::string>(startTime, aodInputFile));
130 }
131
132 // close all output files if one has reached size limit
133 dod->checkFileSizes();
134
135 // loop over the DataRefs which are contained in pc.inputs()
136 for (const auto& ref : pc.inputs()) {
137 if (!ref.spec) {
138 LOGP(debug, "Invalid input will be skipped!");
139 continue;
140 }
141
142 // get metadata
143 if (DataSpecUtils::partialMatch(*ref.spec, header::DataDescription("AODMetadataKeys"))) {
144 aodMetaDataKeys = pc.inputs().get<std::vector<TString>>(ref.spec->binding);
145 }
146 if (DataSpecUtils::partialMatch(*ref.spec, header::DataDescription("AODMetadataVals"))) {
147 aodMetaDataVals = pc.inputs().get<std::vector<TString>>(ref.spec->binding);
148 }
149
150 // skip non-AOD refs
151 if (!DataSpecUtils::partialMatch(*ref.spec, writableAODOrigins)) {
152 continue;
153 }
154 startTime = DataRefUtils::getHeader<DataProcessingHeader*>(ref)->startTime;
155
156 // does this need to be saved?
157 auto dh = DataRefUtils::getHeader<header::DataHeader*>(ref);
158 auto tableName = dh->dataDescription.as<std::string>();
159 auto ds = dod->getDataOutputDescriptors(*dh);
160 if (ds.empty()) {
161 continue;
162 }
163
164 // get TF number from startTime
165 auto it = tfNumbers.find(startTime);
166 if (it != tfNumbers.end()) {
167 tfNumber = (it->second / dod->getNumberTimeFramesToMerge()) * dod->getNumberTimeFramesToMerge();
168 } else {
169 LOGP(fatal, "No time frame number found for output with start time {}", startTime);
170 throw std::runtime_error("Processing is stopped!");
171 }
172 // get aod input file from startTime
173 auto it2 = tfFilenames.find(startTime);
174 if (it2 != tfFilenames.end()) {
175 aodInputFile = it2->second;
176 }
177
178 // get the TableConsumer and corresponding arrow table
179 auto msg = pc.inputs().get(ref.spec->binding);
180 if (msg.header == nullptr) {
181 LOGP(error, "No header for message {}:{}", ref.spec->binding, DataSpecUtils::describe(*ref.spec));
182 continue;
183 }
184 auto s = pc.inputs().get<TableConsumer>(ref.spec->binding);
185 auto table = s->asArrowTable();
186 if (!table->Validate().ok()) {
187 LOGP(warning, "The table \"{}\" is not valid and will not be saved!", tableName);
188 continue;
189 }
190 if (table->schema()->fields().empty()) {
191 LOGP(debug, "The table \"{}\" is empty but will be saved anyway!", tableName);
192 }
193
194 // loop over all DataOutputDescriptors
195 // a table can be saved in multiple ways
196 // e.g. different selections of columns to different files
197 for (auto d : ds) {
198 auto fileAndFolder = dod->getFileFolder(d, tfNumber, aodInputFile, compressionLevel);
199 auto treename = fileAndFolder.folderName + "/" + d->treename;
200 TableToTree ta2tr(table,
201 fileAndFolder.file,
202 treename.c_str());
203
204 // update metadata
205 if (fileAndFolder.file->FindObjectAny("metaData")) {
206 LOGF(debug, "Metadata: target file %s already has metadata, preserving it", fileAndFolder.file->GetName());
207 } else if (!aodMetaDataKeys.empty() && !aodMetaDataVals.empty()) {
208 TMap aodMetaDataMap;
209 for (uint32_t imd = 0; imd < aodMetaDataKeys.size(); imd++) {
210 aodMetaDataMap.Add(new TObjString(aodMetaDataKeys[imd]), new TObjString(aodMetaDataVals[imd]));
211 }
212 fileAndFolder.file->WriteObject(&aodMetaDataMap, "metaData", "Overwrite");
213 }
214
215 if (!d->colnames.empty()) {
216 for (auto& cn : d->colnames) {
217 auto idx = table->schema()->GetFieldIndex(cn);
218 auto col = table->column(idx);
219 auto field = table->schema()->field(idx);
220 if (idx != -1) {
221 ta2tr.addBranch(col, field);
222 }
223 }
224 } else {
225 ta2tr.addAllBranches();
226 }
227 ta2tr.process();
228 }
229 }
230 };
231 }
232
233 };
234}
235
237{
238 auto& ac = ctx.services().get<AnalysisContext>();
239 auto tskmap = ac.outTskMap;
240 auto objmap = ac.outObjHistMap;
241
242 return AlgorithmSpec{[objmap, tskmap](InitContext& ic) -> std::function<void(ProcessingContext&)> {
243 auto& callbacks = ic.services().get<CallbackService>();
244 auto inputObjects = std::make_shared<std::vector<std::pair<InputObjectRoute, InputObject>>>();
245
247 for (auto i = 0u; i < OutputObjHandlingPolicy::numPolicies; ++i) {
248 f[i] = nullptr;
249 }
250
251 static std::string currentDirectory = "";
252 static std::string currentFile = "";
253
254 auto endofdatacb = [inputObjects](EndOfStreamContext& context) {
255 LOG(debug) << "Writing merged objects and histograms to file";
256 if (inputObjects->empty()) {
257 LOG(error) << "Output object map is empty!";
258 context.services().get<ControlService>().readyToQuit(QuitRequest::Me);
259 return;
260 }
261 for (auto i = 0u; i < OutputObjHandlingPolicy::numPolicies; ++i) {
262 if (f[i] != nullptr) {
263 f[i]->Close();
264 }
265 }
266 LOG(debug) << "All outputs merged in their respective target files";
267 context.services().get<ControlService>().readyToQuit(QuitRequest::Me);
268 };
269
270 callbacks.set<CallbackService::Id::EndOfStream>(endofdatacb);
271 return [inputObjects, objmap, tskmap](ProcessingContext& pc) mutable -> void {
272 auto const& ref = pc.inputs().get("x");
273 if (!ref.header) {
274 LOG(error) << "Header not found";
275 return;
276 }
277 auto datah = o2::header::get<o2::header::DataHeader*>(ref.header);
278 if (!datah) {
279 LOG(error) << "No data header in stack";
280 return;
281 }
282
283 if (!ref.payload) {
284 LOGP(error, "Payload not found for {}/{}/{}", datah->dataOrigin.as<std::string>(), datah->dataDescription.as<std::string>(), datah->subSpecification);
285 return;
286 }
287
288 auto objh = o2::header::get<o2::framework::OutputObjHeader*>(ref.header);
289 if (!objh) {
290 LOGP(error, "No output object header in stack of {}/{}/{}", datah->dataOrigin.as<std::string>(), datah->dataDescription.as<std::string>(), datah->subSpecification);
291 return;
292 }
293
294 InputObject obj;
295 FairInputTBuffer tm(const_cast<char*>(ref.payload), static_cast<int>(datah->payloadSize));
296 tm.InitMap();
297 obj.kind = tm.ReadClass();
298 tm.SetBufferOffset(0);
299 tm.ResetMap();
300 if (obj.kind == nullptr) {
301 LOGP(error, "Cannot read class info from buffer of {}/{}/{}", datah->dataOrigin.as<std::string>(), datah->dataDescription.as<std::string>(), datah->subSpecification);
302 return;
303 }
304
305 auto policy = objh->mPolicy;
306 auto sourceType = objh->mSourceType;
307 auto hash = objh->mTaskHash;
308
309 obj.obj = tm.ReadObjectAny(obj.kind);
310 auto* named = static_cast<TNamed*>(obj.obj);
311 obj.name = named->GetName();
312 auto hpos = std::find_if(tskmap.begin(), tskmap.end(), [&](auto&& x) { return x.id == hash; });
313 if (hpos == tskmap.end()) {
314 LOG(error) << "No task found for hash " << hash;
315 return;
316 }
317 auto taskname = hpos->name;
318 auto opos = std::find_if(objmap.begin(), objmap.end(), [&](auto&& x) { return x.id == hash; });
319 if (opos == objmap.end()) {
320 LOG(error) << "No object list found for task " << taskname << " (hash=" << hash << ")";
321 return;
322 }
323 auto objects = opos->bindings;
324 if (std::find(objects.begin(), objects.end(), obj.name) == objects.end()) {
325 LOG(error) << "No object " << obj.name << " in map for task " << taskname;
326 return;
327 }
328 auto nameHash = runtime_hash(obj.name.c_str());
329 InputObjectRoute key{obj.name, nameHash, taskname, hash, policy, sourceType};
330 auto existing = std::find_if(inputObjects->begin(), inputObjects->end(), [&](auto&& x) { return (x.first.uniqueId == nameHash) && (x.first.taskHash == hash); });
331 // If it's the first one, we just add it to the list.
332 if (existing == inputObjects->end()) {
333 obj.count = objh->mPipelineSize;
334 inputObjects->push_back(std::make_pair(key, obj));
335 existing = inputObjects->end() - 1;
336 } else {
337 obj.count = existing->second.count;
338 // Otherwise, we merge it with the existing one.
339 auto merger = existing->second.kind->GetMerge();
340 if (!merger) {
341 LOG(error) << "Already one unmergeable object found for " << obj.name;
342 return;
343 }
344 TList coll;
345 coll.Add(static_cast<TObject*>(obj.obj));
346 merger(existing->second.obj, &coll, nullptr);
347 }
348 // We expect as many objects as the pipeline size, for
349 // a given object name and task hash.
350 existing->second.count -= 1;
351
352 if (existing->second.count != 0) {
353 return;
354 }
355 // Write the object here.
356 auto route = existing->first;
357 auto entry = existing->second;
358 auto file = ROOTfileNames.find(route.policy);
359 if (file == ROOTfileNames.end()) {
360 return;
361 }
362 auto filename = file->second;
363 if (f[route.policy] == nullptr) {
364 f[route.policy] = TFile::Open(filename.c_str(), "RECREATE");
365 }
366 auto nextDirectory = route.directory;
367 if ((nextDirectory != currentDirectory) || (filename != currentFile)) {
368 if (!f[route.policy]->FindKey(nextDirectory.c_str())) {
369 f[route.policy]->mkdir(nextDirectory.c_str());
370 }
371 currentDirectory = nextDirectory;
372 currentFile = filename;
373 }
374
375 // translate the list-structure created by the registry into a directory structure within the file
376 std::function<void(TList*, TDirectory*)> writeListToFile;
377 writeListToFile = [&](TList* list, TDirectory* parentDir) {
378 TIter next(list);
379 TObject* object = nullptr;
380 while ((object = next())) {
381 if (object->InheritsFrom(TList::Class())) {
382 writeListToFile(static_cast<TList*>(object), parentDir->mkdir(object->GetName(), object->GetName(), true));
383 } else {
384 parentDir->WriteObjectAny(object, object->Class(), object->GetName());
385 auto* written = list->Remove(object);
386 delete written;
387 }
388 }
389 };
390
391 TDirectory* currentDir = f[route.policy]->GetDirectory(currentDirectory.c_str());
392 if (route.sourceType == OutputObjSourceType::HistogramRegistrySource) {
393 auto* outputList = static_cast<TList*>(entry.obj);
394 outputList->SetOwner(false);
395
396 // if registry should live in dedicated folder a TNamed object is appended to the list
397 if (outputList->Last() && outputList->Last()->IsA() == TNamed::Class()) {
398 delete outputList->Last();
399 outputList->RemoveLast();
400 currentDir = currentDir->mkdir(outputList->GetName(), outputList->GetName(), true);
401 }
402
403 writeListToFile(outputList, currentDir);
404 outputList->SetOwner();
405 delete outputList;
406 entry.obj = nullptr;
407 } else {
408 currentDir->WriteObjectAny(entry.obj, entry.kind, entry.name.c_str());
409 delete (TObject*)entry.obj;
410 entry.obj = nullptr;
411 }
412 };
413 }};
414}
415} // namespace o2::framework::writers
std::vector< std::string > objects
int32_t i
uint32_t col
Definition RawData.h:4
constexpr uint32_t runtime_hash(char const *str)
std::ostringstream debug
StringRef key
ServiceRegistryRef services() const
ConfigParamRegistry & options() const
bool hasOption(const char *key) const
void addBranch(std::shared_ptr< arrow::ChunkedArray > const &column, std::shared_ptr< arrow::Field > const &field)
std::shared_ptr< TTree > process()
GLint GLenum GLint x
Definition glcorearb.h:403
GLint GLsizei count
Definition glcorearb.h:399
GLuint entry
Definition glcorearb.h:5735
GLdouble f
Definition glcorearb.h:310
typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode)
GLuint object
Definition glcorearb.h:4041
@ Me
Only quit this data processor.
OutputObjHandlingPolicy
Policy enum to determine OutputObj handling when writing.
std::string filename()
Definition list.h:40
std::vector< OutputTaskInfo > outTskMap
std::vector< InputSpec > outputsInputsAOD
static std::shared_ptr< DataOutputDirector > getDataOutputDirector(ConfigContext const &ctx)
Get the data director.
static bool partialMatch(InputSpec const &spec, o2::header::DataOrigin const &origin)
static std::string describe(InputSpec const &spec)
static AlgorithmSpec getOutputObjHistWriter(ConfigContext const &context)
static AlgorithmSpec getOutputTTreeWriter(ConfigContext const &context)
o2::mch::DsIndex ds
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"
uint64_t const void const *restrict const msg
Definition x9.h:153