-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathSubTimeFrameFileSource.cxx
More file actions
535 lines (439 loc) · 18.6 KB
/
SubTimeFrameFileSource.cxx
File metadata and controls
535 lines (439 loc) · 18.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
// Copyright 2019-2022 CERN and copyright holders of ALICE O2.
// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
// All rights not expressly granted are reserved.
//
// This software is distributed under the terms of the GNU General Public
// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
/// \author Gvozden Nešković, Frankfurt Institute for Advanced Studies and Goethe University Frankfurt
#include "SubTimeFrameFileSource.h"
#include "SubTimeFrameFileReader.h"
#include "FilePathUtils.h"
#include "DataDistLogger.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/filesystem.hpp>
#include <boost/process/v1.hpp>
#include <boost/process/v1/child.hpp>
#include <boost/process/v1/search_path.hpp>
#include <boost/process/v1/io.hpp>
#include <chrono>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <future>
namespace o2::DataDistribution
{
namespace bpo = boost::program_options;
namespace bfs = boost::filesystem;
namespace bp = boost::process;
using namespace std::chrono_literals;
////////////////////////////////////////////////////////////////////////////////
/// SubTimeFrameFileSource
////////////////////////////////////////////////////////////////////////////////
std::mutex SubTimeFrameFileSource::StfFileMeta::sLiveFilesLock;
std::map<std::size_t, std::shared_ptr<SubTimeFrameFileSource::StfFileMeta>> SubTimeFrameFileSource::StfFileMeta::mLiveFiles;
void SubTimeFrameFileSource::start(SyncMemoryResources &pMemRes)
{
if (enabled()) {
mFileBuilder = std::make_unique<SubTimeFrameFileBuilder>(
pMemRes,
mRegionSizeMB << 20, mTfDataRegionId,
mHdrRegionSizeMB << 20, mTfHdrRegionId
);
mRunning = true;
mFetchThread = create_thread_member("stf_file_fetch", &SubTimeFrameFileSource::DataFetcherThread, this);
mSourceThread = create_thread_member("stf_file_read", &SubTimeFrameFileSource::DataHandlerThread, this);
mInjectThread = create_thread_member("stf_file_inject", &SubTimeFrameFileSource::DataInjectThread, this);
}
}
void SubTimeFrameFileSource::stop()
{
mRunning = false;
if (mFileBuilder) {
mFileBuilder->stop();
}
mInputFileQueue.stop();
mReadStfQueue.stop();
mReadStfQueue.flush();
if (mFetchThread.joinable()) {
mFetchThread.join();
}
if (mSourceThread.joinable()) {
mSourceThread.join();
}
if (mInjectThread.joinable()) {
mInjectThread.join();
}
// make sure we delete the cache
if (!mLocalFiles && boost::contains(mCopyDstPath.native(), "dd-tmp-tfs")) {
try {
bfs::remove_all(mCopyDstPath);
} catch (...) {
WDDLOG("(Sub)TimeFrame file source: could not remove tf file cache. directory={}", mCopyDstPath.native());
}
}
}
bpo::options_description SubTimeFrameFileSource::getProgramOptions()
{
bpo::options_description lSinkDesc("(Sub)TimeFrame file source options", 120);
lSinkDesc.add_options()(
OptionKeyStfSourceEnable,
bpo::bool_switch()->default_value(false),
"Enable reading of (Sub)TimeFrames from files.")(
OptionKeyStfSourceDir,
bpo::value<std::string>()->default_value(""),
"Specifies the source directory where (Sub)TimeFrame files are located. "
"Note: Only (Sub)TimeFrame data files are allowed in this directory.")(
OptionKeyStfLoadRate,
bpo::value<double>()->default_value(1.0),
"Rate of injecting new (Sub)TimeFrames (approximate). -1 to inject as fast as possible.")(
OptionKeyStfLoadPreRead,
bpo::value<std::uint32_t>()->default_value(1),
"Number of pre-read (Sub)TimeFrames prepared for sending. Must be greater or equal to 1.")(
OptionKeyStfSourceRepeat,
bpo::bool_switch()->default_value(false),
"If enabled, repeatedly inject (Sub)TimeFrames into the chain.")(
OptionKeyStfSourceRegionSize,
bpo::value<std::uint64_t>()->default_value(1024),
"Size of the memory region for (Sub)TimeFrames data in MiB. "
"Note: make sure the region can fit several (Sub)TimeFrames to avoid deadlocks.")(
OptionKeyStfSourceRegionId,
bpo::value<std::uint16_t>()->default_value(std::uint16_t(~0)),
"Optional shm id for reusing existing TimeFrame regions. (default will create a new region)")(
OptionKeyStfHeadersRegionSize,
bpo::value<std::uint64_t>()->default_value(256),
"Size of the memory region for (Sub)TimeFrames O2 headers in MiB. "
"Note: make sure the region can fit several (Sub)TimeFrames to avoid deadlocks.")(
OptionKeyStfHeadersRegionId,
bpo::value<std::uint16_t>()->default_value(std::uint16_t(~0)),
"Optional shm id for reusing existing TimeFrame header region. (default will create a new region)")(
OptionKeyStfFileList,
bpo::value<std::string>()->default_value(""),
"File name which contains the list of files at remote location, e.g. a list of files on EOS, or a remote server. "
"Note: the copy command must be provided.")(
OptionKeyStfCopyCmd,
bpo::value<std::string>()->default_value(""),
"Copy command to be used to fetch remote files. NOTE: Placeholders for source and destination file name "
"(?src and ?dst) must be specified. E.g. \"scp user@my-server:?src ?dst\". Source placeholder will be "
"substituted with files provided in the file-list option.");
return lSinkDesc;
}
std::vector<std::string> SubTimeFrameFileSource::getDataFileList() const
{
// Load the sorted list of StfFiles
auto lFilesVector = FilePathUtils::getAllFiles(mDir);
// Remove side-car files
auto lRemIt = std::remove_if(lFilesVector.begin(), lFilesVector.end(),
[](const std::string &lElem) {
const auto lFileName = bfs::path(lElem).filename().native();
bool lToRemove = !boost::ends_with(lFileName, ".tf") || boost::starts_with(lFileName, ".");
DDDLOG("Checking if should remove file: {} ? {}", lFileName, (lToRemove ? "yes" : "no"));
return lToRemove;
}
);
lFilesVector.erase(lRemIt, lFilesVector.end());
return lFilesVector;
}
bool SubTimeFrameFileSource::loadVerifyConfig(const fair::mq::ProgOptions& pFMQProgOpt)
{
mEnabled = pFMQProgOpt.GetValue<bool>(OptionKeyStfSourceEnable);
IDDLOG("(Sub)TimeFrame file source is {}", (mEnabled ? "enabled." : "disabled."));
if (!mEnabled) {
return true;
}
mDir = pFMQProgOpt.GetValue<std::string>(OptionKeyStfSourceDir);
if (!mDir.empty()) {
// make sure directory exists and it is readable
bfs::path lDirPath(mDir);
if (!bfs::is_directory(lDirPath)) {
EDDLOG("(Sub)TimeFrame file source directory does not exist.");
return false;
}
}
mRepeat = pFMQProgOpt.GetValue<bool>(OptionKeyStfSourceRepeat);
mLoadRate = pFMQProgOpt.GetValue<double>(OptionKeyStfLoadRate);
mPreReadStfs = pFMQProgOpt.GetValue<std::uint32_t>(OptionKeyStfLoadPreRead);
mRegionSizeMB = pFMQProgOpt.GetValue<std::uint64_t>(OptionKeyStfSourceRegionSize);
mTfDataRegionId = pFMQProgOpt.GetValue<std::uint16_t>(OptionKeyStfSourceRegionId);
if (mTfDataRegionId.value() == std::uint16_t(~0)) {
mTfDataRegionId = std::nullopt;
}
mHdrRegionSizeMB = pFMQProgOpt.GetValue<std::uint64_t>(OptionKeyStfHeadersRegionSize);
mTfHdrRegionId = pFMQProgOpt.GetValue<std::uint16_t>(OptionKeyStfHeadersRegionId);
if (mTfHdrRegionId.value() == std::uint16_t(~0)) {
mTfHdrRegionId = std::nullopt;
}
mCopyFileList = pFMQProgOpt.GetValue<std::string>(OptionKeyStfFileList);
mCopyCmd = pFMQProgOpt.GetValue<std::string>(OptionKeyStfCopyCmd);
// initialize file fetcher
if (!mCopyFileList.empty() && !mCopyCmd.empty()) {
if (!mDir.empty()) {
EDDLOG("(Sub)TimeFrame file source: specifying both the directory, and the file copy options is not supported.");
return false;
}
mLocalFiles = false;
try {
// check copy command
if (!boost::contains(mCopyCmd, "?src") || !boost::contains(mCopyCmd, "?dst")) {
EDDLOG("(Sub)TimeFrame file source: copy command does not containt ?src and ?dst placeholders.");
return false;
}
// check copy file list
bfs::path lFileList(mCopyFileList);
if (!bfs::is_regular_file(lFileList) || bfs::is_empty(lFileList)) {
EDDLOG("(Sub)TimeFrame file source: File list does not exist or empty");
return false;
}
// load the file list
std::ifstream lCopyFile(mCopyFileList);
if (!lCopyFile) {
EDDLOG("(Sub)TimeFrame file source: cannot open {}.", mCopyFileList);
return false;
}
mFilesVector.clear();
std::string lLine;
while (std::getline(lCopyFile, lLine)) {
boost::algorithm::trim(lLine);
if (lLine.empty()) {
continue;
}
mFilesVector.push_back(std::move(lLine));
}
if (mFilesVector.empty()) {
EDDLOG("(Sub)TimeFrame file source: no files found in {}.", mCopyFileList);
return false;
}
const auto lCopyDstPath = bfs::temp_directory_path() / "dd-tmp-tfs" / bfs::unique_path("%%%%");
bfs::create_directories(lCopyDstPath);
mCopyDstPath = lCopyDstPath.native();
// location of log file
mCopyCmdLogFile = (lCopyDstPath / "copy-cmd.log").native();
} catch (...) {
EDDLOG("(Sub)TimeFrame file source: setting up file copy failed. Check the provided options.");
return false;
}
} else if (!mDir.empty()) {
// Local directory files
mLocalFiles = true;
mFilesVector = getDataFileList();
if (mFilesVector.empty()) {
EDDLOG("(Sub)TimeFrame directory contains no data files.");
return false;
}
} else {
EDDLOG("(Sub)TimeFrame file source: TF location not specified.");
return false;
}
if (mRegionSizeMB <= 0 || mHdrRegionSizeMB <= 0) {
EDDLOG("(Sub)TimeFrame region sizes must not be zero.");
return false;
}
if (mPreReadStfs == 0) {
EDDLOG("Number of pre-read (Sub)TimeFrame must be >= 1.");
return false;
}
{
const auto lTfFilesVar = getenv("DATADIST_FILE_READ_COUNT");
if (lTfFilesVar) {
try {
const auto lTfFilesNum = std::stol(lTfFilesVar);
if (lTfFilesNum == 0) {
WDDLOG("(Sub)TimeFrame source: DATADIST_FILE_READ_COUNT must be greater than 0.");
return false;
}
mRepeat = true;
mNumFiles = lTfFilesNum;
WDDLOG("(Sub)TimeFrame source: DATADIST_FILE_READ_COUNT is set to {}.", lTfFilesNum);
} catch (...) {
EDDLOG("(Sub)TimeFrame source: DATADIST_FILE_READ_COUNT must be greater than 0. DATADIST_FILE_READ_COUNT={}",
lTfFilesVar);
}
}
}
// print options
IDDLOG("(Sub)TimeFrame source :: enabled = {}", (mEnabled ? "yes" : "no"));
IDDLOG("(Sub)TimeFrame source :: file location = {}", (mLocalFiles ? "local" : "remote"));
if (mLocalFiles) {
IDDLOG("(Sub)TimeFrame source :: directory = {}", mDir);
} else {
IDDLOG("(Sub)TimeFrame source :: file list = {}", mCopyFileList);
IDDLOG("(Sub)TimeFrame source :: copy command = {}", mCopyCmd);
}
IDDLOG("(Sub)TimeFrame source :: (s)tf load rate = {}", mLoadRate);
IDDLOG("(Sub)TimeFrame source :: (s)tf pre reads = {}", mPreReadStfs);
IDDLOG("(Sub)TimeFrame source :: repeat data = {}", mRepeat);
IDDLOG("(Sub)TimeFrame source :: num files in dataset = {}", mFilesVector.size());
IDDLOG("(Sub)TimeFrame source :: data region id = {}", mTfDataRegionId.has_value() ? std::to_string(mTfDataRegionId.value()) : "");
IDDLOG("(Sub)TimeFrame source :: data region size(MiB) = {}", mRegionSizeMB);
IDDLOG("(Sub)TimeFrame source :: header region id = {}", mTfHdrRegionId.has_value() ? std::to_string(mTfHdrRegionId.value()) : "");
IDDLOG("(Sub)TimeFrame source :: header region size(MiB) = {}", mHdrRegionSizeMB);
return true;
}
// Fetch copy files if needed
void SubTimeFrameFileSource::DataFetcherThread()
{
std::size_t lFileIndex = std::size_t(-1);
std::uint64_t lFileErrors = 0;
std::uint64_t lTotalFiles = 0;
std::uint64_t lTotalSuccessfulFiles = 0;
while (mRunning && lFileErrors < 10) {
if (mInputFileQueue.size() > 4) {
std::this_thread::sleep_for(5ms);
continue;
}
// get the next list
if (lTotalFiles >= mFilesVector.size() && !mRepeat) {
IDDLOG("(Sub)TimeFrame source: finished loading all files. Waiting for injecting to complete.");
break;
}
// make sure we progress on errors
lFileIndex = (lFileIndex + 1) % mFilesVector.size();
lTotalFiles++;
if (mLocalFiles) {
// simply forward
mInputFileQueue.push(std::make_shared<StfFileMeta>(lFileIndex, mFilesVector[lFileIndex]));
} else {
// check if the file already exists in the cache
auto lExisting = StfFileMeta::getExistingInstance(lFileIndex);
if (lExisting) {
mInputFileQueue.push(lExisting.value());
} else {
// run the copy command
const auto lDstFileName = mCopyDstPath /
("cache-" + std::to_string(lFileIndex) + "-" + bfs::path(mFilesVector[lFileIndex]).filename().native());
auto lRealCmd = boost::replace_all_copy(mCopyCmd, "?src", mFilesVector[lFileIndex]);
boost::replace_all(lRealCmd, "?dst", lDstFileName.native());
std::vector<std::string> lCopyParams { "-c", lRealCmd };
bp::v1::child lCopyChild(bp::v1::search_path("sh"), lCopyParams, bp::v1::std_err > mCopyCmdLogFile,
bp::v1::std_out > mCopyCmdLogFile);
// Report progress every 5 seconds
for (auto lCopyChildFuture = std::async(std::launch::async, [&]() { lCopyChild.wait(); });
std::future_status::timeout == lCopyChildFuture.wait_for(5s); ) {
IDDLOG("(Sub)TimeFrame source: waiting for copy command. cmd='{}'", lRealCmd);
}
const auto lSysRet = lCopyChild.exit_code();
if (lSysRet != 0) {
WDDLOG_RL(1000, "(Sub)TimeFrame source: copy command returned non-zero exit code. cmd='{}' exit_code={}",
lRealCmd, lSysRet);
}
if (!bfs::is_regular_file(lDstFileName) || bfs::is_empty(lDstFileName)) {
EDDLOG("(Sub)TimeFrame source: copy command failed to fetch the file. stc_file={} dst_file={}.",
mFilesVector[lFileIndex], lDstFileName.native());
lFileErrors++;
continue;
}
auto lNewFile = std::make_shared<StfFileMeta>(lFileIndex, lDstFileName.native(), true /* delete after done */);
StfFileMeta::insertExistingInstance(lFileIndex, lNewFile);
mInputFileQueue.push(lNewFile);
}
}
lTotalSuccessfulFiles++;
// check if we are done because of DATADIST_FILE_READ_COUNT
if (mNumFiles > 0 && lTotalSuccessfulFiles == mNumFiles) {
IDDLOG("(Sub)TimeFrame source: finished loading all files. DATADIST_FILE_READ_COUNT={}", mNumFiles);
break;
}
}
// close the file queue to signal the next thread to exit
mInputFileQueue.stop();
DDDLOG("Exiting file provider thread...");
}
/// File reading thread
void SubTimeFrameFileSource::DataHandlerThread()
{
// inject rate
const std::chrono::microseconds lIntervalUs(mLoadRate > 0. ? unsigned(1000000. / mLoadRate) : 0);
while (mRunning) {
std::shared_ptr<StfFileMeta> lMyFile;
if (!mRunning || !mInputFileQueue.pop(lMyFile)) {
IDDLOG("(Sub)TimeFrame Source: Finished reading all input files. Exiting...");
break;
}
assert(lMyFile);
DDDLOG_RL(5000, "(Sub)TimeFrame Source: reading new file={}", lMyFile->mFilePath);
auto lFileNameAbs = bfs::path(lMyFile->mFilePath);
SubTimeFrameFileReader lStfReader(lFileNameAbs);
try {
// load multiple TF per file
while (mRunning) {
// read STF from file
auto lStfPtr = lStfReader.read(*mFileBuilder);
if (mRunning && lStfPtr) {
// adapt Stf headers for different output channels, native or DPL
mFileBuilder->adaptHeaders(lStfPtr.get());
if (!mReadStfQueue.push(std::move(lStfPtr))) {
break;
}
} else {
// bad file?
break; // EOF or !running
}
// Limit read-ahead
while (mRunning && (mReadStfQueue.size() >= mPreReadStfs)) {
std::this_thread::sleep_for(mPaused ? lIntervalUs : (lIntervalUs / 10));
}
}
} catch (...) {
EDDLOG("(Sub)TimeFrame Source: error while reading (S)TFs from file. file={} file_idx={}",
lMyFile->mFilePath, lMyFile->mIdx);
}
// make sure we release the file first befor put call
const auto lIdx = lMyFile->mIdx;
lMyFile.reset();
StfFileMeta::putExistingInstance(lIdx);
}
// notify the injection thread to stop
mReadStfQueue.stop();
DDDLOG("Exiting file source data load thread...");
}
/// STF injecting thread
void SubTimeFrameFileSource::DataInjectThread()
{
const std::chrono::microseconds lIntervalUs(mLoadRate > 0. ? unsigned(1000000. / mLoadRate) : 0);
IDDLOG("(Sub)TimeFrame Source: Injecting new STF every {} us", lIntervalUs.count());
static double sNumSentStfs = 1;
while (mRunning) {
// Get the next STF
std::unique_ptr<SubTimeFrame> lStf;
if (!mReadStfQueue.pop(lStf)) {
break;
}
static auto sRateStartTime = std::chrono::high_resolution_clock::now();
while (mRunning && mPaused) {
std::this_thread::sleep_for(200ms);
// reset the rate stats
sRateStartTime = std::chrono::high_resolution_clock::now();
sNumSentStfs = 1;
}
mPipelineI.queue(mPipelineStageOut, std::move(lStf));
sNumSentStfs++;
auto getElapsedTime = []() {
return std::max(1e-6, std::chrono::duration<double>(std::chrono::high_resolution_clock::now() -
sRateStartTime).count());
};
// rate limiting
// calculate absolute times from the start to avoid skewing the rate over time
while(mRunning) {
const double lSecSinceStart = getElapsedTime();
const double lSecNext = sNumSentStfs / mLoadRate;
// check if we're done waiting
if ((lSecNext - lSecSinceStart) < 0.001) {
break;
}
// limit sleep time to 0.5s in order to be able to check for exit signal
auto lWaitTime = std::clamp((lSecNext - lSecSinceStart) * 3. / 5., 0.001, 0.5);
std::this_thread::sleep_for(std::chrono::duration<double>(lWaitTime));
}
DDDLOG_RL(2000, "SubTimeFrameFileSource prepared_tfs={} inject_rate={:.4f}",
mReadStfQueue.size(), sNumSentStfs / getElapsedTime());
}
mPipelineI.close(mPipelineStageOut);
DDDLOG("Exiting file source inject thread...");
}
} /* o2::DataDistribution */