25 #include <boost/lexical_cast.hpp>
26 #include <boost/algorithm/string.hpp>
37 const std::vector<std::string> EvFDaqDirector::MergeTypeNames_ = {
"",
"DAT",
"PB",
"JSNDATA"};
40 : base_dir_(
pset.getUntrackedParameter<
std::
string>(
"baseDir")),
41 bu_base_dir_(
pset.getUntrackedParameter<
std::
string>(
"buBaseDir")),
42 run_(
pset.getUntrackedParameter<unsigned
int>(
"runNumber")),
43 useFileBroker_(
pset.getUntrackedParameter<
bool>(
"useFileBroker")),
44 fileBrokerHostFromCfg_(
pset.getUntrackedParameter<
bool>(
"fileBrokerHostFromCfg",
true)),
45 fileBrokerHost_(
pset.getUntrackedParameter<
std::
string>(
"fileBrokerHost",
"InValid")),
46 fileBrokerPort_(
pset.getUntrackedParameter<
std::
string>(
"fileBrokerPort",
"8080")),
47 fileBrokerKeepAlive_(
pset.getUntrackedParameter<
bool>(
"fileBrokerKeepAlive",
true)),
48 fileBrokerUseLocalLock_(
pset.getUntrackedParameter<
bool>(
"fileBrokerUseLocalLock",
true)),
49 fuLockPollInterval_(
pset.getUntrackedParameter<unsigned
int>(
"fuLockPollInterval", 2000)),
50 outputAdler32Recheck_(
pset.getUntrackedParameter<
bool>(
"outputAdler32Recheck",
false)),
51 requireTSPSet_(
pset.getUntrackedParameter<
bool>(
"requireTransfersPSet",
false)),
52 selectedTransferMode_(
pset.getUntrackedParameter<
std::
string>(
"selectedTransferMode",
"")),
53 mergeTypePset_(
pset.getUntrackedParameter<
std::
string>(
"mergingPset",
"")),
54 directorBU_(
pset.getUntrackedParameter<
bool>(
"directorIsBU",
false)),
55 hltSourceDirectory_(
pset.getUntrackedParameter<
std::
string>(
"hltSourceDirectory",
"")),
59 fu_readwritelock_fd_(-1),
60 fulocal_rwlock_fd_(-1),
61 fulocal_rwlock_fd2_(-1),
62 bu_w_lock_stream(nullptr),
63 bu_r_lock_stream(nullptr),
64 fu_rw_lock_stream(nullptr),
65 dirManager_(base_dir_),
67 bu_w_flk(make_flock(F_WRLCK, SEEK_SET, 0, 0, 0)),
68 bu_r_flk(make_flock(F_RDLCK, SEEK_SET, 0, 0, 0)),
69 bu_w_fulk(make_flock(F_UNLCK, SEEK_SET, 0, 0, 0)),
70 bu_r_fulk(make_flock(F_UNLCK, SEEK_SET, 0, 0, 0)),
71 fu_rw_flk(make_flock(F_WRLCK, SEEK_SET, 0, 0, getpid())),
72 fu_rw_fulk(make_flock(F_UNLCK, SEEK_SET, 0, 0, getpid())) {
81 gethostname(hostname, 32);
84 char* fuLockPollIntervalPtr = std::getenv(
"FFF_LOCKPOLLINTERVAL");
85 if (fuLockPollIntervalPtr) {
90 }
catch (boost::bad_lexical_cast
const&) {
96 char* fileBrokerParamPtr = std::getenv(
"FFF_USEFILEBROKER");
97 if (fileBrokerParamPtr) {
101 }
catch (boost::bad_lexical_cast
const&) {
110 if (
stat(
"/etc/appliance/bus.config", &
buf) == 0) {
115 throw cms::Exception(
"EvFDaqDirector") <<
"No file service or BU data address information";
118 <<
"fileBrokerHostFromCfg must be set to true if fileBrokerHost parameter is not valid or empty";
126 char* startFromLSPtr = std::getenv(
"FFF_STARTFROMLS");
127 if (startFromLSPtr) {
131 }
catch (boost::bad_lexical_cast
const&) {
137 char* fileBrokerUseLockParamPtr = std::getenv(
"FFF_FILEBROKERUSELOCALLOCK");
138 if (fileBrokerUseLockParamPtr) {
141 edm::LogInfo(
"EvFDaqDirector") <<
"Setting fileBrokerUseLocalLock parameter by environment string: "
143 }
catch (boost::bad_lexical_cast
const&) {
150 std::stringstream
ss;
151 ss <<
"run" << std::setfill(
'0') << std::setw(6) <<
run_;
153 ss = std::stringstream();
157 ss = std::stringstream();
162 int retval =
mkdir(
base_dir_.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
163 if (retval != 0 && errno != EEXIST) {
165 <<
" Error checking for base dir -: " <<
base_dir_ <<
" mkdir error:" << strerror(errno);
170 retval =
mkdir(
run_dir_.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IRWXO | S_IXOTH);
171 if (retval != 0 && errno != EEXIST) {
173 <<
" Error creating run dir -: " <<
run_dir_ <<
" mkdir error:" << strerror(errno);
181 open(fulocal_lock_.c_str(), O_RDWR | O_CREAT, S_IRWXU | S_IWGRP | S_IRGRP | S_IWOTH | S_IROTH);
184 <<
" Error creating/opening a local lock file -: " << fulocal_lock_.c_str() <<
" : " << strerror(errno);
185 chmod(fulocal_lock_.c_str(), 0777);
189 open(fulocal_lock_.c_str(), O_RDWR, S_IRWXU | S_IWGRP | S_IRGRP | S_IWOTH | S_IROTH);
192 <<
" Error opening a local lock file -: " << fulocal_lock_.c_str() <<
" : " << strerror(errno);
204 if (retval != 0 && errno != EEXIST) {
206 <<
" Error creating bu run dir -: " <<
bu_run_dir_ <<
" mkdir error:" << strerror(errno) <<
"\n";
210 if (retval != 0 && errno != EEXIST) {
212 <<
" Error creating bu run open dir -: " <<
bu_run_open_dir_ <<
" mkdir error:" << strerror(errno) <<
"\n";
216 bu_writelock_fd_ = open(bulockfile.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU);
218 edm::LogWarning(
"EvFDaqDirector") <<
"problem with creating filedesc for buwritelock -: " << strerror(errno);
223 edm::LogWarning(
"EvFDaqDirector") <<
"Error creating write lock stream -: " << strerror(errno);
237 retval =
mkdir(tmphltdir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
238 if (retval != 0 && errno != EEXIST)
240 <<
" Error creating bu run dir -: " << hltdir <<
" mkdir error:" << strerror(errno) <<
"\n";
242 std::filesystem::copy_file(
hltSourceDirectory_ +
"/HltConfig.py", tmphltdir +
"/HltConfig.py");
243 std::filesystem::copy_file(
hltSourceDirectory_ +
"/fffParameters.jsn", tmphltdir +
"/fffParameters.jsn");
245 std::string optfiles[3] = {
"hltinfo",
"blacklist",
"whitelist"};
246 for (
auto& optfile : optfiles) {
248 std::filesystem::copy_file(
hltSourceDirectory_ +
"/" + optfile, tmphltdir +
"/" + optfile);
253 std::filesystem::rename(tmphltdir, hltdir);
262 if (retval != 0 && errno != EEXIST) {
264 <<
" Error checking for bu base dir -: " <<
bu_base_dir_ <<
" mkdir error:" << strerror(errno) <<
"\n";
275 std::stringstream sstp;
282 if (!
stat(defPath.c_str(), &statbuf))
283 edm::LogInfo(
"EvFDaqDirector") <<
"found JSD file in ramdisk -: " << defPath;
286 std::string defPathSuffix =
"src/EventFilter/Utilities/plugins/budef.jsd";
287 defPath =
std::string(std::getenv(
"CMSSW_BASE")) +
"/" + defPathSuffix;
288 if (
stat(defPath.c_str(), &statbuf)) {
289 defPath =
std::string(std::getenv(
"CMSSW_RELEASE_BASE")) +
"/" + defPathSuffix;
290 if (
stat(defPath.c_str(), &statbuf)) {
291 defPath = defPathSuffix;
297 DataPointDefinition::getDataPointDefinitionFor(defPath,
dpd_, &defLabel);
304 boost::system::error_code ec;
305 socket_->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
330 "Service used for file locking arbitration and for propagating information between other EvF components");
331 desc.addUntracked<
std::string>(
"baseDir",
".")->setComment(
"Local base directory for run output");
332 desc.addUntracked<
std::string>(
"buBaseDir",
".")->setComment(
"BU base ramdisk directory ");
333 desc.addUntracked<
unsigned int>(
"runNumber", 0)->setComment(
"Run Number in ramdisk to open");
334 desc.addUntracked<
bool>(
"useFileBroker",
false)
335 ->setComment(
"Use BU file service to grab input data instead of NFS file locking");
336 desc.addUntracked<
bool>(
"fileBrokerHostFromCfg",
true)
337 ->setComment(
"Allow service to discover BU address from hltd configuration");
338 desc.addUntracked<
std::string>(
"fileBrokerHost",
"InValid")->setComment(
"BU file service host.");
339 desc.addUntracked<
std::string>(
"fileBrokerPort",
"8080")->setComment(
"BU file service port");
340 desc.addUntracked<
bool>(
"fileBrokerKeepAlive",
true)
341 ->setComment(
"Use keep alive to avoid using large number of sockets");
342 desc.addUntracked<
bool>(
"fileBrokerUseLocalLock",
true)
343 ->setComment(
"Use local lock file to synchronize appearance of index and EoLS file markers for hltd");
344 desc.addUntracked<
unsigned int>(
"fuLockPollInterval", 2000)
345 ->setComment(
"Lock polling interval in microseconds for the input directory file lock");
346 desc.addUntracked<
bool>(
"outputAdler32Recheck",
false)
347 ->setComment(
"Check Adler32 of per-process output files while micro-merging");
348 desc.addUntracked<
bool>(
"requireTransfersPSet",
false)
349 ->setComment(
"Require complete transferSystem PSet in the process configuration");
351 ->setComment(
"Selected transfer mode (choice in Lvl0 propagated as Python parameter");
352 desc.addUntracked<
bool>(
"directorIsBU",
false)->setComment(
"BU director mode used for testing");
353 desc.addUntracked<
std::string>(
"hltSourceDirectory",
"")->setComment(
"BU director mode source directory");
355 ->setComment(
"Name of merging PSet to look for merging type definitions for streams");
356 descriptions.
add(
"EvFDaqDirector",
desc);
387 edm::LogWarning(
"EvFDaqDirector") <<
" Handles to check for files to delete were not set by the input source...";
394 if (it->second->lumi_ ==
ls) {
498 <<
". error = " << strerror(errno);
506 uint16_t& rawHeaderSize,
508 bool& setExceptionState) {
513 int lock_attempts = 0;
514 long total_lock_attempts = 0;
520 if (stopFileCheck == 0 || stopFilePidCheck == 0) {
521 if (stopFileCheck == 0)
527 if (stopFileLS >= 0 && (
int)
ls >= stopFileLS)
531 edm::LogWarning(
"EvFDaqDirector") <<
"Detected stop request from hltd. Ending run for this process after LS -: "
537 timeval ts_lockbegin;
538 gettimeofday(&ts_lockbegin,
nullptr);
540 while (retval == -1) {
549 if (lock_attempts > 5000000 || errno == 116) {
552 <<
"Stale lock file handle. Checking if run directory and fu.lock file are present" << std::endl;
554 edm::LogWarning(
"EvFDaqDirector") <<
"Unable to obtain a lock for 5 seconds. Checking if run directory and "
555 "fu.lock file are present -: errno "
556 << errno <<
":" << strerror(errno) << std::endl;
559 edm::LogWarning(
"EvFDaqDirector") <<
"Detected local EoLS for lumisection " <<
ls;
571 if (total_lock_attempts > 5 * 60000000) {
572 edm::LogError(
"EvFDaqDirector") <<
"Unable to obtain a lock for 5 minutes. Stopping polling activity.";
578 gettimeofday(&ts_lockend,
nullptr);
579 long deltat = (ts_lockend.tv_usec - ts_lockbegin.tv_usec) + (ts_lockend.tv_sec - ts_lockbegin.tv_sec) * 1000000;
581 lockWaitTime = deltat;
588 gettimeofday(&ts_lockend, 0);
592 int fu_readwritelock_fd2 = open(
fulockfile_.c_str(), O_RDWR, S_IRWXU);
593 if (fu_readwritelock_fd2 == -1)
595 <<
" create. error:" << strerror(errno);
597 FILE* fu_rw_lock_stream2 = fdopen(fu_readwritelock_fd2,
"r+");
600 if (fu_rw_lock_stream2 !=
nullptr) {
604 check = fseek(fu_rw_lock_stream2, 0, SEEK_SET);
608 fscanf(fu_rw_lock_stream2,
"%u %u", &readLs, &
readIndex);
611 unsigned int currentLs = readLs;
612 bool bumpedOk =
false;
615 if (
ls &&
ls + 1 < currentLs)
619 bumpedOk =
bumpFile(readLs,
readIndex, nextFile, fsize, rawHeaderSize, stopFileLS, setExceptionState);
621 if (
ls && readLs > currentLs && currentLs >
ls) {
623 readLs = currentLs =
ls;
628 if (
ls == 0 && readLs > currentLs) {
643 check = fseek(fu_rw_lock_stream2, 0, SEEK_SET);
645 ftruncate(fu_readwritelock_fd2, 0);
647 fprintf(fu_rw_lock_stream2,
"%u %u", readLs,
readIndex + 1);
648 fflush(fu_rw_lock_stream2);
649 fsync(fu_readwritelock_fd2);
651 LogDebug(
"EvFDaqDirector") <<
"Written to file -: " << readLs <<
":" <<
readIndex + 1;
654 <<
"seek on fu read/write lock for updating failed with error " << strerror(errno);
655 setExceptionState =
true;
658 }
else if (currentLs < readLs) {
660 check = fseek(fu_rw_lock_stream2, 0, SEEK_SET);
662 ftruncate(fu_readwritelock_fd2, 0);
664 fprintf(fu_rw_lock_stream2,
"%u %u", readLs,
readIndex);
665 fflush(fu_rw_lock_stream2);
666 fsync(fu_readwritelock_fd2);
667 LogDebug(
"EvFDaqDirector") <<
"Written to file -: " << readLs <<
":" <<
readIndex;
670 <<
"seek on fu read/write lock for updating failed with error " << strerror(errno);
671 setExceptionState =
true;
676 edm::LogError(
"EvFDaqDirector") <<
"seek on fu read/write lock for reading failed with error "
680 edm::LogError(
"EvFDaqDirector") <<
"fu read/write lock stream is invalid " << strerror(errno);
682 fclose(fu_rw_lock_stream2);
685 timeval ts_preunlock;
686 gettimeofday(&ts_preunlock, 0);
687 int locked_period_int = ts_preunlock.tv_sec - ts_lockend.tv_sec;
688 double locked_period = locked_period_int + double(ts_preunlock.tv_usec - ts_lockend.tv_usec) / 1000000;
699 edm::LogError(
"EvFDaqDirector") <<
"Error unlocking the fu.lock " << strerror(errno);
702 edm::LogDebug(
"EvFDaqDirector") <<
"Waited during lock -: " << locked_period <<
" seconds";
705 if (fileStatus ==
noFile) {
710 if (stopFileLS >= 0 && (
int)
ls > stopFileLS) {
711 edm::LogInfo(
"EvFDaqDirector") <<
"Reached maximum lumisection set by hltd";
719 std::ifstream ij(BUEoLSFile);
723 if (!
reader.parse(ij, deserializeRoot)) {
724 edm::LogError(
"EvFDaqDirector") <<
"Cannot deserialize input JSON file -:" << BUEoLSFile;
730 dp.deserialize(deserializeRoot);
738 while (!
def.empty()) {
740 if (
def.find(
'/') == 0)
748 DataPointDefinition::getDataPointDefinitionFor(
fullpath, &eolsDpd, &defLabel);
753 DataPointDefinition::getDataPointDefinitionFor(
fullpath, &eolsDpd, &defLabel);
755 for (
unsigned int i = 0;
i < eolsDpd.
getNames().size();
i++)
756 if (eolsDpd.
getNames().at(
i) ==
"NFiles")
762 if (
def.size() <= 1 ||
def.find(
'/') == std::string::npos) {
773 edm::LogError(
"EvFDaqDirector") <<
" error reading number of files from BU JSON -: " << BUEoLSFile;
776 return boost::lexical_cast<int>(
data);
783 uint16_t& rawHeaderSize,
785 bool& setExceptionState) {
797 if (maxLS >= 0 &&
ls > (
unsigned int)maxLS)
801 std::stringstream
ss;
802 unsigned int nextIndex =
index;
807 if (
stat(nextFileJson.c_str(), &
buf) == 0) {
809 nextFile = nextFileJson;
818 nextFile = nextFileRaw;
824 if (
stat(BUEoLSFile.c_str(), &
buf) == 0) {
826 if (
stat(nextFileJson.c_str(), &
buf) == 0) {
828 nextFile = nextFileJson;
833 nextFile = nextFileRaw;
838 if (indexFilesInLS < 0)
843 if ((
int)
index < indexFilesInLS) {
846 <<
"Potential miss of index file in LS -: " <<
ls <<
". Missing " << nextFile <<
" because "
847 << indexFilesInLS - 1 <<
" is the highest index expected. Will not update fu.lock file";
848 setExceptionState =
true;
857 if (maxLS >= 0 &&
ls > (
unsigned int)maxLS)
862 if (
stat(nextFileJson.c_str(), &
buf) == 0) {
865 nextFile = nextFileJson;
870 nextFile = nextFileRaw;
882 edm::LogError(
"EvFDaqDirector") <<
"Error creating fu read/write lock stream " << strerror(errno);
884 edm::LogInfo(
"EvFDaqDirector") <<
"Initializing FU LOCK FILE";
893 open(
fulockfile_.c_str(), O_RDWR | O_CREAT, S_IRWXU | S_IWGRP | S_IRGRP | S_IWOTH | S_IROTH);
900 <<
" create:" <<
create <<
" error:" << strerror(errno);
906 edm::LogError(
"EvFDaqDirector") <<
"problem with opening fuwritelock file stream -: " << strerror(errno);
937 if (checkIfExists ==
false ||
stat(fuBoLS.c_str(), &
buf) != 0) {
938 int bol_fd = open(fuBoLS.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
944 const uint32_t currentLumiSection,
947 if (currentLumiSection > 0) {
954 open(fuEoLS.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
960 }
else if (doCreateBoLS) {
967 uint16_t& rawHeaderSize,
968 uint32_t& lsFromHeader,
969 int32_t& eventsFromHeader,
970 int64_t& fileSizeFromHeader,
976 if ((
infile = ::open(rawSourcePath.c_str(), O_RDONLY)) < 0) {
979 <<
"parseFRDFileHeader - failed to open input file -: " << rawSourcePath <<
" : " << strerror(errno);
990 if ((
infile = ::open(rawSourcePath.c_str(), O_RDONLY)) < 0) {
992 <<
"parseFRDFileHeader - failed to open input file -: " << rawSourcePath <<
" : " << strerror(errno);
1004 ssize_t sz_read =
::read(
infile, (
char*)&fileHead, buf_sz);
1011 edm::LogError(
"EvFDaqDirector") <<
"parseFRDFileHeader - unable to read " << rawSourcePath <<
" : "
1017 if ((
size_t)sz_read < buf_sz) {
1018 edm::LogError(
"EvFDaqDirector") <<
"parseFRDFileHeader - file smaller than header: " << rawSourcePath;
1026 if (frd_version == 0) {
1028 if (requireHeader) {
1029 edm::LogError(
"EvFDaqDirector") <<
"no header or invalid version string found in:" << rawSourcePath;
1035 lseek(
infile, 0, SEEK_SET);
1038 eventsFromHeader = -1;
1039 fileSizeFromHeader = -1;
1043 uint32_t headerSizeRaw = fileHead.headerSize_;
1044 if (headerSizeRaw < buf_sz) {
1045 edm::LogError(
"EvFDaqDirector") <<
"inconsistent header size: " << rawSourcePath <<
" size: " << headerSizeRaw
1046 <<
" v:" << frd_version;
1052 lsFromHeader = fileHead.lumiSection_;
1053 eventsFromHeader = (int32_t)fileHead.eventCount_;
1054 fileSizeFromHeader = (int64_t)fileHead.fileSize_;
1055 rawHeaderSize = fileHead.headerSize_;
1063 if ((
infile = ::open(rawSourcePath.c_str(), O_RDONLY)) < 0) {
1064 edm::LogWarning(
"EvFDaqDirector") <<
"rawFileHasHeader - failed to open input file -: " << rawSourcePath <<
" : "
1071 ssize_t sz_read =
::read(
infile, (
char*)&fileHead, buf_sz);
1074 edm::LogError(
"EvFDaqDirector") <<
"rawFileHasHeader - unable to read " << rawSourcePath <<
" : "
1080 if ((
size_t)sz_read < buf_sz) {
1081 edm::LogError(
"EvFDaqDirector") <<
"rawFileHasHeader - file smaller than header: " << rawSourcePath;
1091 if (frd_version > 0) {
1092 rawHeaderSize = fileHead.headerSize_;
1102 uint16_t& rawHeaderSize,
1103 int64_t& fileSizeFromHeader,
1111 size_t pos = 0, n_tokens = 0;
1112 while (n_tokens++ < 3 && (
pos = jsonStem.find(
'_',
pos + 1)) != std::string::npos) {
1116 std::ostringstream fileNameWithPID;
1118 fileNameWithPID << reducedJsonStem <<
"_pid" << std::setfill(
'0') << std::setw(5) <<
pid_ <<
".jsn";
1122 LogDebug(
"EvFDaqDirector") <<
"RAW parse -: " << rawSourcePath <<
" and JSON create " << jsonDestPath;
1126 int32_t nbEventsWrittenRaw;
1127 int64_t fileSizeFromRaw;
1129 rawSourcePath, rawFd, rawHeaderSize, lsFromRaw, nbEventsWrittenRaw, fileSizeFromRaw,
true,
true, closeFile);
1137 int oflag = O_CREAT | O_WRONLY | O_TRUNC | O_EXCL;
1138 int omode = S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP | S_IWOTH | S_IROTH;
1139 if ((
outfile = ::open(jsonDestPath.c_str(), oflag, omode)) < 0) {
1140 if (errno == EEXIST) {
1141 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFromRaw - destination file already exists -: " << jsonDestPath
1145 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFromRaw - failed to open output file -: " << jsonDestPath <<
" : "
1147 struct stat out_stat;
1148 if (
stat(jsonDestPath.c_str(), &out_stat) == 0) {
1150 <<
"grabNextJsonFromRaw - output file possibly got created with error, deleting and retry -: "
1152 if (unlink(jsonDestPath.c_str()) == -1) {
1154 <<
"grabNextJsonFromRaw - failed to remove -: " << jsonDestPath <<
" : " << strerror(errno);
1157 if ((
outfile = ::open(jsonDestPath.c_str(), oflag, omode)) < 0) {
1158 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFromRaw - failed to open output file (on retry) -: "
1159 << jsonDestPath <<
" : " << strerror(errno);
1164 std::stringstream
ss;
1165 ss <<
"{\"data\":[" << nbEventsWrittenRaw <<
"," << fileSizeFromRaw <<
",\"" << rawSourcePath <<
"\"]}";
1169 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFromRaw - failed to write to output file file -: " << jsonDestPath
1170 <<
" : " << strerror(errno);
1174 if (serverLS && serverLS != lsFromRaw)
1175 edm::LogWarning(
"EvFDaqDirector") <<
"grabNextJsonFromRaw - mismatch in expected (server) LS " << serverLS
1176 <<
" and raw file header LS " << lsFromRaw;
1178 fileSizeFromHeader = fileSizeFromRaw;
1179 return nbEventsWrittenRaw;
1184 int64_t& fileSizeFromJson,
1189 std::ostringstream fileNameWithPID;
1190 fileNameWithPID <<
std::filesystem::path(rawSourcePath).stem().string() <<
"_pid" << std::setfill(
'0')
1191 << std::setw(5) <<
pid_ <<
".jsn";
1196 LogDebug(
"EvFDaqDirector") <<
"JSON rename -: " << jsonSourcePath <<
" to " << jsonDestPath;
1200 if ((
infile = ::open(jsonSourcePath.c_str(), O_RDONLY)) < 0) {
1201 edm::LogWarning(
"EvFDaqDirector") <<
"grabNextJsonFile - failed to open input file -: " << jsonSourcePath <<
" : "
1203 if ((
infile = ::open(jsonSourcePath.c_str(), O_RDONLY)) < 0) {
1204 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - failed to open input file (on retry) -: "
1205 << jsonSourcePath <<
" : " << strerror(errno);
1206 if (errno == ENOENT)
1212 int oflag = O_CREAT | O_WRONLY | O_TRUNC | O_EXCL;
1213 int omode = S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP | S_IWOTH | S_IROTH;
1214 if ((
outfile = ::open(jsonDestPath.c_str(), oflag, omode)) < 0) {
1215 if (errno == EEXIST) {
1216 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - destination file already exists -: " << jsonDestPath
1221 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - failed to open output file -: " << jsonDestPath <<
" : "
1223 struct stat out_stat;
1224 if (
stat(jsonDestPath.c_str(), &out_stat) == 0) {
1226 <<
"grabNextJsonFile - output file possibly got created with error, deleting and retry -: " << jsonDestPath;
1227 if (unlink(jsonDestPath.c_str()) == -1) {
1229 <<
"grabNextJsonFile - failed to remove -: " << jsonDestPath <<
" : " << strerror(errno);
1232 if ((
outfile = ::open(jsonDestPath.c_str(), oflag, omode)) < 0) {
1233 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - failed to open output file (on retry) -: "
1234 << jsonDestPath <<
" : " << strerror(errno);
1240 const std::size_t buf_sz = 512;
1241 std::size_t tot_written = 0;
1242 std::unique_ptr<char>
buf(
new char[buf_sz]);
1244 ssize_t sz, sz_read = 1, sz_write;
1245 while (sz_read > 0 && (sz_read = ::
read(
infile,
buf.get(), buf_sz)) > 0) {
1248 assert(sz_read - sz_write > 0);
1249 if ((sz = ::
write(
outfile,
buf.get() + sz_write, sz_read - sz_write)) < 0) {
1256 }
while (sz_write < sz_read);
1261 if (tot_written > 0) {
1263 if (unlink(jsonSourcePath.c_str()) == -1) {
1264 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - failed to remove -: " << jsonSourcePath <<
" : "
1269 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - failed to copy json file or file was empty -: "
1278 std::stringstream
ss;
1281 if (tot_written <= buf_sz) {
1286 std::ifstream ij(jsonDestPath);
1288 }
catch (std::filesystem::filesystem_error
const& ex) {
1289 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - FILESYSTEM ERROR CAUGHT -: " << ex.what();
1295 if (tot_written <= buf_sz)
1297 edm::LogError(
"EvFDaqDirector") <<
"Failed to deserialize JSON file -: " << jsonDestPath <<
"\nERROR:\n"
1298 <<
reader.getFormatedErrorMessages() <<
"CONTENT:\n"
1305 dp.deserialize(deserializeRoot);
1309 if (
i <
dp.getData().size()) {
1316 if (!
dp.getData().empty())
1320 <<
"grabNextJsonFile - "
1321 <<
" error reading number of events from BU JSON; No input value. data -: " <<
data;
1327 fileSizeFromJson = -1;
1330 if (
i <
dp.getData().size()) {
1333 fileSizeFromJson = boost::lexical_cast<long>(dataSize);
1334 }
catch (boost::bad_lexical_cast
const&) {
1336 edm::LogWarning(
"EvFDaqDirector") <<
"grabNextJsonFile - error parsing number of Bytes from BU JSON. "
1337 <<
"Input value is -: " << dataSize;
1343 return boost::lexical_cast<int>(
data);
1344 }
catch (boost::bad_lexical_cast
const&
e) {
1345 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - error parsing number of events from BU JSON. "
1346 <<
"Input value is -: " <<
data;
1347 }
catch (std::runtime_error
const&
e) {
1349 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - std::runtime_error exception -: " <<
e.what();
1353 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - SOME OTHER EXCEPTION OCCURED! -: " <<
e.what();
1356 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - SOME OTHER EXCEPTION OCCURED!";
1369 std::ostringstream fileNameWithPID;
1370 fileNameWithPID << jsonSourcePath.stem().string() <<
"_pid" << std::setfill(
'0') << std::setw(5) << getpid()
1372 jsonDestPath /= fileNameWithPID.str();
1374 LogDebug(
"EvFDaqDirector") <<
"JSON rename -: " << jsonSourcePath <<
" to " << jsonDestPath;
1377 }
catch (std::filesystem::filesystem_error
const& ex) {
1379 edm::LogError(
"EvFDaqDirector") <<
"grabNextFile BOOST FILESYSTEM ERROR CAUGHT -: " << ex.what();
1389 }
catch (std::filesystem::filesystem_error
const& ex) {
1391 edm::LogError(
"EvFDaqDirector") <<
"grabNextFile BOOST FILESYSTEM ERROR CAUGHT -: " << ex.what();
1394 edm::LogError(
"EvFDaqDirector") <<
"grabNextFile std::exception CAUGHT -: " << ex.what();
1397 std::ifstream ij(jsonDestPath);
1401 std::stringstream
ss;
1403 if (!
reader.parse(
ss.str(), deserializeRoot)) {
1404 edm::LogError(
"EvFDaqDirector") <<
"grabNextFile Failed to deserialize JSON file -: " << jsonDestPath
1406 <<
reader.getFormatedErrorMessages() <<
"CONTENT:\n"
1408 throw std::runtime_error(
"Cannot deserialize input JSON file");
1414 dp.deserialize(deserializeRoot);
1418 if (
i <
dp.getData().size()) {
1424 if (!
dp.getData().empty())
1428 <<
" error reading number of events from BU JSON -: No input value " <<
data;
1430 return boost::lexical_cast<int>(
data);
1431 }
catch (std::filesystem::filesystem_error
const& ex) {
1434 edm::LogError(
"EvFDaqDirector") <<
"grabNextFile BOOST FILESYSTEM ERROR CAUGHT -: " << ex.what();
1435 }
catch (std::runtime_error
const&
e) {
1438 edm::LogError(
"EvFDaqDirector") <<
"grabNextFile runtime Exception -: " <<
e.what();
1439 }
catch (boost::bad_lexical_cast
const&) {
1440 edm::LogError(
"EvFDaqDirector") <<
"grabNextFile error parsing number of events from BU JSON. "
1441 <<
"Input value is -: " <<
data;
1445 edm::LogError(
"EvFDaqDirector") <<
"grabNextFile SOME OTHER EXCEPTION OCCURED!!!! -: " <<
e.what();
1454 uint32_t& closedServerLS,
1460 serverError =
false;
1462 boost::system::error_code ec;
1470 edm::LogWarning(
"EvFDaqDirector") <<
"boost::asio::connect error -:" << ec;
1476 boost::asio::streambuf request;
1477 std::ostream request_stream(&request);
1480 std::stringstream spath;
1481 spath <<
path <<
"&stopls=" << maxLS;
1485 request_stream <<
"GET " <<
path <<
" HTTP/1.1\r\n";
1487 request_stream <<
"Accept: */*\r\n";
1488 request_stream <<
"Connection: keep-alive\r\n\r\n";
1493 edm::LogInfo(
"EvFDaqDirector") <<
"reconnecting socket on received connection_reset";
1497 edm::LogWarning(
"EvFDaqDirector") <<
"boost::asio::connect error -:" << ec;
1503 edm::LogWarning(
"EvFDaqDirector") <<
"boost::asio::write error -:" << ec;
1508 boost::asio::streambuf response;
1509 boost::asio::read_until(*
socket_, response,
"\r\n", ec);
1511 edm::LogWarning(
"EvFDaqDirector") <<
"boost::asio::read_until error -:" << ec;
1516 std::istream response_stream(&response);
1519 response_stream >> http_version;
1521 response_stream >> serverHttpStatus;
1524 std::getline(response_stream, status_message);
1525 if (!response_stream || http_version.substr(0, 5) !=
"HTTP/") {
1530 if (serverHttpStatus != 200) {
1531 edm::LogWarning(
"EvFDaqDirector") <<
"Response returned with status code " << serverHttpStatus;
1538 while (std::getline(response_stream,
header) &&
header !=
"\r") {
1542 std::map<std::string, std::string> serverMap;
1543 while (std::getline(response_stream, fileInfo) && fileInfo !=
"\r") {
1544 auto pos = fileInfo.find(
'=');
1545 if (
pos == std::string::npos)
1547 auto stitle = fileInfo.substr(0,
pos);
1548 auto svalue = fileInfo.substr(
pos + 1);
1549 serverMap[stitle] = svalue;
1553 auto server_version = serverMap.find(
"version");
1554 assert(server_version != serverMap.end());
1556 auto server_run = serverMap.find(
"runnumber");
1557 assert(server_run != serverMap.end());
1560 auto server_state = serverMap.find(
"state");
1561 assert(server_state != serverMap.end());
1563 auto server_eols = serverMap.find(
"lasteols");
1564 assert(server_eols != serverMap.end());
1566 auto server_ls = serverMap.find(
"lumisection");
1568 int version_maj = 1;
1569 int version_min = 0;
1570 int version_rev = 0;
1572 auto* s_ptr = server_version->second.c_str();
1573 if (!server_version->second.empty() && server_version->second[0] ==
'"')
1575 auto res = sscanf(s_ptr,
"%d.%d.%d", &version_maj, &version_min, &version_rev);
1577 res = sscanf(s_ptr,
"%d.%d", &version_maj, &version_min);
1579 res = sscanf(s_ptr,
"%d", &version_maj);
1582 edm::LogWarning(
"EvFDaqDirector") <<
"Can not parse server version " << server_version->second;
1589 if (server_ls != serverMap.end())
1592 serverLS = closedServerLS + 1;
1595 if (s_state ==
"STARTING")
1597 auto server_file = serverMap.find(
"file");
1598 assert(server_file == serverMap.end());
1600 edm::LogInfo(
"EvFDaqDirector") <<
"Got STARTING notification with last EOLS " << closedServerLS;
1601 }
else if (s_state ==
"READY") {
1602 auto server_file = serverMap.find(
"file");
1603 if (server_file == serverMap.end()) {
1605 if (serverLS <= closedServerLS)
1606 serverLS = closedServerLS + 1;
1609 <<
"Got READY notification with last EOLS " << closedServerLS <<
" and no new file";
1613 auto server_fileprefix = serverMap.find(
"fileprefix");
1615 if (server_fileprefix != serverMap.end()) {
1616 auto pssize = server_fileprefix->second.size();
1617 if (pssize > 1 && server_fileprefix->second[0] ==
'"' && server_fileprefix->second[pssize - 1] ==
'"')
1618 fileprefix = server_fileprefix->second.substr(1, pssize - 2);
1620 fileprefix = server_fileprefix->second;
1624 auto ssize = server_file->second.size();
1625 if (ssize > 1 && server_file->second[0] ==
'"' && server_file->second[ssize - 1] ==
'"')
1626 filestem = server_file->second.substr(1, ssize - 2);
1628 filestem = server_file->second;
1629 assert(!filestem.empty());
1630 if (version_maj > 1) {
1631 nextFileRaw =
bu_run_dir_ +
"/" + fileprefix + filestem +
".raw";
1632 filestem =
bu_run_dir_ +
"/" + fileprefix + filestem;
1636 nextFileRaw =
bu_run_dir_ +
"/" + filestem +
".raw";
1637 filestem =
bu_run_dir_ +
"/" + fileprefix + filestem;
1638 nextFileJson = filestem +
".jsn";
1642 edm::LogInfo(
"EvFDaqDirector") <<
"Got READY notification with last EOLS " << closedServerLS <<
" new LS "
1643 << serverLS <<
" file:" << filestem;
1645 }
else if (s_state ==
"EOLS") {
1646 serverLS = closedServerLS + 1;
1647 edm::LogInfo(
"EvFDaqDirector") <<
"Got EOLS notification with last EOLS " << closedServerLS;
1649 }
else if (s_state ==
"EOR") {
1651 edm::LogInfo(
"EvFDaqDirector") <<
"Got EOR notification with last EOLS " << closedServerLS;
1653 }
else if (s_state ==
"NORUN") {
1654 auto err_msg = serverMap.find(
"errormessage");
1655 if (err_msg != serverMap.end())
1656 edm::LogWarning(
"EvFDaqDirector") <<
"Server NORUN -:" << server_state->second <<
" : " << err_msg->second;
1661 }
else if (s_state ==
"ERROR") {
1662 auto err_msg = serverMap.find(
"errormessage");
1663 if (err_msg != serverMap.end())
1664 edm::LogWarning(
"EvFDaqDirector") <<
"Server error -:" << server_state->second <<
" : " << err_msg->second;
1666 edm::LogWarning(
"EvFDaqDirector") <<
"Server error -:" << server_state->second;
1670 edm::LogWarning(
"EvFDaqDirector") <<
"Unknown Server state -:" << server_state->second;
1679 if (ec != boost::asio::error::eof) {
1680 edm::LogWarning(
"EvFDaqDirector") <<
"boost::asio::read_until error -:" << ec;
1694 socket_->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
1696 edm::LogWarning(
"EvFDaqDirector") <<
"socket shutdown error -:" << ec;
1721 uint16_t& rawHeaderSize,
1722 int32_t& serverEventsInNewFile,
1723 int64_t& fileSizeFromMetadata,
1732 int stopFileLS = -1;
1735 if (stopFileCheck == 0 || stopFilePidCheck == 0) {
1736 if (stopFileCheck == 0)
1742 if (stopFileLS >= 0 && (
int)
ls >= stopFileLS)
1746 edm::LogWarning(
"EvFDaqDirector") <<
"Detected stop request from hltd. Ending run for this process after LS -: "
1760 timeval ts_lockbegin;
1761 gettimeofday(&ts_lockbegin,
nullptr);
1764 uint32_t serverLS, closedServerLS;
1765 unsigned int serverHttpStatus;
1772 int maxLS = stopFileLS < 0 ? -1 :
std::max(stopFileLS, (
int)currentLumiSection);
1773 bool rawHeader =
false;
1775 serverHttpStatus, serverError, serverLS, closedServerLS, nextFileJson, nextFileRaw, rawHeader, maxLS);
1785 if (currentLumiSection == 0) {
1791 if (closedServerLS >= currentLumiSection) {
1793 for (uint32_t
i =
std::max(currentLumiSection, 1
U);
i <= closedServerLS;
i++)
1798 bool fileFound =
true;
1802 serverEventsInNewFile =
1803 grabNextJsonFromRaw(nextFileRaw, rawFd, rawHeaderSize, fileSizeFromMetadata, fileFound, serverLS,
false);
1805 serverEventsInNewFile =
grabNextJsonFile(nextFileJson, nextFileRaw, fileSizeFromMetadata, fileFound);
1808 if (serverEventsInNewFile < 0 && rawFd != -1) {
1829 if (currentLumiSection == 0) {
1839 if (closedServerLS >= currentLumiSection) {
1842 for (uint32_t
i =
std::max(currentLumiSection, 1
U);
i <= closedServerLS;
i++)
1850 else if (fileStatus ==
newFile) {
1853 }
else if (fileStatus ==
noFile) {
1857 edm::LogWarning(
"EvFDaqDirector") <<
"Server reported LS " << serverLS
1858 <<
" which is smaller than currently open LS " <<
ls <<
". Ignoring response";
1870 if (!std::filesystem::is_directory(openPath)) {
1871 LogDebug(
"EvFDaqDirector") <<
"<open> FU dir not found. Creating... -:" << openPath.string();
1872 std::filesystem::create_directories(openPath);
1877 std::ifstream ij(
file);
1881 if (!
reader.parse(ij, deserializeRoot)) {
1882 edm::LogError(
"EvFDaqDirector") <<
"Cannot deserialize input JSON file -:" <<
file;
1886 int ret = deserializeRoot.
get(
"lastLS",
"").
asInt();
1896 std::stringstream
ss;
1897 ss << fileprefix << std::setfill(
'0') << std::setw(4) << lscount <<
"_EoLS.jsn";
1915 std::vector<std::string>
destinations = tsPset.getParameter<std::vector<std::string>>(
"destinations");
1917 destinationsVal.append(
dest);
1918 (*transferSystemJson_)[
"destinations"] = destinationsVal;
1921 std::vector<std::string> modes = tsPset.getParameter<std::vector<std::string>>(
"transferModes");
1922 for (
auto&
mode : modes)
1924 (*transferSystemJson_)[
"transferModes"] = modesVal;
1926 for (
auto psKeyItr = tsPset.psetTable().begin(); psKeyItr != tsPset.psetTable().end(); ++psKeyItr) {
1927 if (psKeyItr->first !=
"destinations" && psKeyItr->first !=
"transferModes") {
1930 for (
auto&
mode : modes) {
1932 if (!streamDef.
existsAs<std::vector<std::string>>(
mode,
true))
1934 <<
" Missing transfer system specification for -:" << psKeyItr->first <<
" (transferMode " <<
mode
1936 std::vector<std::string> streamDestinations = streamDef.
getParameter<std::vector<std::string>>(
mode);
1940 if (streamDestinations.empty())
1942 <<
" Missing transter system destination(s) for -: " << psKeyItr->first <<
", mode:" <<
mode;
1944 for (
auto& sdest : streamDestinations) {
1945 bool sDestValid =
false;
1946 sDestsValue.append(sdest);
1953 <<
" Invalid transter system destination specified for -: " << psKeyItr->first <<
", mode:" <<
mode
1954 <<
", dest:" << sdest;
1956 streamVal[
mode] = sDestsValue;
1958 (*transferSystemJson_)[psKeyItr->first] = streamVal;
1963 throw cms::Exception(
"EvFDaqDirector") <<
"transferSystem PSet not found";
1970 streamRequestName =
stream;
1972 std::stringstream
msg;
1973 msg <<
"Transfer system mode definitions missing for -: " <<
stream;
1984 <<
"Selected mode string is not provided as DaqDirector parameter."
1985 <<
"Switch on requireTSPSet parameter to enforce this requirement. Setting mode to empty string.";
1989 throw cms::Exception(
"EvFDaqDirector") <<
"Selected mode string is not provided as DaqDirector parameter.";
1993 std::stringstream
msg;
2008 ret += (*it).asString();
2023 tbb::concurrent_hash_map<std::string, std::string>::accessor ac;
2025 ac->second = streamType;
2032 tbb::concurrent_hash_map<std::string, std::string>::const_accessor search_ac;
2034 return search_ac->second;
2036 edm::LogInfo(
"EvFDaqDirector") <<
" No merging type specified for stream " <<
stream <<
". Using default value";
2038 tbb::concurrent_hash_map<std::string, std::string>::accessor ac;
2040 ac->second = defaultName;
2047 int proc_flag_fd = open(proc_flag.c_str(), O_RDWR | O_CREAT, S_IRWXU | S_IWGRP | S_IRGRP | S_IWOTH | S_IROTH);
2048 close(proc_flag_fd);
2051 struct flock
EvFDaqDirector::make_flock(short type, short whence, off_t start, off_t len, pid_t pid) {