CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
FedRawDataInputSource.cc
Go to the documentation of this file.
1 #include <fcntl.h>
2 #include <iomanip>
3 #include <iostream>
4 #include <sstream>
5 #include <sys/types.h>
6 #include <sys/file.h>
7 #include <sys/time.h>
8 #include <unistd.h>
9 #include <vector>
10 #include <fstream>
11 #include <zlib.h>
12 #include <stdio.h>
13 #include <chrono>
14 
15 #include <boost/algorithm/string.hpp>
16 #include <boost/filesystem/fstream.hpp>
17 
21 
24 
31 
35 
37 
41 
42 //JSON file reader
44 
45 #include <boost/lexical_cast.hpp>
46 
47 using namespace jsoncollector;
48 
50  edm::InputSourceDescription const& desc) :
51  edm::RawInputSource(pset, desc),
52  defPath_(pset.getUntrackedParameter<std::string> ("buDefPath", std::string(getenv("CMSSW_BASE"))+"/src/EventFilter/Utilities/plugins/budef.jsd")),
53  eventChunkSize_(pset.getUntrackedParameter<unsigned int> ("eventChunkSize",16)*1048576),
54  eventChunkBlock_(pset.getUntrackedParameter<unsigned int> ("eventChunkBlock",eventChunkSize_/1048576)*1048576),
55  numBuffers_(pset.getUntrackedParameter<unsigned int> ("numBuffers",1)),
56  getLSFromFilename_(pset.getUntrackedParameter<bool> ("getLSFromFilename", true)),
57  verifyAdler32_(pset.getUntrackedParameter<bool> ("verifyAdler32", true)),
58  useL1EventID_(pset.getUntrackedParameter<bool> ("useL1EventID", false)),
59  testModeNoBuilderUnit_(edm::Service<evf::EvFDaqDirector>()->getTestModeNoBuilderUnit()),
60  runNumber_(edm::Service<evf::EvFDaqDirector>()->getRunNumber()),
61  fuOutputDir_(edm::Service<evf::EvFDaqDirector>()->baseRunDir()),
62  daqProvenanceHelper_(edm::TypeID(typeid(FEDRawDataCollection))),
63  eventID_(),
64  processHistoryID_(),
65  currentLumiSection_(0),
66  eventsThisLumi_(0),
67  dpd_(nullptr)
68 {
69  char thishost[256];
70  gethostname(thishost, 255);
71  edm::LogInfo("FedRawDataInputSource") << "Construction. read-ahead chunk size -: "
72  << std::endl << (eventChunkSize_/1048576)
73  << " MB on host " << thishost;
75  edm::LogInfo("FedRawDataInputSource") << "Test mode is ON!";
76 
78  setNewRun();
81 
82  dpd_ = new DataPointDefinition();
83  std::string defLabel = "data";
84  DataPointDefinition::getDataPointDefinitionFor(defPath_, dpd_,&defLabel);
85 
86  //make sure that chunk size is N * block size
91 
92  if (!numBuffers_)
93  throw cms::Exception("FedRawDataInputSource::FedRawDataInputSource") <<
94  "no reading enabled with numBuffers parameter 0";
95 
98 
99  //het handles to DaqDirector and FastMonitoringService because it isn't acessible in readSupervisor thread
100 
101  try {
103  } catch (...){
104  edm::LogWarning("FedRawDataInputSource") << "FastMonitoringService not found";
105  assert(0);//test
106  }
107 
108  try {
110  //set DaqDirector to delete files in preGlobalEndLumi callback
113  if (fms_) daqDirector_->setFMS(fms_);
114  } catch (...){
115  edm::LogWarning("FedRawDataInputSource") << "EvFDaqDirector not found";
116  assert(0);//test
117  }
118 
119  //should delete chunks when run stops
120  for (unsigned int i=0;i<numBuffers_;i++) {
122  }
123 
124  quit_threads_ = false;
125 
126  for (unsigned int i=0;i<numConcurrentReads_;i++)
127  {
128  std::unique_lock<std::mutex> lk(startupLock_);
129  //issue a memory fence here and in threads (constructor was segfaulting without this)
130  thread_quit_signal.push_back(false);
131  workerJob_.push_back(ReaderInfo(nullptr,nullptr));
132  cvReader_.push_back(new std::condition_variable);
133  threadInit_.store(false,std::memory_order_release);
134  workerThreads_.push_back(new std::thread(&FedRawDataInputSource::readWorker,this,i));
135  startupCv_.wait(lk);
136  }
137 
138  runAuxiliary()->setProcessHistoryID(processHistoryID_);
139 }
140 
142 {
143  quit_threads_=true;
144 
145  //delete any remaining open files
146  for (auto it = filesToDelete_.begin();it!=filesToDelete_.end();it++) {
147  deleteFile(it->second->fileName_);
148  delete it->second;
149  }
151  readSupervisorThread_->join();
152  }
153  else {
154  //join aux threads in case the supervisor thread was not started
155  for (unsigned int i=0;i<workerThreads_.size();i++) {
156  std::unique_lock<std::mutex> lk(mReader_);
157  thread_quit_signal[i]=true;
158  cvReader_[i]->notify_one();
159  lk.unlock();
160  workerThreads_[i]->join();
161  delete workerThreads_[i];
162  }
163  }
164  for (unsigned int i=0;i<numConcurrentReads_;i++) delete cvReader_[i];
165  /*
166  for (unsigned int i=0;i<numConcurrentReads_+1;i++) {
167  InputChunk *ch;
168  while (!freeChunks_.try_pop(ch)) {}
169  delete ch;
170  }
171  */
172 }
173 
175 {
177  {
178  //this thread opens new files and dispatches reading to worker readers
179  //threadInit_.store(false,std::memory_order_release);
180  std::unique_lock<std::mutex> lk(startupLock_);
181  readSupervisorThread_.reset(new std::thread(&FedRawDataInputSource::readSupervisor,this));
183  startupCv_.wait(lk);
184  }
185  switch (nextEvent() ) {
187 
188  //maybe create EoL file in working directory before ending run
189  struct stat buf;
190  if ( currentLumiSection_ > 0 ) {
191  bool eolFound = (stat(daqDirector_->getEoLSFilePathOnBU(currentLumiSection_).c_str(), &buf) == 0);
192  if (eolFound) {
194  bool found = (stat(fuEoLS.c_str(), &buf) == 0);
195  if ( !found ) {
197  int eol_fd = open(fuEoLS.c_str(), O_RDWR|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
198  close(eol_fd);
200  }
201  }
202  }
203  //also create EoR file in FU data directory
204  bool eorFound = (stat(daqDirector_->getEoRFilePathOnFU().c_str(),&buf) == 0);
205  if (!eorFound) {
206  int eor_fd = open(daqDirector_->getEoRFilePathOnFU().c_str(), O_RDWR|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
207  close(eor_fd);
208  }
210  eventsThisLumi_=0;
212  edm::LogInfo("FedRawDataInputSource") << "----------------RUN ENDED----------------";
213  return false;
214  }
216  //this is not reachable
217  return true;
218  }
220  //std::cout << "--------------NEW LUMI---------------" << std::endl;
221  return true;
222  }
223  default: {
224  if (!getLSFromFilename_) {
225  //get new lumi from file header
226  if (event_->lumi() > currentLumiSection_) {
228  eventsThisLumi_=0;
229  maybeOpenNewLumiSection( event_->lumi() );
230  }
231  }
232  eventRunNumber_=event_->run();
233  L1EventID_ = event_->event();
234 
235  setEventCached();
236 
237  return true;
238  }
239  }
240 }
241 
242 void FedRawDataInputSource::maybeOpenNewLumiSection(const uint32_t lumiSection)
243 {
245  || luminosityBlockAuxiliary()->luminosityBlock() != lumiSection) {
246 
247  if ( currentLumiSection_ > 0 ) {
248  const std::string fuEoLS =
250  struct stat buf;
251  bool found = (stat(fuEoLS.c_str(), &buf) == 0);
252  if ( !found ) {
254  int eol_fd = open(fuEoLS.c_str(), O_RDWR|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
255  close(eol_fd);
257  }
258  }
259 
260  currentLumiSection_ = lumiSection;
261 
263 
264  timeval tv;
265  gettimeofday(&tv, 0);
266  const edm::Timestamp lsopentime( (unsigned long long) tv.tv_sec * 1000000 + (unsigned long long) tv.tv_usec );
267 
268  edm::LuminosityBlockAuxiliary* lumiBlockAuxiliary =
270  runAuxiliary()->run(),
271  lumiSection, lsopentime,
273 
274  setLuminosityBlockAuxiliary(lumiBlockAuxiliary);
275  luminosityBlockAuxiliary()->setProcessHistoryID(processHistoryID_);
276 
277  edm::LogInfo("FedRawDataInputSource") << "New lumi section was opened. LUMI -: "<< lumiSection;
278  }
279 }
280 
282 {
284  while ((status = getNextEvent())==evf::EvFDaqDirector::noFile)
285  {
286  if (edm::shutdown_flag.load(std::memory_order_relaxed)) break;
287  }
288  return status;
289 }
290 
292 {
293  const size_t headerSize[4] = {0,2*sizeof(uint32),(4 + 1024) * sizeof(uint32),7*sizeof(uint32)}; //size per version of FRDEventHeader
294 
296  if (!currentFile_)
297  {
298  if (!streamFileTrackerPtr_) {
302  }
303 
305  if (!fileQueue_.try_pop(currentFile_))
306  {
307  //sleep until wakeup (only in single-buffer mode) or timeout
308  std::unique_lock<std::mutex> lkw(mWakeup_);
309  if (cvWakeup_.wait_for(lkw, std::chrono::milliseconds(100)) == std::cv_status::timeout || !currentFile_)
311  }
312  status = currentFile_->status_;
313  if ( status == evf::EvFDaqDirector::runEnded)
314  {
315  delete currentFile_;
316  currentFile_=nullptr;
317  return status;
318  }
319 
320  else if (status == evf::EvFDaqDirector::newLumi)
321  {
322  if (getLSFromFilename_) {
325  eventsThisLumi_=0;
327  }
328  }
329  else {//let this be picked up from next event
331  }
332 
333  delete currentFile_;
334  currentFile_=nullptr;
335  return status;
336  }
337  else if (status == evf::EvFDaqDirector::newFile) {
340  }
341  else
342  assert(0);
343  }
344 
345  //file is empty
346  if (!currentFile_->fileSize_) {
347  //try to open new lumi
348  assert(currentFile_->nChunks_==0);
349  if (getLSFromFilename_)
352  eventsThisLumi_=0;
354  }
355  //immediately delete empty file
357  delete currentFile_;
358  currentFile_=nullptr;
360  }
361 
362  //file is finished
364  //release last chunk (it is never released elsewhere)
367  {
368  throw cms::Exception("RuntimeError")
369  << "Fully processed " << currentFile_->nProcessed_
370  << " from the file " << currentFile_->fileName_
371  << " but according to BU JSON there should be "
372  << currentFile_->nEvents_ << " events";
373  }
374  //try to wake up supervisor thread which might be sleeping waiting for the free chunk
375  if (singleBufferMode_) {
376  std::unique_lock<std::mutex> lkw(mWakeup_);
377  cvWakeup_.notify_one();
378  }
381  //put the file in pending delete list;
382  std::unique_lock<std::mutex> lkw(fileDeleteLock_);
383  filesToDelete_.push_back(std::pair<int,InputFile*>(currentFileIndex_,currentFile_));
384  }
385  else {
386  //in single-thread and stream jobs, events are already processed
388  delete currentFile_;
389  }
390  currentFile_=nullptr;
392  }
393 
394 
395  //file is too short
397  {
398  throw cms::Exception("FedRawDataInputSource::cacheNextEvent") <<
399  "Premature end of input file while reading event header";
400  }
401  if (singleBufferMode_) {
402 
403  //should already be there
405  usleep(10000);
407  }
408 
409  unsigned char *dataPosition = currentFile_->chunks_[0]->buf_+ currentFile_->chunkPosition_;
410 
411  //conditions when read amount is not sufficient for the header to fit
412  if (!bufferInputRead_ || bufferInputRead_ < headerSize[detectedFRDversion_]
413  || eventChunkSize_ - currentFile_->chunkPosition_ < headerSize[detectedFRDversion_])
414  {
416 
417  if (detectedFRDversion_==0) {
418  detectedFRDversion_=*((uint32*)dataPosition);
419  assert(detectedFRDversion_>=1 && detectedFRDversion_<=3);
420  }
421 
422  //recalculate chunk position
423  dataPosition = currentFile_->chunks_[0]->buf_+ currentFile_->chunkPosition_;
424  if ( bufferInputRead_ < headerSize[detectedFRDversion_])
425  {
426  throw cms::Exception("FedRawDataInputSource::cacheNextEvent") <<
427  "Premature end of input file while reading event header";
428  }
429  }
430 
431  event_.reset( new FRDEventMsgView(dataPosition) );
432  if (event_->size()>eventChunkSize_) {
433  throw cms::Exception("FedRawDataInputSource::nextEvent")
434  << " event id:"<< event_->event()<< " lumi:" << event_->lumi()
435  << " run:" << event_->run() << " of size:" << event_->size()
436  << " bytes does not fit into a chunk of size:" << eventChunkSize_ << " bytes";
437  }
438 
439  const uint32_t msgSize = event_->size()-headerSize[detectedFRDversion_];
440 
442  {
443  throw cms::Exception("FedRawDataInputSource::nextEvent") <<
444  "Premature end of input file while reading event data";
445  }
446  if (eventChunkSize_ - currentFile_->chunkPosition_ < msgSize) {
448  //recalculate chunk position
449  dataPosition = currentFile_->chunks_[0]->buf_+ currentFile_->chunkPosition_;
450  event_.reset( new FRDEventMsgView(dataPosition) );
451  }
452  currentFile_->bufferPosition_ += event_->size();
453  currentFile_->chunkPosition_ += event_->size();
454  //last chunk is released when this function is invoked next time
455 
456  }
457  //multibuffer mode:
458  else
459  {
460  //wait for the current chunk to become added to the vector
462  usleep(10000);
464  }
465 
466  //check if header is at the boundary of two chunks
467  chunkIsFree_ = false;
468  unsigned char *dataPosition;
469 
470  //read header, copy it to a single chunk if necessary
471  bool chunkEnd = currentFile_->advance(dataPosition,headerSize[detectedFRDversion_]);
472 
473  event_.reset( new FRDEventMsgView(dataPosition) );
474  if (event_->size()>eventChunkSize_) {
475  throw cms::Exception("FedRawDataInputSource::nextEvent")
476  << " event id:"<< event_->event()<< " lumi:" << event_->lumi()
477  << " run:" << event_->run() << " of size:" << event_->size()
478  << " bytes does not fit into a chunk of size:" << eventChunkSize_ << " bytes";
479  }
480 
481  const uint32_t msgSize = event_->size()-headerSize[detectedFRDversion_];
482 
484  {
485  throw cms::Exception("FedRawDataInputSource::nextEvent") <<
486  "Premature end of input file while reading event data";
487  }
488 
489  if (chunkEnd) {
490  //header was at the chunk boundary, we will have to move payload as well
491  currentFile_->moveToPreviousChunk(msgSize,headerSize[detectedFRDversion_]);
492  chunkIsFree_ = true;
493  }
494  else {
495  //header was contiguous, but check if payload fits the chunk
496  if (eventChunkSize_ - currentFile_->chunkPosition_ < msgSize) {
497  //rewind to header start position
498  currentFile_->rewindChunk(headerSize[detectedFRDversion_]);
499  //copy event to a chunk start and move pointers
500  chunkEnd = currentFile_->advance(dataPosition,headerSize[detectedFRDversion_]+msgSize);
501  assert(chunkEnd);
502  chunkIsFree_=true;
503  //header is moved
504  event_.reset( new FRDEventMsgView(dataPosition) );
505  }
506  else {
507  //everything is in a single chunk, only move pointers forward
508  chunkEnd = currentFile_->advance(dataPosition,msgSize);
509  assert(!chunkEnd);
510  chunkIsFree_=false;
511  }
512  }
513  }//end multibuffer mode
514 
515  if ( verifyAdler32_ && event_->version() >= 3 )
516  {
517  uint32_t adler = adler32(0L,Z_NULL,0);
518  adler = adler32(adler,(Bytef*)event_->payload(),event_->eventSize());
519 
520  if ( adler != event_->adler32() ) {
521  throw cms::Exception("FedRawDataInputSource::nextEvent") <<
522  "Found a wrong Adler32 checksum: expected 0x" << std::hex << event_->adler32() <<
523  " but calculated 0x" << adler;
524  }
525  }
527 
529 }
530 
532 {
533  const boost::filesystem::path filePath(fileName);
534  if (!testModeNoBuilderUnit_) {
535  LogDebug("FedRawDataInputSource") << "Deleting input file -:" << fileName;
536  try {
537  //sometimes this fails but file gets deleted
538  boost::filesystem::remove(filePath);
539  }
540  catch (const boost::filesystem::filesystem_error& ex)
541  {
542  edm::LogError("FedRawDataInputSource") << " - deleteFile BOOST FILESYSTEM ERROR CAUGHT -: " << ex.what()
543  << ". Trying again.";
544  usleep(100000);
545  try {
546  boost::filesystem::remove(filePath);
547  }
548  catch (...) {/*file gets deleted first time but exception is still thrown*/}
549  }
550  catch (std::exception& ex)
551  {
552  edm::LogError("FedRawDataInputSource") << " - deleteFile std::exception CAUGHT -: " << ex.what()
553  << ". Trying again.";
554  usleep(100000);
555  try {
556  boost::filesystem::remove(filePath);
557  } catch (...) {/*file gets deleted first time but exception is still thrown*/}
558  }
559  } else {
560  renameToNextFree(fileName);
561  }
562 }
563 
564 
566 {
567  std::auto_ptr<FEDRawDataCollection> rawData(new FEDRawDataCollection);
568  edm::Timestamp tstamp = fillFEDRawDataCollection(rawData);
569 
570  if (useL1EventID_)
572  else {
573  assert(GTPEventID_);
575  }
576 
577  edm::EventAuxiliary aux(eventID_, processGUID(), tstamp, true,
580  makeEvent(eventPrincipal, aux);
581 
584 
585  //FWCore/Sources DaqProvenanceHelper before 7_1_0_pre3
586  //eventPrincipal.put(daqProvenanceHelper_.constBranchDescription_, edp,
587  // daqProvenanceHelper_.dummyProvenance_);
588 
589  eventPrincipal.put(daqProvenanceHelper_.branchDescription(), edp,
591 
592  eventsThisLumi_++;
593 
594  //this old file check runs no more often than every 10 events
595  if (!((currentFile_->nProcessed_-1)%(checkEvery_))) {
596  //delete files that are not in processing
597  std::unique_lock<std::mutex> lkw(fileDeleteLock_);
598  auto it = filesToDelete_.begin();
599  while (it!=filesToDelete_.end()) {
600  bool fileIsBeingProcessed = false;
601  for (unsigned int i=0;i<nStreams_;i++) {
602  if (it->first == streamFileTrackerPtr_->at(i)) {
603  fileIsBeingProcessed = true;
604  break;
605  }
606  }
607  if (!fileIsBeingProcessed) {
608  deleteFile(it->second->fileName_);
609  delete it->second;
610  it = filesToDelete_.erase(it);
611  }
612  else it++;
613  }
614 
615  }
617  chunkIsFree_=false;
618  return;
619 }
620 
621 edm::Timestamp FedRawDataInputSource::fillFEDRawDataCollection(std::auto_ptr<FEDRawDataCollection>& rawData)
622 {
623  edm::Timestamp tstamp;
624  uint32_t eventSize = event_->eventSize();
625  char* event = (char*)event_->payload();
626  GTPEventID_=0;
627 
628  while (eventSize > 0) {
629  eventSize -= sizeof(fedt_t);
630  const fedt_t* fedTrailer = (fedt_t*) (event + eventSize);
631  const uint32_t fedSize = FED_EVSZ_EXTRACT(fedTrailer->eventsize) << 3; //trailer length counts in 8 bytes
632  eventSize -= (fedSize - sizeof(fedh_t));
633  const fedh_t* fedHeader = (fedh_t *) (event + eventSize);
634  const uint16_t fedId = FED_SOID_EXTRACT(fedHeader->sourceid);
635  if (fedId == FEDNumbering::MINTriggerGTPFEDID) {
636  if (evf::evtn::evm_board_sense((unsigned char*) fedHeader,fedSize))
637  GTPEventID_ = evf::evtn::get((unsigned char*) fedHeader,true);
638  else
639  GTPEventID_ = evf::evtn::get((unsigned char*) fedHeader,false);
640  //evf::evtn::evm_board_setformat(fedSize);
641  const uint64_t gpsl = evf::evtn::getgpslow((unsigned char*) fedHeader);
642  const uint64_t gpsh = evf::evtn::getgpshigh((unsigned char*) fedHeader);
643  tstamp = edm::Timestamp(static_cast<edm::TimeValue_t> ((gpsh << 32) + gpsl));
644  }
645  //take event ID from GTPE FED
646  if (fedId == FEDNumbering::MINTriggerEGTPFEDID && GTPEventID_==0) {
647  if (evf::evtn::gtpe_board_sense((unsigned char*)fedHeader)) {
648  GTPEventID_ = evf::evtn::gtpe_get((unsigned char*) fedHeader);
649  }
650  }
651  FEDRawData& fedData = rawData->FEDData(fedId);
652  fedData.resize(fedSize);
653  memcpy(fedData.data(), event + eventSize, fedSize);
654  }
655  assert(eventSize == 0);
656 
657  return tstamp;
658 }
659 
661 {
663  try {
664  // assemble json destination path
666 
667  //TODO:should be ported to use fffnaming
668  std::ostringstream fileNameWithPID;
669  fileNameWithPID << jsonSourcePath.stem().string() << "_pid"
670  << std::setfill('0') << std::setw(5) << getpid() << ".jsn";
671  jsonDestPath /= fileNameWithPID.str();
672 
673  LogDebug("FedRawDataInputSource") << "JSON rename -: " << jsonSourcePath << " to "
674  << jsonDestPath;
675 
677  boost::filesystem::copy(jsonSourcePath,jsonDestPath);
678  else {
679  try {
680  boost::filesystem::copy(jsonSourcePath,jsonDestPath);
681  }
682  catch (const boost::filesystem::filesystem_error& ex)
683  {
684  // Input dir gone?
685  edm::LogError("FedRawDataInputSource") << "grabNextFile BOOST FILESYSTEM ERROR CAUGHT -: " << ex.what();
686  // << " Maybe the file is not yet visible by FU. Trying again in one second";
687  sleep(1);
688  boost::filesystem::copy(jsonSourcePath,jsonDestPath);
689  }
691 
692 
693  try {
694  //sometimes this fails but file gets deleted
695  boost::filesystem::remove(jsonSourcePath);
696  }
697  catch (const boost::filesystem::filesystem_error& ex)
698  {
699  // Input dir gone?
700  edm::LogError("FedRawDataInputSource") << "grabNextFile BOOST FILESYSTEM ERROR CAUGHT -: " << ex.what();
701  }
702  catch (std::exception& ex)
703  {
704  // Input dir gone?
705  edm::LogError("FedRawDataInputSource") << "grabNextFile std::exception CAUGHT -: " << ex.what();
706  }
707 
708  }
709 
710  boost::filesystem::ifstream ij(jsonDestPath);
711  Json::Value deserializeRoot;
713 
714  if (!reader.parse(ij, deserializeRoot))
715  throw std::runtime_error("Cannot deserialize input JSON file");
716 
717  //read BU JSON
719  DataPoint dp;
720  dp.deserialize(deserializeRoot);
721  bool success = false;
722  for (unsigned int i=0;i<dpd_->getNames().size();i++) {
723  if (dpd_->getNames().at(i)=="NEvents")
724  if (i<dp.getData().size()) {
725  data = dp.getData()[i];
726  success=true;
727  }
728  }
729  if (!success) {
730  if (dp.getData().size())
731  data = dp.getData()[0];
732  else
733  throw cms::Exception("FedRawDataInputSource::grabNextJsonFile") <<
734  " error reading number of events from BU JSON -: No input value " << data;
735  }
736  return boost::lexical_cast<int>(data);
737 
738  }
739  catch (const boost::filesystem::filesystem_error& ex)
740  {
741  // Input dir gone?
743  edm::LogError("FedRawDataInputSource") << "grabNextFile - BOOST FILESYSTEM ERROR CAUGHT -: " << ex.what()
744  << " - Maybe the BU run dir disappeared? Ending process with code 0...";
745  _exit(-1);
746  }
747  catch (std::runtime_error e)
748  {
749  // Another process grabbed the file and NFS did not register this
751  edm::LogError("FedRawDataInputSource") << "grabNextFile - runtime Exception -: " << e.what();
752  }
753 
754  catch( boost::bad_lexical_cast const& ) {
755  edm::LogError("FedRawDataInputSource") << "grabNextFile - error parsing number of events from BU JSON. "
756  << "Input value is -: " << data;
757  }
758 
759  catch (std::exception e)
760  {
761  // BU run directory disappeared?
763  edm::LogError("FedRawDataInputSource") << "grabNextFile - SOME OTHER EXCEPTION OCCURED!!!! -: " << e.what();
764  }
765 
766  return -1;
767 }
768 
770 {
773 
774  edm::LogInfo("FedRawDataInputSource") << "Instead of delete, RENAME -: " << fileName
775  << " to: " << destination.string();
776  boost::filesystem::rename(source,destination);
777  boost::filesystem::rename(source.replace_extension(".jsn"),destination.replace_extension(".jsn"));
778 }
779 
781 {}
782 
783 void FedRawDataInputSource::postForkReacquireResources(boost::shared_ptr<edm::multicore::MessageReceiverForSource>)
784 {
785  InputSource::rewind();
789 }
790 
792 {}
793 
794 
796 {
797  bool stop=false;
798  unsigned int currentLumiSection = 0;
799  //threadInit_.exchange(true,std::memory_order_acquire);
800 
801  {
802  std::unique_lock<std::mutex> lk(startupLock_);
803  startupCv_.notify_one();
804  }
805 
806  while (!stop) {
807 
808  //wait for at least one free thread and chunk
809  int counter=0;
810  while ((workerPool_.empty() && !singleBufferMode_) || freeChunks_.empty())
811  {
812  std::unique_lock<std::mutex> lkw(mWakeup_);
813  //sleep until woken up by condition or a timeout
814  if (cvWakeup_.wait_for(lkw, std::chrono::milliseconds(100)) == std::cv_status::timeout) {
815  counter++;
816  //if (!(counter%50)) edm::LogInfo("FedRawDataInputSource") << "No free chunks or threads...";
817  LogDebug("FedRawDataInputSource") << "No free chunks or threads...";
818  }
819  else {
820  assert(!(workerPool_.empty() && !singleBufferMode_) || freeChunks_.empty());
821  }
822  if (quit_threads_.load(std::memory_order_relaxed) || edm::shutdown_flag.load(std::memory_order_relaxed)) {stop=true;break;}
823  }
824 
825  if (stop) break;
826 
827  //look for a new file
828  std::string nextFile;
829  uint32_t ls;
830  uint32_t fileSize;
831 
833 
835 
836  while (status == evf::EvFDaqDirector::noFile) {
837  if (quit_threads_.load(std::memory_order_relaxed) || edm::shutdown_flag.load(std::memory_order_relaxed)) {
838  stop=true;
839  break;
840  }
841  else
842  status = daqDirector_->updateFuLock(ls,nextFile,fileSize);
843 
844  if ( status == evf::EvFDaqDirector::runEnded) {
846  stop=true;
847  break;
848  }
849 
850  //queue new lumisection
851  if( getLSFromFilename_ && ls > currentLumiSection) {
852  currentLumiSection = ls;
853  fileQueue_.push(new InputFile(evf::EvFDaqDirector::newLumi, currentLumiSection));
854  }
855 
856  if( getLSFromFilename_ && currentLumiSection>0 && ls < currentLumiSection) {
857  edm::LogError("FedRawDataInputSource") << "Got old LS ("<<ls<<") file from EvFDAQDirector! Expected LS:" << currentLumiSection<<". Aborting execution."<<std::endl;
858  _exit(-1);
859  }
860 
861  int dbgcount=0;
862  if (status == evf::EvFDaqDirector::noFile) {
863  dbgcount++;
864  if (!(dbgcount%20)) LogDebug("FedRawDataInputSource") << "No file for me... sleep and try again...";
865  usleep(100000);
866  }
867  }
868  if ( status == evf::EvFDaqDirector::newFile ) {
869  LogDebug("FedRawDataInputSource") << "The director says to grab -: " << nextFile;
870 
871 
872  boost::filesystem::path rawFilePath(nextFile);
873  std::string rawFile = rawFilePath.replace_extension(".raw").string();
874 
875  struct stat st;
876  stat(rawFile.c_str(),&st);
877  fileSize=st.st_size;
878 
879  int eventsInNewFile = grabNextJsonFile(nextFile);
880  if (fms_) fms_->stoppedLookingForFile(ls);
881  assert( eventsInNewFile>=0 );
882  assert((eventsInNewFile>0) == (fileSize>0));//file without events must be empty
883 
884  if (!singleBufferMode_) {
885  //calculate number of needed chunks
886  unsigned int neededChunks = fileSize/eventChunkSize_;
887  if (fileSize%eventChunkSize_) neededChunks++;
888 
889  InputFile * newInputFile = new InputFile(evf::EvFDaqDirector::FileStatus::newFile,ls,rawFile,fileSize,neededChunks,eventsInNewFile,this);
890  fileQueue_.push(newInputFile);
891 
892  for (unsigned int i=0;i<neededChunks;i++) {
893 
894  //get thread
895  unsigned int newTid = 0xffffffff;
896  while (!workerPool_.try_pop(newTid)) {
897  usleep(100000);
898  }
899 
900  InputChunk * newChunk = nullptr;
901  while (!freeChunks_.try_pop(newChunk)) {
902  usleep(100000);
903  if (quit_threads_.load(std::memory_order_relaxed)) break;
904  }
905 
906  if (newChunk == nullptr) {
907  //return unused tid if we received shutdown (nullptr chunk)
908  if (newTid!=0xffffffff) workerPool_.push(newTid);
909  stop = true;
910  break;
911  }
912 
913  std::unique_lock<std::mutex> lk(mReader_);
914 
915  unsigned int toRead = eventChunkSize_;
916  if (i==neededChunks-1 && fileSize%eventChunkSize_) toRead = fileSize%eventChunkSize_;
917  newChunk->reset(i*eventChunkSize_,toRead,i);
918 
919  workerJob_[newTid].first=newInputFile;
920  workerJob_[newTid].second=newChunk;
921 
922  //wake up the worker thread
923  cvReader_[newTid]->notify_one();
924  }
925  }
926  else {
927  if (!eventsInNewFile) {
928  //still queue file for lumi update
929  std::unique_lock<std::mutex> lkw(mWakeup_);
930  InputFile * newInputFile = new InputFile(evf::EvFDaqDirector::FileStatus::newFile,ls,rawFile,0,0,0,this);
931  fileQueue_.push(newInputFile);
932  cvWakeup_.notify_one();
933  return;
934  }
935  //in single-buffer mode put single chunk in the file and let the main thread read the file
936  InputChunk * newChunk;
937  //should be available immediately
938  while(!freeChunks_.try_pop(newChunk)) usleep(100000);
939 
940  std::unique_lock<std::mutex> lkw(mWakeup_);
941 
942  unsigned int toRead = eventChunkSize_;
943  if (fileSize%eventChunkSize_) toRead = fileSize%eventChunkSize_;
944  newChunk->reset(0,toRead,0);
945  newChunk->readComplete_=true;
946 
947  //push file and wakeup main thread
948  InputFile * newInputFile = new InputFile(evf::EvFDaqDirector::FileStatus::newFile,ls,rawFile,fileSize,1,eventsInNewFile,this);
949  newInputFile->chunks_[0]=newChunk;
950  fileQueue_.push(newInputFile);
951  cvWakeup_.notify_one();
952  }
953  }
954  }
955  //make sure threads finish reading
956  unsigned numFinishedThreads = 0;
957  while (numFinishedThreads < workerThreads_.size()) {
958  unsigned int tid;
959  while (!workerPool_.try_pop(tid)) {usleep(10000);}
960  std::unique_lock<std::mutex> lk(mReader_);
961  thread_quit_signal[tid]=true;
962  cvReader_[tid]->notify_one();
963  numFinishedThreads++;
964  }
965  for (unsigned int i=0;i<workerThreads_.size();i++) {
966  workerThreads_[i]->join();
967  delete workerThreads_[i];
968  }
969 }
970 
971 void FedRawDataInputSource::readWorker(unsigned int tid)
972 {
973  bool init = true;
974  threadInit_.exchange(true,std::memory_order_acquire);
975 
976  while (1) {
977 
978  std::unique_lock<std::mutex> lk(mReader_);
979  workerJob_[tid].first=nullptr;
980  workerJob_[tid].first=nullptr;
981 
982  assert(!thread_quit_signal[tid]);//should never get it here
983  workerPool_.push(tid);
984 
985  if (init) {
986  std::unique_lock<std::mutex> lk(startupLock_);
987  init = false;
988  startupCv_.notify_one();
989  }
990  cvReader_[tid]->wait(lk);
991 
992  if (thread_quit_signal[tid]) return;
993 
994  InputFile * file;
995  InputChunk * chunk;
996 
997  assert(workerJob_[tid].first!=nullptr && workerJob_[tid].second!=nullptr);
998 
999  file = workerJob_[tid].first;
1000  chunk = workerJob_[tid].second;
1001 
1002  int fileDescriptor = open(file->fileName_.c_str(), O_RDONLY);
1003  off_t pos = lseek(fileDescriptor,chunk->offset_,SEEK_SET);
1004 
1005 
1006  if (fileDescriptor>=0)
1007  LogDebug("FedRawDataInputSource") << "Reader thread opened file -: TID: " << tid << " file: " << file->fileName_ << " at offset " << pos;
1008  else
1009  {
1010  edm::LogError("FedRawDataInputSource") <<
1011  "readWorker failed to open file -: " << file->fileName_ << " fd:" << fileDescriptor <<
1012  " or seek to offset " << chunk->offset_ << ", lseek returned:" << pos;
1013  setExceptionState_=true;
1014  return;
1015 
1016  }
1017 
1018  unsigned int bufferLeft = 0;
1020  for (unsigned int i=0;i<readBlocks_;i++)
1021  {
1022  const ssize_t last = ::read(fileDescriptor,( void*) (chunk->buf_+bufferLeft), eventChunkBlock_);
1023  if ( last > 0 )
1024  bufferLeft+=last;
1025  if (last < eventChunkBlock_) {
1026  assert(chunk->usedSize_==i*eventChunkBlock_+last);
1027  break;
1028  }
1029  }
1031  auto diff = end-start;
1032  std::chrono::milliseconds msec = std::chrono::duration_cast<std::chrono::milliseconds>(diff);
1033  LogDebug("FedRawDataInputSource") << " finished reading block -: " << (bufferLeft >> 20) << " MB" << " in " << msec.count() << " ms ("<< (bufferLeft >> 20)/double(msec.count())<<" GB/s)";
1034  close(fileDescriptor);
1035 
1036  if (detectedFRDversion_==0 && chunk->offset_==0) detectedFRDversion_=*((uint32*)chunk->buf_);
1037  assert(detectedFRDversion_<=3);
1038  chunk->readComplete_=true;//this is atomic to secure the sequential buffer fill before becoming available for processing)
1039  file->chunks_[chunk->fileIndex_]=chunk;//put the completed chunk in the file chunk vector at predetermined index
1040 
1041  }
1042 }
1043 
1045 {
1046  quit_threads_=true;
1047  throw cms::Exception("FedRawDataInputSource:threadError") << " file reader thread error ";
1048 
1049 }
1050 
1051 
1052 inline bool InputFile::advance(unsigned char* & dataPosition, const size_t size)
1053 {
1054  //wait for chunk
1055  while (!waitForChunk(currentChunk_)) {
1056  usleep(100000);
1058  }
1059 
1060  dataPosition = chunks_[currentChunk_]->buf_+ chunkPosition_;
1061  size_t currentLeft = chunks_[currentChunk_]->size_ - chunkPosition_;
1062 
1063  if (currentLeft < size) {
1064 
1065  //we need next chunk
1066  while (!waitForChunk(currentChunk_+1)) {
1067  usleep(100000);
1069  }
1070  //copy everything to beginning of the first chunk
1071  dataPosition-=chunkPosition_;
1072  assert(dataPosition==chunks_[currentChunk_]->buf_);
1073  memmove(chunks_[currentChunk_]->buf_, chunks_[currentChunk_]->buf_+chunkPosition_, currentLeft);
1074  memcpy(chunks_[currentChunk_]->buf_ + currentLeft, chunks_[currentChunk_+1]->buf_, size - currentLeft);
1075  //set pointers at the end of the old data position
1077  chunkPosition_=size-currentLeft;
1078  currentChunk_++;
1079  return true;
1080  }
1081  else {
1084  return false;
1085  }
1086 }
1087 
1088 inline void InputFile::moveToPreviousChunk(const size_t size, const size_t offset)
1089 {
1090  //this will fail in case of events that are too large
1091  assert(size < chunks_[currentChunk_]->size_ - chunkPosition_);
1092  assert(size - offset < chunks_[currentChunk_]->size_);
1093  memcpy(chunks_[currentChunk_-1]->buf_+offset,chunks_[currentChunk_]->buf_+chunkPosition_,size);
1096 }
1097 
1098 inline void InputFile::rewindChunk(const size_t size) {
1101 }
1102 
1103 //single-buffer mode file reading
1105 {
1106 
1107  if (fileDescriptor_<0) {
1108  fileDescriptor_ = open(file->fileName_.c_str(), O_RDONLY);
1109  bufferInputRead_ = 0;
1110  //off_t pos = lseek(fileDescriptor,0,SEEK_SET);
1111  if (fileDescriptor_>=0)
1112  LogDebug("FedRawDataInputSource") << "opened file -: " << std::endl << file->fileName_;
1113  else
1114  {
1115  throw cms::Exception("FedRawDataInputSource:readNextChunkIntoBuffer") << "failed to open file " << std::endl
1116  << file->fileName_ << " fd:" << fileDescriptor_;
1117  }
1118  }
1119 
1120  if (file->chunkPosition_ == 0) { //in the rare case the last byte barely fit
1121  uint32_t existingSize = 0;
1122  for (unsigned int i=0;i<readBlocks_;i++)
1123  {
1124  const ssize_t last = ::read(fileDescriptor_,( void*) (file->chunks_[0]->buf_ + existingSize), eventChunkBlock_);
1126  existingSize+=last;
1127  }
1128  }
1129  else {
1130  const uint32_t chunksize = file->chunkPosition_;
1131  const uint32_t blockcount=chunksize/eventChunkBlock_;
1132  const uint32_t leftsize = chunksize%eventChunkBlock_;
1133  uint32_t existingSize = eventChunkSize_ - file->chunkPosition_;
1134  memmove((void*) file->chunks_[0]->buf_, file->chunks_[0]->buf_ + file->chunkPosition_, existingSize);
1135 
1136  for (uint32_t i=0;i<blockcount;i++) {
1137  const ssize_t last = ::read(fileDescriptor_,( void*) (file->chunks_[0]->buf_ + existingSize), eventChunkBlock_);
1139  existingSize+=last;
1140  }
1141  if (leftsize) {
1142  const ssize_t last = ::read(fileDescriptor_,( void*)( file->chunks_[0]->buf_ + existingSize ), leftsize);
1144  existingSize+=last;
1145  }
1146  file->chunkPosition_=0;//data was moved to beginning of the chunk
1147  }
1148  if (bufferInputRead_ == file->fileSize_) { // no more data in this file
1149  if (fileDescriptor_!=-1)
1150  {
1151  LogDebug("FedRawDataInputSource") << "Closing input file -: " << std::endl << file->fileName_;
1152  close(fileDescriptor_);
1153  fileDescriptor_=-1;
1154  }
1155  }
1156 }
1157 
1158 // define this class as an input source
1160 
#define LogDebug(id)
static const char runNumber_[]
std::vector< std::string > & getData()
Definition: DataPoint.h:58
unsigned int lumi_
int i
Definition: DBlmapReader.cc:9
unsigned int getgpshigh(const unsigned char *)
uint32_t chunkPosition_
std::condition_variable cvWakeup_
tuple start
Check for commandline option errors.
Definition: dqm_diff.py:58
virtual void read(edm::EventPrincipal &eventPrincipal) override
bool gtpe_board_sense(const unsigned char *p)
struct fedh_struct fedh_t
static Timestamp invalidTimestamp()
Definition: Timestamp.h:101
virtual void rewind_() override
std::vector< int > * getStreamFileTracker()
unsigned int offset_
jsoncollector::DataPointDefinition * dpd_
tbb::concurrent_queue< unsigned int > workerPool_
unsigned int get(const unsigned char *, bool)
void maybeOpenNewLumiSection(const uint32_t lumiSection)
void rewindChunk(const size_t size)
std::vector< int > * streamFileTrackerPtr_
#define nullptr
int init
Definition: HydjetWrapper.h:62
evf::EvFDaqDirector::FileStatus status_
boost::shared_ptr< LuminosityBlockAuxiliary > luminosityBlockAuxiliary() const
Called by the framework to merge or insert lumi in principal cache.
Definition: InputSource.h:262
RunNumber_t run() const
Accessor for current run number.
Definition: InputSource.cc:595
std::atomic< bool > quit_threads_
volatile std::atomic< bool > shutdown_flag
std::vector< ReaderInfo > workerJob_
bool parse(const std::string &document, Value &root, bool collectComments=true)
Read a Value from a JSON document.
std::unique_ptr< std::thread > readSupervisorThread_
ProductProvenance const & dummyProvenance() const
Represents a JSON value.
Definition: value.h:111
std::string getEoLSFilePathOnBU(const unsigned int ls) const
std::vector< std::condition_variable * > cvReader_
FedRawDataInputSource * parent_
unsigned int sourceid
Definition: fed_header.h:32
std::string const & processGUID() const
Accessor for global process identifier.
Definition: InputSource.h:214
void reportEventsThisLumiInSource(unsigned int lumi, unsigned int events)
FileStatus updateFuLock(unsigned int &ls, std::string &nextFile, uint32_t &fsize)
FedRawDataInputSource(edm::ParameterSet const &, edm::InputSourceDescription const &)
U second(std::pair< T, U > const &p)
void reset(unsigned int newOffset, unsigned int toRead, unsigned int fileIndex)
static Timestamp beginOfTime()
Definition: Timestamp.h:103
std::vector< bool > thread_quit_signal
uint32_t bufferPosition_
tuple path
else: Piece not in the list, fine.
void updateFileIndex(int const &fileIndex)
#define DEFINE_FWK_INPUT_SOURCE(type)
void resize(size_t newsize)
Definition: FEDRawData.cc:32
const edm::RunNumber_t runNumber_
bool advance(unsigned char *&dataPosition, const size_t size)
void setLuminosityBlockAuxiliary(LuminosityBlockAuxiliary *lbp)
Definition: InputSource.h:354
void moveToPreviousChunk(const size_t size, const size_t offset)
unsigned char * buf_
void setDeleteTracking(std::mutex *fileDeleteLock, std::list< std::pair< int, InputFile * >> *filesToDelete)
struct fedt_struct fedt_t
#define FED_EVSZ_EXTRACT(a)
Definition: fed_trailer.h:36
int grabNextJsonFile(boost::filesystem::path const &)
def load
Definition: svgfig.py:546
BranchDescription const & branchDescription() const
edm::ProcessHistoryID processHistoryID_
#define end
Definition: vmac.h:37
virtual void preForkReleaseResources() override
bool waitForChunk(unsigned int chunkid)
const edm::DaqProvenanceHelper daqProvenanceHelper_
unsigned int fileIndex_
unsigned int offset(bool)
How EventSelector::AcceptEvent() decides whether to accept an event for output otherwise it is excluding the probing of A single or multiple positive and the trigger will pass if any such matching triggers are PASS or EXCEPTION[A criterion thatmatches no triggers at all is detected and causes a throw.] A single negative with an expectation of appropriate bit checking in the decision and the trigger will pass if any such matching triggers are FAIL or EXCEPTION A wildcarded negative criterion that matches more than one trigger in the trigger but the state exists so we define the behavior If all triggers are the negative crieriion will lead to accepting the event(this again matches the behavior of"!*"before the partial wildcard feature was incorporated).The per-event"cost"of each negative criterion with multiple relevant triggers is about the same as!*was in the past
bool first
Definition: L1TdeRCT.cc:75
virtual void deserialize(Json::Value &root)
Definition: DataPoint.cc:56
ProcessHistoryID daqInit(ProductRegistry &productRegistry, ProcessHistoryRegistry &processHistoryRegistry) const
std::vector< std::thread * > workerThreads_
bool evm_board_sense(const unsigned char *p, size_t size)
unsigned int uint32
Definition: MsgTools.h:13
void setEventCached()
Called by the framework to merge or ached() const {return eventCached_;}.
Definition: InputSource.h:381
const std::string fuOutputDir_
edm::Timestamp fillFEDRawDataCollection(std::auto_ptr< FEDRawDataCollection > &)
std::atomic< bool > readComplete_
virtual bool checkNextEvent() override
LuminosityBlockNumber_t luminosityBlock() const
Accessor for current luminosity block number.
Definition: InputSource.cc:601
std::list< std::pair< int, InputFile * > > filesToDelete_
unsigned int nProcessed_
unsigned long long uint64_t
Definition: Time.h:15
unsigned int currentChunk_
auto dp
Definition: deltaR.h:24
tbb::concurrent_queue< InputFile * > fileQueue_
ProductRegistry & productRegistryUpdate() const
Definition: InputSource.h:347
std::unique_ptr< FRDEventMsgView > event_
virtual void postForkReacquireResources(boost::shared_ptr< edm::multicore::MessageReceiverForSource >) override
std::string fileName_
void setProcessHistoryID(ProcessHistoryID const &phid)
std::condition_variable startupCv_
void stoppedLookingForFile(unsigned int lumi)
tbb::concurrent_vector< InputChunk * > chunks_
void resetLuminosityBlockAuxiliary(bool isNewLumi=true) const
Definition: InputSource.h:362
boost::shared_ptr< RunAuxiliary > runAuxiliary() const
Called by the framework to merge or insert run in principal cache.
Definition: InputSource.h:259
ProcessHistoryRegistry & processHistoryRegistryForUpdate()
Non-const accessor for process history registry.
Definition: InputSource.h:174
unsigned int eventsize
Definition: fed_trailer.h:33
std::atomic< bool > threadInit_
std::pair< InputFile *, InputChunk * > ReaderInfo
char data[epos_bytes_allocation]
Definition: EPOS_Wrapper.h:82
evf::EvFDaqDirector * daqDirector_
void setRunAuxiliary(RunAuxiliary *rp)
Definition: InputSource.h:350
void readWorker(unsigned int tid)
static std::atomic< unsigned int > counter
void makeEvent(EventPrincipal &eventPrincipal, EventAuxiliary const &eventAuxiliary)
const unsigned char * data() const
Return a const pointer to the beginning of the data buffer.
Definition: FEDRawData.cc:28
Unserialize a JSON document into a Value.
Definition: reader.h:16
void deleteFile(std::string const &)
evf::FastMonitoringService * fms_
friend class InputFile
Open Root file and provide MEs ############.
size_(0)
Definition: OwnArray.h:181
unsigned int gtpe_get(const unsigned char *)
std::vector< std::string > const & getNames()
std::string getEoLSFilePathOnFU(const unsigned int ls) const
std::string getJumpFilePath() const
volatile std::atomic< bool > shutdown_flag false
tbb::concurrent_queue< InputChunk * > freeChunks_
evf::EvFDaqDirector::FileStatus getNextEvent()
tuple status
Definition: ntuplemaker.py:245
evf::EvFDaqDirector::FileStatus nextEvent()
void readNextChunkIntoBuffer(InputFile *file)
unsigned int nEvents_
void setFMS(evf::FastMonitoringService *fms)
static std::string const source
Definition: EdmProvDump.cc:43
unsigned int getgpslow(const unsigned char *)
tuple size
Write out results.
#define FED_SOID_EXTRACT(a)
Definition: fed_header.h:53
std::string getEoRFilePathOnFU() const
void put(BranchDescription const &bd, WrapperOwningHolder const &edp, ProductProvenance const &productProvenance)
void renameToNextFree(std::string const &fileName) const