16 #include <boost/algorithm/string.hpp> 53 defPath_(
pset.getUntrackedParameter<
std::
string>(
"buDefPath",
"")),
54 eventChunkSize_(
pset.getUntrackedParameter<unsigned
int>(
"eventChunkSize", 32) * 1048576),
55 eventChunkBlock_(
pset.getUntrackedParameter<unsigned
int>(
"eventChunkBlock", 32) * 1048576),
56 numBuffers_(
pset.getUntrackedParameter<unsigned
int>(
"numBuffers", 2)),
57 maxBufferedFiles_(
pset.getUntrackedParameter<unsigned
int>(
"maxBufferedFiles", 2)),
58 getLSFromFilename_(
pset.getUntrackedParameter<
bool>(
"getLSFromFilename",
true)),
59 alwaysStartFromFirstLS_(
pset.getUntrackedParameter<
bool>(
"alwaysStartFromFirstLS",
false)),
60 verifyChecksum_(
pset.getUntrackedParameter<
bool>(
"verifyChecksum",
true)),
61 useL1EventID_(
pset.getUntrackedParameter<
bool>(
"useL1EventID",
false)),
65 fileListMode_(
pset.getUntrackedParameter<
bool>(
"fileListMode",
false)),
66 fileListLoopMode_(
pset.getUntrackedParameter<
bool>(
"fileListLoopMode",
false)),
71 currentLumiSection_(0),
72 tcds_pointer_(nullptr),
75 gethostname(thishost, 255);
76 edm::LogInfo(
"FedRawDataInputSource") <<
"Construction. read-ahead chunk size -: " << std::endl
81 throw cms::Exception(
"FedRawDataInputSource::fillFEDRawDataCollection")
82 <<
"Invalid TCDS Test FED range parameter";
88 long autoRunNumber = -1;
92 if (autoRunNumber < 0)
93 throw cms::Exception(
"FedRawDataInputSource::FedRawDataInputSource") <<
"Run number not found from filename";
112 throw cms::Exception(
"FedRawDataInputSource::FedRawDataInputSource")
113 <<
"no reading enabled with numBuffers parameter 0";
120 edm::LogError(
"FedRawDataInputSource::FedRawDataInputSource") <<
"Intel crc32c checksum computation unavailable";
127 edm::LogInfo(
"FedRawDataInputSource") <<
"No FastMonitoringService found in the configuration";
132 throw cms::Exception(
"FedRawDataInputSource") <<
"FastMonitoringService not found";
138 cms::Exception(
"FedRawDataInputSource") <<
"EvFDaqDirector not found";
142 edm::LogInfo(
"FedRawDataInputSource") <<
"EvFDaqDirector/Source configured to use file service";
162 cvReader_.push_back(std::make_unique<std::condition_variable>());
189 it->second->unsetDeleteFile();
204 std::unique_lock<std::mutex> lk(
mReader_);
216 desc.setComment(
"File-based Filter Farm input source for reading raw data from BU ramdisk");
217 desc.addUntracked<
unsigned int>(
"eventChunkSize", 32)->setComment(
"Input buffer (chunk) size");
218 desc.addUntracked<
unsigned int>(
"eventChunkBlock", 32)
219 ->setComment(
"Block size used in a single file read call (must be smaller or equal to buffer size)");
220 desc.addUntracked<
unsigned int>(
"numBuffers", 2)->setComment(
"Number of buffers used for reading input");
221 desc.addUntracked<
unsigned int>(
"maxBufferedFiles", 2)
222 ->setComment(
"Maximum number of simultaneously buffered raw files");
223 desc.addUntracked<
unsigned int>(
"alwaysStartFromfirstLS",
false)
224 ->setComment(
"Force source to start from LS 1 if server provides higher lumisection number");
225 desc.addUntracked<
bool>(
"verifyChecksum",
true)
226 ->setComment(
"Verify event CRC-32C checksum of FRDv5 and higher or Adler32 with v3 and v4");
227 desc.addUntracked<
bool>(
"useL1EventID",
false)
228 ->setComment(
"Use L1 event ID from FED header if true or from TCDS FED if false");
229 desc.addUntracked<std::vector<unsigned int>>(
"testTCDSFEDRange", std::vector<unsigned int>())
230 ->setComment(
"[min, max] range to search for TCDS FED ID in test setup");
231 desc.addUntracked<
bool>(
"fileListMode",
false)
232 ->setComment(
"Use fileNames parameter to directly specify raw files to open");
233 desc.addUntracked<std::vector<std::string>>(
"fileNames", std::vector<std::string>())
234 ->setComment(
"file list used when fileListMode is enabled");
235 desc.setAllowAnything();
236 descriptions.
add(
"source",
desc);
263 open(fuEoLS.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
274 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
280 edm::LogInfo(
"FedRawDataInputSource") <<
"----------------RUN ENDED----------------";
323 open(fuEoLS.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
337 gettimeofday(&tv,
nullptr);
338 const edm::Timestamp lsopentime((
unsigned long long)tv.tv_sec * 1000000 + (
unsigned long long)tv.tv_usec);
346 edm::LogInfo(
"FedRawDataInputSource") <<
"New lumi section was opened. LUMI -: " << lumiSection;
367 std::unique_lock<std::mutex> lkw(
mWakeup_);
378 <<
"Run has been aborted by the input source reader thread";
423 <<
" but according to BU JSON there should be " <<
currentFile_->nEvents_ <<
" events";
427 std::unique_lock<std::mutex> lkw(
mWakeup_);
447 <<
"Premature end of input file while reading file header";
450 <<
"File with only raw header and no events received in LS " <<
currentFile_->lumi_;
467 <<
"Premature end of input file while reading event header";
498 <<
"Premature end of input file while reading event header";
502 event_ = std::make_unique<FRDEventMsgView>(dataPosition);
505 <<
" event id:" <<
event_->event() <<
" lumi:" <<
event_->lumi() <<
" run:" <<
event_->run()
514 <<
"Premature end of input file while reading event data";
520 event_ = std::make_unique<FRDEventMsgView>(dataPosition);
540 unsigned char* dataPosition;
545 <<
"Premature end of input file (missing:" 547 <<
") while reading event data for next event header";
550 event_ = std::make_unique<FRDEventMsgView>(dataPosition);
553 <<
" event id:" <<
event_->event() <<
" lumi:" <<
event_->lumi() <<
" run:" <<
event_->run()
562 <<
"Premature end of input file (missing:" << (msgSize -
currentFile_->fileSizeLeft())
563 <<
") while reading event data for event " <<
event_->event() <<
" lumi:" <<
event_->lumi();
586 event_ = std::make_unique<FRDEventMsgView>(dataPosition);
589 chunkEnd =
currentFile_->advance(dataPosition, msgSize);
598 <<
" after reading last event declared size of " <<
event_->size() <<
" bytes";
606 if (crc !=
event_->crc32c()) {
610 <<
"Found a wrong crc32c checksum: expected 0x" << std::hex <<
event_->crc32c() <<
" but calculated 0x" 614 uint32_t adler = adler32(0
L, Z_NULL, 0);
615 adler = adler32(adler, (Bytef*)
event_->payload(),
event_->eventSize());
617 if (adler !=
event_->adler32()) {
621 <<
"Found a wrong Adler32 checksum: expected 0x" << std::hex <<
event_->adler32() <<
" but calculated 0x" 646 <<
"No TCDS or GTP FED in event with FEDHeader EID -: " <<
L1EventID_;
687 bool fileIsBeingProcessed =
false;
690 fileIsBeingProcessed =
true;
711 gettimeofday(&stv,
nullptr);
716 uint32_t eventSize =
event_->eventSize();
717 unsigned char*
event = (
unsigned char*)
event_->payload();
721 uint16_t selectedTCDSFed = 0;
722 while (eventSize > 0) {
732 throw cms::Exception(
"FedRawDataInputSource::fillFEDRawDataCollection") <<
"Out of range FED ID : " <<
fedId;
734 if (!selectedTCDSFed) {
735 selectedTCDSFed =
fedId;
741 throw cms::Exception(
"FedRawDataInputSource::fillFEDRawDataCollection")
742 <<
"Second TCDS FED ID " <<
fedId <<
" found. First ID: " << selectedTCDSFed;
752 tstamp =
edm::Timestamp(static_cast<edm::TimeValue_t>((gpsh << 32) + gpsl));
762 memcpy(fedData.
data(),
event + eventSize, fedSize);
773 unsigned int currentLumiSection = 0;
782 uint32_t lockCount = 0;
793 bool copy_active =
false;
811 std::unique_lock<std::mutex> lkw(
mWakeup_);
817 <<
"No free chunks or threads. Worker pool empty:" <<
workerPool_.empty()
821 LogDebug(
"FedRawDataInputSource") <<
"No free chunks or threads...";
837 uint32_t fileSizeIndex;
838 int64_t fileSizeFromMetadata;
846 uint16_t rawHeaderSize = 0;
847 uint32_t lsFromRaw = 0;
848 int32_t serverEventsInNewFile = -1;
862 unsigned int nOtherLumis = nConcurrentLumis > 0 ? nConcurrentLumis - 1 : 0;
863 unsigned int checkLumiStart = currentLumiSection > nOtherLumis ? currentLumiSection - nOtherLumis : 1;
864 bool hasDiscardedLumi =
false;
865 for (
unsigned int i = checkLumiStart;
i <= currentLumiSection;
i++) {
867 edm::LogWarning(
"FedRawDataInputSource") <<
"Source detected that the lumisection is discarded -: " <<
i;
868 hasDiscardedLumi =
true;
872 if (hasDiscardedLumi)
878 edm::LogWarning(
"FedRawDataInputSource") <<
"Input throttled detected, reading files is paused...";
899 serverEventsInNewFile,
900 fileSizeFromMetadata,
921 serverEventsInNewFile,
922 fileSizeFromMetadata,
933 if (thisLockWaitTimeUs > 0.)
934 sumLockWaitTimeUs += thisLockWaitTimeUs;
942 sumLockWaitTimeUs = 0;
972 if (
ls > currentLumiSection) {
976 currentLumiSection =
ls;
984 if (ls < daqDirector_->getStartLumisectionFromEnv()) {
996 }
else if (
ls < 100) {
1000 for (
unsigned int nextLS =
std::min(lsToStart,
ls); nextLS <=
ls; nextLS++) {
1011 for (
unsigned int nextLS = currentLumiSection + 1; nextLS <=
ls; nextLS++) {
1016 currentLumiSection =
ls;
1020 if (currentLumiSection > 0 &&
ls < currentLumiSection) {
1022 <<
"Got old LS (" <<
ls <<
") file from EvFDAQDirector! Expected LS:" << currentLumiSection
1023 <<
". Aborting execution." << std::endl;
1038 if (!(dbgcount % 20))
1039 LogDebug(
"FedRawDataInputSource") <<
"No file for me... sleep and try again...";
1043 backoff_exp =
std::min(4, backoff_exp);
1045 int sleeptime = (
int)(100000. *
pow(2, backoff_exp));
1055 LogDebug(
"FedRawDataInputSource") <<
"The director says to grab -: " << nextFile;
1063 rawFile = rawFilePath.replace_extension(
".raw").string();
1067 int stat_res =
stat(rawFile.c_str(), &st);
1068 if (stat_res == -1) {
1069 edm::LogError(
"FedRawDataInputSource") <<
"Can not stat file (" << errno <<
"):-" << rawFile << std::endl;
1080 int eventsInNewFile;
1083 eventsInNewFile = 0;
1085 eventsInNewFile = -1;
1089 if (rawHeaderSize) {
1090 int rawFdEmpty = -1;
1091 uint16_t rawHeaderCheck;
1094 nextFile, rawFdEmpty, rawHeaderCheck, fileSizeFromMetadata, fileFound, 0,
true);
1095 assert(fileFound && rawHeaderCheck == rawHeaderSize);
1100 eventsInNewFile = serverEventsInNewFile;
1101 assert(eventsInNewFile >= 0);
1102 assert((eventsInNewFile > 0) ==
1103 (fileSize > rawHeaderSize));
1112 std::unique_ptr<InputFile> newInputFile(
new InputFile(evf::EvFDaqDirector::FileStatus::newFile,
1123 auto newInputFilePtr = newInputFile.get();
1126 for (
unsigned int i = 0;
i < neededChunks;
i++) {
1128 bool copy_active =
false;
1138 unsigned int newTid = 0xffffffff;
1148 bool copy_active =
false;
1166 if (newChunk ==
nullptr) {
1168 if (newTid != 0xffffffff)
1177 std::unique_lock<std::mutex> lk(
mReader_);
1191 if (!eventsInNewFile) {
1197 std::unique_lock<std::mutex> lkw(
mWakeup_);
1199 std::unique_ptr<InputFile> newInputFile(
new InputFile(evf::EvFDaqDirector::FileStatus::newFile,
1206 (rawHeaderSize > 0),
1223 std::unique_lock<std::mutex> lkw(
mWakeup_);
1228 newChunk->
reset(0, toRead, 0);
1232 std::unique_ptr<InputFile> newInputFile(
new InputFile(evf::EvFDaqDirector::FileStatus::newFile,
1242 newInputFile->chunks_[0] = newChunk;
1251 unsigned numFinishedThreads = 0;
1257 std::unique_lock<std::mutex> lk(
mReader_);
1260 numFinishedThreads++;
1273 std::unique_lock<std::mutex> lk(
mReader_);
1300 unsigned int bufferLeft = (chunk->
offset_ == 0 &&
file->rawFd_ != -1) ?
file->rawHeaderSize_ : 0;
1305 bool fileOpenedHere =
false;
1308 fileDescriptor =
file->rawFd_;
1309 if (fileDescriptor == -1) {
1310 fileDescriptor = open(
file->fileName_.c_str(), O_RDONLY);
1311 fileOpenedHere =
true;
1312 file->rawFd_ = fileDescriptor;
1316 fileDescriptor =
file->rawFd_;
1318 if (fileDescriptor == -1) {
1319 fileDescriptor = open(
file->fileName_.c_str(), O_RDONLY);
1320 fileOpenedHere =
true;
1323 fileDescriptor = open(
file->fileName_.c_str(), O_RDONLY);
1324 fileOpenedHere =
true;
1328 if (fileDescriptor < 0) {
1329 edm::LogError(
"FedRawDataInputSource") <<
"readWorker failed to open file -: " <<
file->fileName_
1330 <<
" fd:" << fileDescriptor <<
" error: " << strerror(errno);
1334 if (fileOpenedHere) {
1336 pos = lseek(fileDescriptor, chunk->
offset_, SEEK_SET);
1339 <<
"readWorker failed to seek file -: " <<
file->fileName_ <<
" fd:" << fileDescriptor <<
" to offset " 1340 << chunk->
offset_ <<
" error: " << strerror(errno);
1346 LogDebug(
"FedRawDataInputSource") <<
"Reader thread opened file -: TID: " << tid <<
" file: " <<
file->fileName_
1347 <<
" at offset " << lseek(fileDescriptor, 0, SEEK_CUR);
1349 unsigned int skipped = bufferLeft;
1359 edm::LogError(
"FedRawDataInputSource") <<
"readWorker failed to read file -: " <<
file->fileName_
1360 <<
" fd:" << fileDescriptor <<
" error: " << strerror(errno);
1370 <<
"readWorker failed to read file -: " <<
file->fileName_ <<
" fd:" << fileDescriptor <<
" last:" <<
last 1371 <<
" expectedChunkSize:" << chunk->
usedSize_ 1373 <<
" block:" << (
i + 1) <<
"/" <<
readBlocks_ <<
" error: " << strerror(errno);
1384 std::chrono::milliseconds msec = std::chrono::duration_cast<std::chrono::milliseconds>(
diff);
1385 LogDebug(
"FedRawDataInputSource") <<
" finished reading block -: " << (bufferLeft >> 20) <<
" MB" 1386 <<
" in " << msec.count() <<
" ms (" << (bufferLeft >> 20) /
double(msec.count())
1389 if (chunk->
offset_ + bufferLeft ==
file->fileSize_) {
1390 close(fileDescriptor);
1391 fileDescriptor = -1;
1396 close(fileDescriptor);
1411 throw cms::Exception(
"FedRawDataInputSource:threadError") <<
" file reader thread error ";
1438 if (currentLeft <
size) {
1487 LogDebug(
"FedRawDataInputSource:InputFile") <<
"Deleting input file -:" <<
fileName_;
1490 }
catch (
const std::filesystem::filesystem_error& ex) {
1492 <<
" - deleteFile BOOST FILESYSTEM ERROR CAUGHT -: " << ex.what() <<
". Trying again.";
1495 <<
" - deleteFile std::exception CAUGHT -: " << ex.what() <<
". Trying again.";
1503 uint32_t existingSize = 0;
1507 if (
file->rawFd_ == -1) {
1509 if (
file->rawHeaderSize_)
1516 existingSize +=
file->rawHeaderSize_;
1519 LogDebug(
"FedRawDataInputSource") <<
"opened file -: " << std::endl <<
file->fileName_;
1521 throw cms::Exception(
"FedRawDataInputSource:readNextChunkIntoBuffer")
1522 <<
"failed to open file " << std::endl
1528 (
void*)(
file->chunks_[0]->buf_ + existingSize),
1531 existingSize +=
last;
1536 if (
file->chunkPosition_ == 0) {
1540 existingSize +=
last;
1545 memmove((
void*)
file->chunks_[0]->buf_,
file->chunks_[0]->buf_ +
file->chunkPosition_, existingSizeLeft);
1551 for (uint32_t
i = 0;
i < blockcount;
i++) {
1552 const ssize_t
last =
1555 existingSizeLeft +=
last;
1561 file->chunkPosition_ = 0;
1566 LogDebug(
"FedRawDataInputSource") <<
"Closing input file -: " << std::endl <<
file->fileName_;
1586 std::pair<bool, unsigned int>
ret(
true, itr->second);
1591 return std::pair<bool, unsigned int>(
false, 0);
1596 if (
a.rfind(
'/') != std::string::npos)
1597 a =
a.substr(
a.rfind(
'/'));
1598 if (
b.rfind(
'/') != std::string::npos)
1599 b =
b.substr(
b.rfind(
'/'));
1607 if (fileStem.find(
"file://") == 0)
1608 fileStem = fileStem.substr(7);
1609 else if (fileStem.find(
"file:") == 0)
1610 fileStem = fileStem.substr(5);
1611 auto end = fileStem.find(
'_');
1613 if (fileStem.find(
"run") == 0) {
1617 long rval = std::stol(runStr);
1618 edm::LogInfo(
"FedRawDataInputSource") <<
"Autodetected run number in fileListMode -: " << rval;
1622 <<
"Unable to autodetect run number in fileListMode from file -: " <<
fileName;
1635 if (nextFile.find(
"file://") == 0)
1636 nextFile = nextFile.substr(7);
1637 else if (nextFile.find(
"file:") == 0)
1638 nextFile = nextFile.substr(5);
1641 if (fileStem.find(
"ls"))
1642 fileStem = fileStem.substr(fileStem.find(
"ls") + 2);
1643 if (fileStem.find(
'_'))
1644 fileStem = fileStem.substr(0, fileStem.find(
'_'));
1647 ls = std::stoul(fileStem);
1662 return getFile(
ls, nextFile, fsize, lockWaitTime);
static const char runNumber_[]
unsigned int getgpshigh(const unsigned char *)
void startedLookingForFile()
bool gtpe_board_sense(const unsigned char *p)
constexpr size_t FRDHeaderMaxVersion
void setExceptionDetected(unsigned int ls)
static Timestamp invalidTimestamp()
static const uint32_t length
unsigned int get(const unsigned char *, bool)
bool useFileBroker() const
ret
prodAgent to be discontinued
volatile std::atomic< bool > shutdown_flag
std::string getEoLSFilePathOnFU(const unsigned int ls) const
bool lumisectionDiscarded(unsigned int ls)
FileStatus getNextFromFileBroker(const unsigned int currentLumiSection, unsigned int &ls, std::string &nextFile, int &rawFd, uint16_t &rawHeaderSize, int32_t &serverEventsInNewFile_, int64_t &fileSize, uint64_t &thisLockWaitTimeUs)
bool isSingleStreamThread()
Log< level::Error, false > LogError
unsigned int numConcurrentLumis() const
StreamID streamID() const
bool isExceptionOnData(unsigned int ls)
ProcessHistoryID daqInit(ProductRegistry &productRegistry, ProcessHistoryRegistry &processHistoryRegistry) const
std::string getEoRFilePathOnFU() const
edm::EventAuxiliary makeEventAuxiliary(const tcds::Raw_v1 *, unsigned int runNumber, unsigned int lumiSection, bool isRealData, const edm::EventAuxiliary::ExperimentType &, const std::string &processGUID, bool verifyLumiSection, bool suppressWarning)
uint32_t fragmentLength() const
The length of the event fragment counted in 64-bit words including header and trailer.
U second(std::pair< T, U > const &p)
std::string getEoLSFilePathOnBU(const unsigned int ls) const
static Timestamp beginOfTime()
void put(BranchDescription const &bd, std::unique_ptr< WrapperBase > edp, ProductProvenance const &productProvenance) const
void resize(size_t newsize)
ProductProvenance const & dummyProvenance() const
filePath
CUSTOMIZE FOR ML.
static int parseFRDFileHeader(std::string const &rawSourcePath, int &rawFd, uint16_t &rawHeaderSize, uint32_t &lsFromHeader, int32_t &eventsFromHeader, int64_t &fileSizeFromHeader, bool requireHeader, bool retry, bool closeFile)
int grabNextJsonFileAndUnlock(std::filesystem::path const &jsonSourcePath)
unsigned long long TimeValue_t
bool evm_board_sense(const unsigned char *p, size_t size)
void createProcessingNotificationMaybe() const
uint32_t crc32c(uint32_t crc, const unsigned char *buf, size_t len)
void setInputSource(FedRawDataInputSource *inputSource)
Log< level::Info, false > LogInfo
FileStatus updateFuLock(unsigned int &ls, std::string &nextFile, uint32_t &fsize, uint16_t &rawHeaderSize, uint64_t &lockWaitTime, bool &setExceptionState)
BranchDescription const & branchDescription() const
unsigned int getStartLumisectionFromEnv() const
int grabNextJsonFromRaw(std::string const &rawSourcePath, int &rawFd, uint16_t &rawHeaderSize, int64_t &fileSizeFromHeader, bool &fileFound, uint32_t serverLS, bool closeFile)
def getRunNumber(filename)
void setInStateSup(FastMonState::InputState inputState)
unsigned long long uint64_t
void add(std::string const &label, ParameterSetDescription const &psetDescription)
def remove(d, key, TELL=False)
void stoppedLookingForFile(unsigned int lumi)
unsigned int getLumisectionToStart() const
const unsigned char * data() const
Return a const pointer to the beginning of the data buffer.
unsigned int gtpe_get(const unsigned char *)
void setDeleteTracking(std::mutex *fileDeleteLock, std::list< std::pair< int, std::unique_ptr< InputFile >>> *filesToDelete)
constexpr std::array< uint32, FRDHeaderMaxVersion+1 > FRDHeaderVersionSize
Log< level::Warning, false > LogWarning
void createBoLSFile(const uint32_t lumiSection, bool checkIfExists) const
bool exceptionDetected() const
void setFMS(evf::FastMonitoringService *fms)
unsigned int getgpslow(const unsigned char *)
Power< A, B >::type pow(const A &a, const B &b)
void reportLockWait(unsigned int ls, double waitTime, unsigned int lockCount)
void setInState(FastMonState::InputState inputState)