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";
163 cvReader_.push_back(
new std::condition_variable);
165 threadInit_.store(
false, std::memory_order_release);
185 it->second->unsetDeleteFile();
200 std::unique_lock<std::mutex> lk(
mReader_);
221 desc.setComment(
"File-based Filter Farm input source for reading raw data from BU ramdisk");
222 desc.addUntracked<
unsigned int>(
"eventChunkSize", 32)->setComment(
"Input buffer (chunk) size");
223 desc.addUntracked<
unsigned int>(
"eventChunkBlock", 32)
224 ->setComment(
"Block size used in a single file read call (must be smaller or equal to buffer size)");
225 desc.addUntracked<
unsigned int>(
"numBuffers", 2)->setComment(
"Number of buffers used for reading input");
226 desc.addUntracked<
unsigned int>(
"maxBufferedFiles", 2)
227 ->setComment(
"Maximum number of simultaneously buffered raw files");
228 desc.addUntracked<
unsigned int>(
"alwaysStartFromfirstLS",
false)
229 ->setComment(
"Force source to start from LS 1 if server provides higher lumisection number");
230 desc.addUntracked<
bool>(
"verifyChecksum",
true)
231 ->setComment(
"Verify event CRC-32C checksum of FRDv5 and higher or Adler32 with v3 and v4");
232 desc.addUntracked<
bool>(
"useL1EventID",
false)
233 ->setComment(
"Use L1 event ID from FED header if true or from TCDS FED if false");
234 desc.addUntracked<std::vector<unsigned int>>(
"testTCDSFEDRange", std::vector<unsigned int>())
235 ->setComment(
"[min, max] range to search for TCDS FED ID in test setup");
236 desc.addUntracked<
bool>(
"fileListMode",
false)
237 ->setComment(
"Use fileNames parameter to directly specify raw files to open");
238 desc.addUntracked<std::vector<std::string>>(
"fileNames", std::vector<std::string>())
239 ->setComment(
"file list used when fileListMode is enabled");
240 desc.setAllowAnything();
241 descriptions.
add(
"source",
desc);
269 open(fuEoLS.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
280 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
286 edm::LogInfo(
"FedRawDataInputSource") <<
"----------------RUN ENDED----------------";
329 open(fuEoLS.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
343 gettimeofday(&tv,
nullptr);
344 const edm::Timestamp lsopentime((
unsigned long long)tv.tv_sec * 1000000 + (
unsigned long long)tv.tv_usec);
352 edm::LogInfo(
"FedRawDataInputSource") <<
"New lumi section was opened. LUMI -: " << lumiSection;
373 std::unique_lock<std::mutex> lkw(
mWakeup_);
384 <<
"Run has been aborted by the input source reader thread";
429 <<
" but according to BU JSON there should be " <<
currentFile_->nEvents_ <<
" events";
433 std::unique_lock<std::mutex> lkw(
mWakeup_);
453 <<
"Premature end of input file while reading file header";
456 <<
"File with only raw header and no events received in LS " <<
currentFile_->lumi_;
473 <<
"Premature end of input file while reading event header";
504 <<
"Premature end of input file while reading event header";
508 event_ = std::make_unique<FRDEventMsgView>(dataPosition);
511 <<
" event id:" <<
event_->event() <<
" lumi:" <<
event_->lumi() <<
" run:" <<
event_->run()
520 <<
"Premature end of input file while reading event data";
526 event_ = std::make_unique<FRDEventMsgView>(dataPosition);
546 unsigned char* dataPosition;
551 event_ = std::make_unique<FRDEventMsgView>(dataPosition);
554 <<
" event id:" <<
event_->event() <<
" lumi:" <<
event_->lumi() <<
" run:" <<
event_->run()
563 <<
"Premature end of input file while reading event data";
586 event_ = std::make_unique<FRDEventMsgView>(dataPosition);
589 chunkEnd =
currentFile_->advance(dataPosition, msgSize);
600 if (crc !=
event_->crc32c()) {
604 <<
"Found a wrong crc32c checksum: expected 0x" << std::hex <<
event_->crc32c() <<
" but calculated 0x" 608 uint32_t adler = adler32(0
L, Z_NULL, 0);
609 adler = adler32(adler, (Bytef*)
event_->payload(),
event_->eventSize());
611 if (adler !=
event_->adler32()) {
615 <<
"Found a wrong Adler32 checksum: expected 0x" << std::hex <<
event_->adler32() <<
" but calculated 0x" 640 <<
"No TCDS or GTP FED in event with FEDHeader EID -: " <<
L1EventID_;
681 bool fileIsBeingProcessed =
false;
684 fileIsBeingProcessed =
true;
705 gettimeofday(&stv,
nullptr);
710 uint32_t eventSize =
event_->eventSize();
711 unsigned char*
event = (
unsigned char*)
event_->payload();
715 uint16_t selectedTCDSFed = 0;
716 while (eventSize > 0) {
726 throw cms::Exception(
"FedRawDataInputSource::fillFEDRawDataCollection") <<
"Out of range FED ID : " <<
fedId;
728 if (!selectedTCDSFed) {
729 selectedTCDSFed =
fedId;
735 throw cms::Exception(
"FedRawDataInputSource::fillFEDRawDataCollection")
736 <<
"Second TCDS FED ID " <<
fedId <<
" found. First ID: " << selectedTCDSFed;
746 tstamp =
edm::Timestamp(static_cast<edm::TimeValue_t>((gpsh << 32) + gpsl));
756 memcpy(fedData.
data(),
event + eventSize, fedSize);
767 unsigned int currentLumiSection = 0;
777 uint32_t lockCount = 0;
788 bool copy_active =
false;
806 std::unique_lock<std::mutex> lkw(
mWakeup_);
811 LogDebug(
"FedRawDataInputSource") <<
"No free chunks or threads...";
827 uint32_t fileSizeIndex;
828 int64_t fileSizeFromMetadata;
836 uint16_t rawHeaderSize = 0;
837 uint32_t lsFromRaw = 0;
838 int32_t serverEventsInNewFile = -1;
852 unsigned int nOtherLumis = nConcurrentLumis > 0 ? nConcurrentLumis - 1 : 0;
853 unsigned int checkLumiStart = currentLumiSection > nOtherLumis ? currentLumiSection - nOtherLumis : 1;
854 bool hasDiscardedLumi =
false;
855 for (
unsigned int i = checkLumiStart;
i <= currentLumiSection;
i++) {
857 edm::LogWarning(
"FedRawDataInputSource") <<
"Source detected that the lumisection is discarded -: " <<
i;
858 hasDiscardedLumi =
true;
862 if (hasDiscardedLumi)
868 edm::LogWarning(
"FedRawDataInputSource") <<
"Input throttled detected, reading files is paused...";
885 uint16_t rawDataType;
891 serverEventsInNewFile,
892 fileSizeFromMetadata,
913 serverEventsInNewFile,
914 fileSizeFromMetadata,
925 if (thisLockWaitTimeUs > 0.)
926 sumLockWaitTimeUs += thisLockWaitTimeUs;
934 sumLockWaitTimeUs = 0;
964 if (
ls > currentLumiSection) {
968 currentLumiSection =
ls;
976 if (ls < daqDirector_->getStartLumisectionFromEnv()) {
988 }
else if (
ls < 100) {
992 for (
unsigned int nextLS =
std::min(lsToStart,
ls); nextLS <=
ls; nextLS++) {
1003 for (
unsigned int nextLS = currentLumiSection + 1; nextLS <=
ls; nextLS++) {
1008 currentLumiSection =
ls;
1012 if (currentLumiSection > 0 &&
ls < currentLumiSection) {
1014 <<
"Got old LS (" <<
ls <<
") file from EvFDAQDirector! Expected LS:" << currentLumiSection
1015 <<
". Aborting execution." << std::endl;
1030 if (!(dbgcount % 20))
1031 LogDebug(
"FedRawDataInputSource") <<
"No file for me... sleep and try again...";
1035 backoff_exp =
std::min(4, backoff_exp);
1037 int sleeptime = (
int)(100000. *
pow(2, backoff_exp));
1047 LogDebug(
"FedRawDataInputSource") <<
"The director says to grab -: " << nextFile;
1055 rawFile = rawFilePath.replace_extension(
".raw").string();
1059 int stat_res =
stat(rawFile.c_str(), &st);
1060 if (stat_res == -1) {
1061 edm::LogError(
"FedRawDataInputSource") <<
"Can not stat file (" << errno <<
"):-" << rawFile << std::endl;
1072 int eventsInNewFile;
1075 eventsInNewFile = 0;
1077 eventsInNewFile = -1;
1081 if (rawHeaderSize) {
1082 int rawFdEmpty = -1;
1083 uint16_t rawHeaderCheck;
1086 nextFile, rawFdEmpty, rawHeaderCheck, fileSizeFromMetadata, fileFound, 0,
true);
1087 assert(fileFound && rawHeaderCheck == rawHeaderSize);
1092 eventsInNewFile = serverEventsInNewFile;
1093 assert(eventsInNewFile >= 0);
1094 assert((eventsInNewFile > 0) ==
1095 (fileSize > rawHeaderSize));
1104 std::unique_ptr<InputFile> newInputFile(
new InputFile(evf::EvFDaqDirector::FileStatus::newFile,
1115 auto newInputFilePtr = newInputFile.get();
1118 for (
unsigned int i = 0;
i < neededChunks;
i++) {
1120 bool copy_active =
false;
1130 unsigned int newTid = 0xffffffff;
1140 bool copy_active =
false;
1158 if (newChunk ==
nullptr) {
1160 if (newTid != 0xffffffff)
1169 std::unique_lock<std::mutex> lk(
mReader_);
1183 if (!eventsInNewFile) {
1189 std::unique_lock<std::mutex> lkw(
mWakeup_);
1191 std::unique_ptr<InputFile> newInputFile(
new InputFile(evf::EvFDaqDirector::FileStatus::newFile,
1198 (rawHeaderSize > 0),
1217 if (newChunk ==
nullptr) {
1224 std::unique_lock<std::mutex> lkw(
mWakeup_);
1229 newChunk->
reset(0, toRead, 0);
1233 std::unique_ptr<InputFile> newInputFile(
new InputFile(evf::EvFDaqDirector::FileStatus::newFile,
1243 newInputFile->chunks_[0] = newChunk;
1252 unsigned numFinishedThreads = 0;
1258 std::unique_lock<std::mutex> lk(
mReader_);
1261 numFinishedThreads++;
1271 threadInit_.exchange(
true, std::memory_order_acquire);
1275 std::unique_lock<std::mutex> lk(
mReader_);
1302 unsigned int bufferLeft = (chunk->
offset_ == 0 &&
file->rawFd_ != -1) ?
file->rawHeaderSize_ : 0;
1307 bool fileOpenedHere =
false;
1310 fileDescriptor =
file->rawFd_;
1311 if (fileDescriptor == -1) {
1312 fileDescriptor = open(
file->fileName_.c_str(), O_RDONLY);
1313 fileOpenedHere =
true;
1314 file->rawFd_ = fileDescriptor;
1318 fileDescriptor =
file->rawFd_;
1320 if (fileDescriptor == -1) {
1321 fileDescriptor = open(
file->fileName_.c_str(), O_RDONLY);
1322 fileOpenedHere =
true;
1325 fileDescriptor = open(
file->fileName_.c_str(), O_RDONLY);
1326 fileOpenedHere =
true;
1330 if (fileDescriptor < 0) {
1331 edm::LogError(
"FedRawDataInputSource") <<
"readWorker failed to open file -: " <<
file->fileName_
1332 <<
" fd:" << fileDescriptor <<
" error: " << strerror(errno);
1336 if (fileOpenedHere) {
1338 pos = lseek(fileDescriptor, chunk->
offset_, SEEK_SET);
1341 <<
"readWorker failed to seek file -: " <<
file->fileName_ <<
" fd:" << fileDescriptor <<
" to offset " 1342 << chunk->
offset_ <<
" error: " << strerror(errno);
1348 LogDebug(
"FedRawDataInputSource") <<
"Reader thread opened file -: TID: " << tid <<
" file: " <<
file->fileName_
1349 <<
" at offset " << lseek(fileDescriptor, 0, SEEK_CUR);
1351 unsigned int skipped = bufferLeft;
1358 (
void*)(chunk->
buf_ + bufferLeft),
1362 edm::LogError(
"FedRawDataInputSource") <<
"readWorker failed to read file -: " <<
file->fileName_
1363 <<
" fd:" << fileDescriptor <<
" error: " << strerror(errno);
1373 <<
"readWorker failed to read file -: " <<
file->fileName_ <<
" fd:" << fileDescriptor <<
" last:" <<
last 1374 <<
" expectedChunkSize:" << chunk->
usedSize_ 1376 <<
" block:" << (
i + 1) <<
"/" <<
readBlocks_ <<
" error: " << strerror(errno);
1387 std::chrono::milliseconds msec = std::chrono::duration_cast<std::chrono::milliseconds>(
diff);
1388 LogDebug(
"FedRawDataInputSource") <<
" finished reading block -: " << (bufferLeft >> 20) <<
" MB" 1389 <<
" in " << msec.count() <<
" ms (" << (bufferLeft >> 20) /
double(msec.count())
1392 if (chunk->
offset_ + bufferLeft ==
file->fileSize_) {
1393 close(fileDescriptor);
1394 fileDescriptor = -1;
1399 close(fileDescriptor);
1414 throw cms::Exception(
"FedRawDataInputSource:threadError") <<
" file reader thread error ";
1441 if (currentLeft <
size) {
1491 LogDebug(
"FedRawDataInputSource:InputFile") <<
"Deleting input file -:" <<
fileName;
1494 }
catch (
const std::filesystem::filesystem_error& ex) {
1496 <<
" - deleteFile BOOST FILESYSTEM ERROR CAUGHT -: " << ex.what() <<
". Trying again.";
1499 <<
" - deleteFile std::exception CAUGHT -: " << ex.what() <<
". Trying again.";
1509 uint32_t existingSize = 0;
1513 if (
file->rawFd_ == -1) {
1515 if (
file->rawHeaderSize_)
1522 existingSize +=
file->rawHeaderSize_;
1525 LogDebug(
"FedRawDataInputSource") <<
"opened file -: " << std::endl <<
file->fileName_;
1527 throw cms::Exception(
"FedRawDataInputSource:readNextChunkIntoBuffer")
1528 <<
"failed to open file " << std::endl
1534 (
void*)(
file->chunks_[0]->buf_ + existingSize),
1537 existingSize +=
last;
1542 if (
file->chunkPosition_ == 0) {
1546 existingSize +=
last;
1551 memmove((
void*)
file->chunks_[0]->buf_,
file->chunks_[0]->buf_ +
file->chunkPosition_, existingSizeLeft);
1557 for (uint32_t
i = 0;
i < blockcount;
i++) {
1558 const ssize_t
last =
1561 existingSizeLeft +=
last;
1567 file->chunkPosition_ = 0;
1572 LogDebug(
"FedRawDataInputSource") <<
"Closing input file -: " << std::endl <<
file->fileName_;
1592 std::pair<bool, unsigned int>
ret(
true, itr->second);
1597 return std::pair<bool, unsigned int>(
false, 0);
1602 if (
a.rfind(
'/') != std::string::npos)
1603 a =
a.substr(
a.rfind(
'/'));
1604 if (
b.rfind(
'/') != std::string::npos)
1605 b =
b.substr(
b.rfind(
'/'));
1613 if (fileStem.find(
"file://") == 0)
1614 fileStem = fileStem.substr(7);
1615 else if (fileStem.find(
"file:") == 0)
1616 fileStem = fileStem.substr(5);
1617 auto end = fileStem.find(
'_');
1619 if (fileStem.find(
"run") == 0) {
1623 long rval = std::stol(runStr);
1624 edm::LogInfo(
"FedRawDataInputSource") <<
"Autodetected run number in fileListMode -: " << rval;
1628 <<
"Unable to autodetect run number in fileListMode from file -: " <<
fileName;
1641 if (nextFile.find(
"file://") == 0)
1642 nextFile = nextFile.substr(7);
1643 else if (nextFile.find(
"file:") == 0)
1644 nextFile = nextFile.substr(5);
1647 if (fileStem.find(
"ls"))
1648 fileStem = fileStem.substr(fileStem.find(
"ls") + 2);
1649 if (fileStem.find(
'_'))
1650 fileStem = fileStem.substr(0, fileStem.find(
'_'));
1653 ls = std::stoul(fileStem);
1668 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)
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)
static int parseFRDFileHeader(std::string const &rawSourcePath, int &rawFd, uint16_t &rawHeaderSize, uint16_t &rawDataType, uint32_t &lsFromHeader, int32_t &eventsFromHeader, int64_t &fileSizeFromHeader, bool requireHeader, bool retry, bool closeFile)
std::string getEoLSFilePathOnBU(const unsigned int ls) const
static Timestamp beginOfTime()
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 requireHeader=true)
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.
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
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 *)
int grabNextJsonFromRaw(std::string const &rawSourcePath, int &rawFd, uint16_t &rawHeaderSize, int64_t &fileSizeFromHeader, bool &fileFound, uint32_t serverLS, bool closeFile, bool requireHeader=true)
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)