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,
946 if (currentLumiSection > 0) {
951 int eol_fd = open(fuEoLS.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
956 }
else if (doCreateBoLS) {
963 uint16_t& rawHeaderSize,
964 uint32_t& lsFromHeader,
965 int32_t& eventsFromHeader,
966 int64_t& fileSizeFromHeader,
972 if ((
infile = ::open(rawSourcePath.c_str(), O_RDONLY)) < 0) {
975 <<
"parseFRDFileHeader - failed to open input file -: " << rawSourcePath <<
" : " << strerror(errno);
986 if ((
infile = ::open(rawSourcePath.c_str(), O_RDONLY)) < 0) {
988 <<
"parseFRDFileHeader - failed to open input file -: " << rawSourcePath <<
" : " << strerror(errno);
1000 ssize_t sz_read =
::read(
infile, (
char*)&fileHead, buf_sz);
1007 edm::LogError(
"EvFDaqDirector") <<
"parseFRDFileHeader - unable to read " << rawSourcePath <<
" : "
1013 if ((
size_t)sz_read < buf_sz) {
1014 edm::LogError(
"EvFDaqDirector") <<
"parseFRDFileHeader - file smaller than header: " << rawSourcePath;
1022 if (frd_version == 0) {
1024 if (requireHeader) {
1025 edm::LogError(
"EvFDaqDirector") <<
"no header or invalid version string found in:" << rawSourcePath;
1031 lseek(
infile, 0, SEEK_SET);
1034 eventsFromHeader = -1;
1035 fileSizeFromHeader = -1;
1039 uint32_t headerSizeRaw = fileHead.headerSize_;
1040 if (headerSizeRaw < buf_sz) {
1041 edm::LogError(
"EvFDaqDirector") <<
"inconsistent header size: " << rawSourcePath <<
" size: " << headerSizeRaw
1042 <<
" v:" << frd_version;
1048 lsFromHeader = fileHead.lumiSection_;
1049 eventsFromHeader = (int32_t)fileHead.eventCount_;
1050 fileSizeFromHeader = (int64_t)fileHead.fileSize_;
1051 rawHeaderSize = fileHead.headerSize_;
1059 if ((
infile = ::open(rawSourcePath.c_str(), O_RDONLY)) < 0) {
1060 edm::LogWarning(
"EvFDaqDirector") <<
"rawFileHasHeader - failed to open input file -: " << rawSourcePath <<
" : "
1067 ssize_t sz_read =
::read(
infile, (
char*)&fileHead, buf_sz);
1070 edm::LogError(
"EvFDaqDirector") <<
"rawFileHasHeader - unable to read " << rawSourcePath <<
" : "
1076 if ((
size_t)sz_read < buf_sz) {
1077 edm::LogError(
"EvFDaqDirector") <<
"rawFileHasHeader - file smaller than header: " << rawSourcePath;
1087 if (frd_version > 0) {
1088 rawHeaderSize = fileHead.headerSize_;
1098 uint16_t& rawHeaderSize,
1099 int64_t& fileSizeFromHeader,
1107 size_t pos = 0, n_tokens = 0;
1108 while (n_tokens++ < 3 && (
pos = jsonStem.find(
'_',
pos + 1)) != std::string::npos) {
1112 std::ostringstream fileNameWithPID;
1114 fileNameWithPID << reducedJsonStem <<
"_pid" << std::setfill(
'0') << std::setw(5) <<
pid_ <<
".jsn";
1118 LogDebug(
"EvFDaqDirector") <<
"RAW parse -: " << rawSourcePath <<
" and JSON create " << jsonDestPath;
1122 int32_t nbEventsWrittenRaw;
1123 int64_t fileSizeFromRaw;
1125 rawSourcePath, rawFd, rawHeaderSize, lsFromRaw, nbEventsWrittenRaw, fileSizeFromRaw,
true,
true, closeFile);
1133 int oflag = O_CREAT | O_WRONLY | O_TRUNC | O_EXCL;
1134 int omode = S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP | S_IWOTH | S_IROTH;
1135 if ((
outfile = ::open(jsonDestPath.c_str(), oflag, omode)) < 0) {
1136 if (errno == EEXIST) {
1137 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFromRaw - destination file already exists -: " << jsonDestPath
1141 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFromRaw - failed to open output file -: " << jsonDestPath <<
" : "
1143 struct stat out_stat;
1144 if (
stat(jsonDestPath.c_str(), &out_stat) == 0) {
1146 <<
"grabNextJsonFromRaw - output file possibly got created with error, deleting and retry -: "
1148 if (unlink(jsonDestPath.c_str()) == -1) {
1150 <<
"grabNextJsonFromRaw - failed to remove -: " << jsonDestPath <<
" : " << strerror(errno);
1153 if ((
outfile = ::open(jsonDestPath.c_str(), oflag, omode)) < 0) {
1154 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFromRaw - failed to open output file (on retry) -: "
1155 << jsonDestPath <<
" : " << strerror(errno);
1160 std::stringstream
ss;
1161 ss <<
"{\"data\":[" << nbEventsWrittenRaw <<
"," << fileSizeFromRaw <<
",\"" << rawSourcePath <<
"\"]}";
1165 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFromRaw - failed to write to output file file -: " << jsonDestPath
1166 <<
" : " << strerror(errno);
1170 if (serverLS && serverLS != lsFromRaw)
1171 edm::LogWarning(
"EvFDaqDirector") <<
"grabNextJsonFromRaw - mismatch in expected (server) LS " << serverLS
1172 <<
" and raw file header LS " << lsFromRaw;
1174 fileSizeFromHeader = fileSizeFromRaw;
1175 return nbEventsWrittenRaw;
1180 int64_t& fileSizeFromJson,
1185 std::ostringstream fileNameWithPID;
1186 fileNameWithPID <<
std::filesystem::path(rawSourcePath).stem().string() <<
"_pid" << std::setfill(
'0')
1187 << std::setw(5) <<
pid_ <<
".jsn";
1192 LogDebug(
"EvFDaqDirector") <<
"JSON rename -: " << jsonSourcePath <<
" to " << jsonDestPath;
1196 if ((
infile = ::open(jsonSourcePath.c_str(), O_RDONLY)) < 0) {
1197 edm::LogWarning(
"EvFDaqDirector") <<
"grabNextJsonFile - failed to open input file -: " << jsonSourcePath <<
" : "
1199 if ((
infile = ::open(jsonSourcePath.c_str(), O_RDONLY)) < 0) {
1200 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - failed to open input file (on retry) -: "
1201 << jsonSourcePath <<
" : " << strerror(errno);
1202 if (errno == ENOENT)
1208 int oflag = O_CREAT | O_WRONLY | O_TRUNC | O_EXCL;
1209 int omode = S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP | S_IWOTH | S_IROTH;
1210 if ((
outfile = ::open(jsonDestPath.c_str(), oflag, omode)) < 0) {
1211 if (errno == EEXIST) {
1212 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - destination file already exists -: " << jsonDestPath
1217 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - failed to open output file -: " << jsonDestPath <<
" : "
1219 struct stat out_stat;
1220 if (
stat(jsonDestPath.c_str(), &out_stat) == 0) {
1222 <<
"grabNextJsonFile - output file possibly got created with error, deleting and retry -: " << jsonDestPath;
1223 if (unlink(jsonDestPath.c_str()) == -1) {
1225 <<
"grabNextJsonFile - failed to remove -: " << jsonDestPath <<
" : " << strerror(errno);
1228 if ((
outfile = ::open(jsonDestPath.c_str(), oflag, omode)) < 0) {
1229 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - failed to open output file (on retry) -: "
1230 << jsonDestPath <<
" : " << strerror(errno);
1236 const std::size_t buf_sz = 512;
1237 std::size_t tot_written = 0;
1238 std::unique_ptr<char>
buf(
new char[buf_sz]);
1240 ssize_t sz, sz_read = 1, sz_write;
1241 while (sz_read > 0 && (sz_read = ::
read(
infile,
buf.get(), buf_sz)) > 0) {
1244 assert(sz_read - sz_write > 0);
1245 if ((sz = ::
write(
outfile,
buf.get() + sz_write, sz_read - sz_write)) < 0) {
1252 }
while (sz_write < sz_read);
1257 if (tot_written > 0) {
1259 if (unlink(jsonSourcePath.c_str()) == -1) {
1260 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - failed to remove -: " << jsonSourcePath <<
" : "
1265 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - failed to copy json file or file was empty -: "
1274 std::stringstream
ss;
1277 if (tot_written <= buf_sz) {
1282 std::ifstream ij(jsonDestPath);
1284 }
catch (std::filesystem::filesystem_error
const& ex) {
1285 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - FILESYSTEM ERROR CAUGHT -: " << ex.what();
1291 if (tot_written <= buf_sz)
1293 edm::LogError(
"EvFDaqDirector") <<
"Failed to deserialize JSON file -: " << jsonDestPath <<
"\nERROR:\n"
1294 <<
reader.getFormatedErrorMessages() <<
"CONTENT:\n"
1301 dp.deserialize(deserializeRoot);
1305 if (
i <
dp.getData().size()) {
1312 if (!
dp.getData().empty())
1316 <<
"grabNextJsonFile - "
1317 <<
" error reading number of events from BU JSON; No input value. data -: " <<
data;
1323 fileSizeFromJson = -1;
1326 if (
i <
dp.getData().size()) {
1329 fileSizeFromJson = boost::lexical_cast<long>(dataSize);
1330 }
catch (boost::bad_lexical_cast
const&) {
1332 edm::LogWarning(
"EvFDaqDirector") <<
"grabNextJsonFile - error parsing number of Bytes from BU JSON. "
1333 <<
"Input value is -: " << dataSize;
1339 return boost::lexical_cast<int>(
data);
1340 }
catch (boost::bad_lexical_cast
const&
e) {
1341 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - error parsing number of events from BU JSON. "
1342 <<
"Input value is -: " <<
data;
1343 }
catch (std::runtime_error
const&
e) {
1345 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - std::runtime_error exception -: " <<
e.what();
1349 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - SOME OTHER EXCEPTION OCCURED! -: " <<
e.what();
1352 edm::LogError(
"EvFDaqDirector") <<
"grabNextJsonFile - SOME OTHER EXCEPTION OCCURED!";
1365 std::ostringstream fileNameWithPID;
1366 fileNameWithPID << jsonSourcePath.stem().string() <<
"_pid" << std::setfill(
'0') << std::setw(5) << getpid()
1368 jsonDestPath /= fileNameWithPID.str();
1370 LogDebug(
"EvFDaqDirector") <<
"JSON rename -: " << jsonSourcePath <<
" to " << jsonDestPath;
1373 }
catch (std::filesystem::filesystem_error
const& ex) {
1375 edm::LogError(
"EvFDaqDirector") <<
"grabNextFile BOOST FILESYSTEM ERROR CAUGHT -: " << ex.what();
1385 }
catch (std::filesystem::filesystem_error
const& ex) {
1387 edm::LogError(
"EvFDaqDirector") <<
"grabNextFile BOOST FILESYSTEM ERROR CAUGHT -: " << ex.what();
1390 edm::LogError(
"EvFDaqDirector") <<
"grabNextFile std::exception CAUGHT -: " << ex.what();
1393 std::ifstream ij(jsonDestPath);
1397 std::stringstream
ss;
1399 if (!
reader.parse(
ss.str(), deserializeRoot)) {
1400 edm::LogError(
"EvFDaqDirector") <<
"grabNextFile Failed to deserialize JSON file -: " << jsonDestPath
1402 <<
reader.getFormatedErrorMessages() <<
"CONTENT:\n"
1404 throw std::runtime_error(
"Cannot deserialize input JSON file");
1410 dp.deserialize(deserializeRoot);
1414 if (
i <
dp.getData().size()) {
1420 if (!
dp.getData().empty())
1424 <<
" error reading number of events from BU JSON -: No input value " <<
data;
1426 return boost::lexical_cast<int>(
data);
1427 }
catch (std::filesystem::filesystem_error
const& ex) {
1430 edm::LogError(
"EvFDaqDirector") <<
"grabNextFile BOOST FILESYSTEM ERROR CAUGHT -: " << ex.what();
1431 }
catch (std::runtime_error
const&
e) {
1434 edm::LogError(
"EvFDaqDirector") <<
"grabNextFile runtime Exception -: " <<
e.what();
1435 }
catch (boost::bad_lexical_cast
const&) {
1436 edm::LogError(
"EvFDaqDirector") <<
"grabNextFile error parsing number of events from BU JSON. "
1437 <<
"Input value is -: " <<
data;
1441 edm::LogError(
"EvFDaqDirector") <<
"grabNextFile SOME OTHER EXCEPTION OCCURED!!!! -: " <<
e.what();
1450 uint32_t& closedServerLS,
1456 serverError =
false;
1458 boost::system::error_code ec;
1466 edm::LogWarning(
"EvFDaqDirector") <<
"boost::asio::connect error -:" << ec;
1472 boost::asio::streambuf request;
1473 std::ostream request_stream(&request);
1476 std::stringstream spath;
1477 spath <<
path <<
"&stopls=" << maxLS;
1481 request_stream <<
"GET " <<
path <<
" HTTP/1.1\r\n";
1483 request_stream <<
"Accept: */*\r\n";
1484 request_stream <<
"Connection: keep-alive\r\n\r\n";
1489 edm::LogInfo(
"EvFDaqDirector") <<
"reconnecting socket on received connection_reset";
1493 edm::LogWarning(
"EvFDaqDirector") <<
"boost::asio::connect error -:" << ec;
1499 edm::LogWarning(
"EvFDaqDirector") <<
"boost::asio::write error -:" << ec;
1504 boost::asio::streambuf response;
1505 boost::asio::read_until(*
socket_, response,
"\r\n", ec);
1507 edm::LogWarning(
"EvFDaqDirector") <<
"boost::asio::read_until error -:" << ec;
1512 std::istream response_stream(&response);
1515 response_stream >> http_version;
1517 response_stream >> serverHttpStatus;
1520 std::getline(response_stream, status_message);
1521 if (!response_stream || http_version.substr(0, 5) !=
"HTTP/") {
1526 if (serverHttpStatus != 200) {
1527 edm::LogWarning(
"EvFDaqDirector") <<
"Response returned with status code " << serverHttpStatus;
1534 while (std::getline(response_stream,
header) &&
header !=
"\r") {
1538 std::map<std::string, std::string> serverMap;
1539 while (std::getline(response_stream, fileInfo) && fileInfo !=
"\r") {
1540 auto pos = fileInfo.find(
'=');
1541 if (
pos == std::string::npos)
1543 auto stitle = fileInfo.substr(0,
pos);
1544 auto svalue = fileInfo.substr(
pos + 1);
1545 serverMap[stitle] = svalue;
1549 auto server_version = serverMap.find(
"version");
1550 assert(server_version != serverMap.end());
1552 auto server_run = serverMap.find(
"runnumber");
1553 assert(server_run != serverMap.end());
1556 auto server_state = serverMap.find(
"state");
1557 assert(server_state != serverMap.end());
1559 auto server_eols = serverMap.find(
"lasteols");
1560 assert(server_eols != serverMap.end());
1562 auto server_ls = serverMap.find(
"lumisection");
1564 int version_maj = 1;
1565 int version_min = 0;
1566 int version_rev = 0;
1568 auto* s_ptr = server_version->second.c_str();
1569 if (!server_version->second.empty() && server_version->second[0] ==
'"')
1571 auto res = sscanf(s_ptr,
"%d.%d.%d", &version_maj, &version_min, &version_rev);
1573 res = sscanf(s_ptr,
"%d.%d", &version_maj, &version_min);
1575 res = sscanf(s_ptr,
"%d", &version_maj);
1578 edm::LogWarning(
"EvFDaqDirector") <<
"Can not parse server version " << server_version->second;
1585 if (server_ls != serverMap.end())
1588 serverLS = closedServerLS + 1;
1591 if (s_state ==
"STARTING")
1593 auto server_file = serverMap.find(
"file");
1594 assert(server_file == serverMap.end());
1596 edm::LogInfo(
"EvFDaqDirector") <<
"Got STARTING notification with last EOLS " << closedServerLS;
1597 }
else if (s_state ==
"READY") {
1598 auto server_file = serverMap.find(
"file");
1599 if (server_file == serverMap.end()) {
1601 if (serverLS <= closedServerLS)
1602 serverLS = closedServerLS + 1;
1605 <<
"Got READY notification with last EOLS " << closedServerLS <<
" and no new file";
1609 auto server_fileprefix = serverMap.find(
"fileprefix");
1611 if (server_fileprefix != serverMap.end()) {
1612 auto pssize = server_fileprefix->second.size();
1613 if (pssize > 1 && server_fileprefix->second[0] ==
'"' && server_fileprefix->second[pssize - 1] ==
'"')
1614 fileprefix = server_fileprefix->second.substr(1, pssize - 2);
1616 fileprefix = server_fileprefix->second;
1620 auto ssize = server_file->second.size();
1621 if (ssize > 1 && server_file->second[0] ==
'"' && server_file->second[ssize - 1] ==
'"')
1622 filestem = server_file->second.substr(1, ssize - 2);
1624 filestem = server_file->second;
1625 assert(!filestem.empty());
1626 if (version_maj > 1) {
1627 nextFileRaw =
bu_run_dir_ +
"/" + fileprefix + filestem +
".raw";
1628 filestem =
bu_run_dir_ +
"/" + fileprefix + filestem;
1632 nextFileRaw =
bu_run_dir_ +
"/" + filestem +
".raw";
1633 filestem =
bu_run_dir_ +
"/" + fileprefix + filestem;
1634 nextFileJson = filestem +
".jsn";
1638 edm::LogInfo(
"EvFDaqDirector") <<
"Got READY notification with last EOLS " << closedServerLS <<
" new LS "
1639 << serverLS <<
" file:" << filestem;
1641 }
else if (s_state ==
"EOLS") {
1642 serverLS = closedServerLS + 1;
1643 edm::LogInfo(
"EvFDaqDirector") <<
"Got EOLS notification with last EOLS " << closedServerLS;
1645 }
else if (s_state ==
"EOR") {
1647 edm::LogInfo(
"EvFDaqDirector") <<
"Got EOR notification with last EOLS " << closedServerLS;
1649 }
else if (s_state ==
"NORUN") {
1650 auto err_msg = serverMap.find(
"errormessage");
1651 if (err_msg != serverMap.end())
1652 edm::LogWarning(
"EvFDaqDirector") <<
"Server NORUN -:" << server_state->second <<
" : " << err_msg->second;
1657 }
else if (s_state ==
"ERROR") {
1658 auto err_msg = serverMap.find(
"errormessage");
1659 if (err_msg != serverMap.end())
1660 edm::LogWarning(
"EvFDaqDirector") <<
"Server error -:" << server_state->second <<
" : " << err_msg->second;
1662 edm::LogWarning(
"EvFDaqDirector") <<
"Server error -:" << server_state->second;
1666 edm::LogWarning(
"EvFDaqDirector") <<
"Unknown Server state -:" << server_state->second;
1675 if (ec != boost::asio::error::eof) {
1676 edm::LogWarning(
"EvFDaqDirector") <<
"boost::asio::read_until error -:" << ec;
1688 socket_->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
1690 edm::LogWarning(
"EvFDaqDirector") <<
"socket shutdown error -:" << ec;
1714 uint16_t& rawHeaderSize,
1715 int32_t& serverEventsInNewFile,
1716 int64_t& fileSizeFromMetadata,
1725 int stopFileLS = -1;
1728 if (stopFileCheck == 0 || stopFilePidCheck == 0) {
1729 if (stopFileCheck == 0)
1735 if (stopFileLS >= 0 && (
int)
ls >= stopFileLS)
1739 edm::LogWarning(
"EvFDaqDirector") <<
"Detected stop request from hltd. Ending run for this process after LS -: "
1753 timeval ts_lockbegin;
1754 gettimeofday(&ts_lockbegin,
nullptr);
1757 uint32_t serverLS, closedServerLS;
1758 unsigned int serverHttpStatus;
1765 int maxLS = stopFileLS < 0 ? -1 :
std::max(stopFileLS, (
int)currentLumiSection);
1766 bool rawHeader =
false;
1768 serverHttpStatus, serverError, serverLS, closedServerLS, nextFileJson, nextFileRaw, rawHeader, maxLS);
1778 if (currentLumiSection == 0) {
1786 if (closedServerLS >= currentLumiSection) {
1787 for (uint32_t
i =
std::max(currentLumiSection, 1
U);
i <= closedServerLS;
i++)
1792 bool fileFound =
true;
1796 serverEventsInNewFile =
1797 grabNextJsonFromRaw(nextFileRaw, rawFd, rawHeaderSize, fileSizeFromMetadata, fileFound, serverLS,
false);
1799 serverEventsInNewFile =
grabNextJsonFile(nextFileJson, nextFileRaw, fileSizeFromMetadata, fileFound);
1802 if (serverEventsInNewFile < 0 && rawFd != -1) {
1822 else if (fileStatus ==
newFile) {
1825 }
else if (fileStatus ==
noFile) {
1829 edm::LogWarning(
"EvFDaqDirector") <<
"Server reported LS " << serverLS
1830 <<
" which is smaller than currently open LS " <<
ls <<
". Ignoring response";
1842 if (!std::filesystem::is_directory(openPath)) {
1843 LogDebug(
"EvFDaqDirector") <<
"<open> FU dir not found. Creating... -:" << openPath.string();
1844 std::filesystem::create_directories(openPath);
1849 std::ifstream ij(
file);
1853 if (!
reader.parse(ij, deserializeRoot)) {
1854 edm::LogError(
"EvFDaqDirector") <<
"Cannot deserialize input JSON file -:" <<
file;
1858 int ret = deserializeRoot.
get(
"lastLS",
"").
asInt();
1868 std::stringstream
ss;
1869 ss << fileprefix << std::setfill(
'0') << std::setw(4) << lscount <<
"_EoLS.jsn";
1887 std::vector<std::string>
destinations = tsPset.getParameter<std::vector<std::string>>(
"destinations");
1889 destinationsVal.append(
dest);
1890 (*transferSystemJson_)[
"destinations"] = destinationsVal;
1893 std::vector<std::string> modes = tsPset.getParameter<std::vector<std::string>>(
"transferModes");
1894 for (
auto&
mode : modes)
1896 (*transferSystemJson_)[
"transferModes"] = modesVal;
1898 for (
auto psKeyItr = tsPset.psetTable().begin(); psKeyItr != tsPset.psetTable().end(); ++psKeyItr) {
1899 if (psKeyItr->first !=
"destinations" && psKeyItr->first !=
"transferModes") {
1902 for (
auto&
mode : modes) {
1904 if (!streamDef.
existsAs<std::vector<std::string>>(
mode,
true))
1906 <<
" Missing transfer system specification for -:" << psKeyItr->first <<
" (transferMode " <<
mode
1908 std::vector<std::string> streamDestinations = streamDef.
getParameter<std::vector<std::string>>(
mode);
1912 if (streamDestinations.empty())
1914 <<
" Missing transter system destination(s) for -: " << psKeyItr->first <<
", mode:" <<
mode;
1916 for (
auto& sdest : streamDestinations) {
1917 bool sDestValid =
false;
1918 sDestsValue.append(sdest);
1925 <<
" Invalid transter system destination specified for -: " << psKeyItr->first <<
", mode:" <<
mode
1926 <<
", dest:" << sdest;
1928 streamVal[
mode] = sDestsValue;
1930 (*transferSystemJson_)[psKeyItr->first] = streamVal;
1935 throw cms::Exception(
"EvFDaqDirector") <<
"transferSystem PSet not found";
1942 streamRequestName =
stream;
1944 std::stringstream
msg;
1945 msg <<
"Transfer system mode definitions missing for -: " <<
stream;
1956 <<
"Selected mode string is not provided as DaqDirector parameter."
1957 <<
"Switch on requireTSPSet parameter to enforce this requirement. Setting mode to empty string.";
1961 throw cms::Exception(
"EvFDaqDirector") <<
"Selected mode string is not provided as DaqDirector parameter.";
1965 std::stringstream
msg;
1980 ret += (*it).asString();
1995 tbb::concurrent_hash_map<std::string, std::string>::accessor ac;
1997 ac->second = streamType;
2004 tbb::concurrent_hash_map<std::string, std::string>::const_accessor search_ac;
2006 return search_ac->second;
2008 edm::LogInfo(
"EvFDaqDirector") <<
" No merging type specified for stream " <<
stream <<
". Using default value";
2010 tbb::concurrent_hash_map<std::string, std::string>::accessor ac;
2012 ac->second = defaultName;
2019 int proc_flag_fd = open(proc_flag.c_str(), O_RDWR | O_CREAT, S_IRWXU | S_IWGRP | S_IRGRP | S_IWOTH | S_IROTH);
2020 close(proc_flag_fd);
2023 struct flock
EvFDaqDirector::make_flock(short type, short whence, off_t start, off_t len, pid_t pid) {