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 if (!ref.payload) {
278 LOG(error) << "Payload not found";
279 return;
280 }
281 auto datah = o2::header::get<o2::header::DataHeader*>(ref.header);
282 if (!datah) {
283 LOG(error) << "No data header in stack";
284 return;
285 }
286
287 auto objh = o2::header::get<o2::framework::OutputObjHeader*>(ref.header);
288 if (!objh) {
289 LOG(error) << "No output object header in stack";
290 return;
291 }
292
293 InputObject obj;
294 FairInputTBuffer tm(const_cast<char*>(ref.payload), static_cast<int>(datah->payloadSize));
295 tm.InitMap();
296 obj.kind = tm.ReadClass();
297 tm.SetBufferOffset(0);
298 tm.ResetMap();
299 if (obj.kind == nullptr) {
300 LOG(error) << "Cannot read class info from buffer.";
301 return;
302 }
303
304 auto policy = objh->mPolicy;
305 auto sourceType = objh->mSourceType;
306 auto hash = objh->mTaskHash;
307
308 obj.obj = tm.ReadObjectAny(obj.kind);
309 auto* named = static_cast<TNamed*>(obj.obj);
310 obj.name = named->GetName();
311 auto hpos = std::find_if(tskmap.begin(), tskmap.end(), [&](auto&& x) { return x.id == hash; });
312 if (hpos == tskmap.end()) {
313 LOG(error) << "No task found for hash " << hash;
314 return;
315 }
316 auto taskname = hpos->name;
317 auto opos = std::find_if(objmap.begin(), objmap.end(), [&](auto&& x) { return x.id == hash; });
318 if (opos == objmap.end()) {
319 LOG(error) << "No object list found for task " << taskname << " (hash=" << hash << ")";
320 return;
321 }
322 auto objects = opos->bindings;
323 if (std::find(objects.begin(), objects.end(), obj.name) == objects.end()) {
324 LOG(error) << "No object " << obj.name << " in map for task " << taskname;
325 return;
326 }
327 auto nameHash = runtime_hash(obj.name.c_str());
328 InputObjectRoute key{obj.name, nameHash, taskname, hash, policy, sourceType};
329 auto existing = std::find_if(inputObjects->begin(), inputObjects->end(), [&](auto&& x) { return (x.first.uniqueId == nameHash) && (x.first.taskHash == hash); });
330 // If it's the first one, we just add it to the list.
331 if (existing == inputObjects->end()) {
332 obj.count = objh->mPipelineSize;
333 inputObjects->push_back(std::make_pair(key, obj));
334 existing = inputObjects->end() - 1;
335 } else {
336 obj.count = existing->second.count;
337 // Otherwise, we merge it with the existing one.
338 auto merger = existing->second.kind->GetMerge();
339 if (!merger) {
340 LOG(error) << "Already one unmergeable object found for " << obj.name;
341 return;
342 }
343 TList coll;
344 coll.Add(static_cast<TObject*>(obj.obj));
345 merger(existing->second.obj, &coll, nullptr);
346 }
347 // We expect as many objects as the pipeline size, for
348 // a given object name and task hash.
349 existing->second.count -= 1;
350
351 if (existing->second.count != 0) {
352 return;
353 }
354 // Write the object here.
355 auto route = existing->first;
356 auto entry = existing->second;
357 auto file = ROOTfileNames.find(route.policy);
358 if (file == ROOTfileNames.end()) {
359 return;
360 }
361 auto filename = file->second;
362 if (f[route.policy] == nullptr) {
363 f[route.policy] = TFile::Open(filename.c_str(), "RECREATE");
364 }
365 auto nextDirectory = route.directory;
366 if ((nextDirectory != currentDirectory) || (filename != currentFile)) {
367 if (!f[route.policy]->FindKey(nextDirectory.c_str())) {
368 f[route.policy]->mkdir(nextDirectory.c_str());
369 }
370 currentDirectory = nextDirectory;
371 currentFile = filename;
372 }
373
374 // translate the list-structure created by the registry into a directory structure within the file
375 std::function<void(TList*, TDirectory*)> writeListToFile;
376 writeListToFile = [&](TList* list, TDirectory* parentDir) {
377 TIter next(list);
378 TObject* object = nullptr;
379 while ((object = next())) {
380 if (object->InheritsFrom(TList::Class())) {
381 writeListToFile(static_cast<TList*>(object), parentDir->mkdir(object->GetName(), object->GetName(), true));
382 } else {
383 parentDir->WriteObjectAny(object, object->Class(), object->GetName());
384 auto* written = list->Remove(object);
385 delete written;
386 }
387 }
388 };
389
390 TDirectory* currentDir = f[route.policy]->GetDirectory(currentDirectory.c_str());
391 if (route.sourceType == OutputObjSourceType::HistogramRegistrySource) {
392 auto* outputList = static_cast<TList*>(entry.obj);
393 outputList->SetOwner(false);
394
395 // if registry should live in dedicated folder a TNamed object is appended to the list
396 if (outputList->Last() && outputList->Last()->IsA() == TNamed::Class()) {
397 delete outputList->Last();
398 outputList->RemoveLast();
399 currentDir = currentDir->mkdir(outputList->GetName(), outputList->GetName(), true);
400 }
401
402 writeListToFile(outputList, currentDir);
403 outputList->SetOwner();
404 delete outputList;
405 entry.obj = nullptr;
406 } else {
407 currentDir->WriteObjectAny(entry.obj, entry.kind, entry.name.c_str());
408 delete (TObject*)entry.obj;
409 entry.obj = nullptr;
410 }
411 };
412 }};
413}
414} // 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