Jpp  15.0.0
the software that should make you happy
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
JDataWriter.cc
Go to the documentation of this file.
1 #include <string>
2 #include <iostream>
3 #include <sstream>
4 #include <iomanip>
5 #include <map>
6 
7 #include "Jeep/JParser.hh"
8 #include "Jeep/JProperties.hh"
9 #include "Jeep/JTimer.hh"
10 #include "Jeep/JTimekeeper.hh"
11 #include "Jeep/JPrint.hh"
12 #include "Jeep/JeepToolkit.hh"
13 #include "JNet/JControlHost.hh"
14 #include "JLang/JException.hh"
15 #include "JLang/JSharedPointer.hh"
18 #include "JDAQ/JDAQTags.hh"
19 #include "JDAQ/JDAQEventIO.hh"
20 #include "JDAQ/JDAQTimesliceIO.hh"
25 #include "JIO/JByteArrayIO.hh"
26 #include "JTools/JAutoMap.hh"
27 #include "JSupport/JMeta.hh"
28 #include "JSupport/JSupport.hh"
30 
31 
32 /**
33  * Type definition of auto map.
34  */
36 
37 
38 namespace JSUPPORT {
39 
40  /**
41  * Get key for given DAQ data type.
42  *
43  * \param type data type
44  * \return map element
45  */
46  template<>
47  template<class T>
49  {
50  return getTag<T>();
51  }
52 }
53 
54 
55 namespace KM3NETDAQ {
56 
57  /**
58  * Runcontrol client to write data to disk.
59  * In state running, this application will write ROOT formatted data from the data filters to disk.
60  */
61  class JDataWriter :
62  public JDAQClient
63  {
64  public:
65  /**
66  * Constructor.
67  *
68  * \param name name of client
69  * \param server name of command message server
70  * \param hostname name of data server
71  * \param logger pointer to logger
72  * \param level debug level
73  * \param path default path
74  */
75  JDataWriter(const std::string& name,
76  const std::string& server,
77  const std::string& hostname,
78  JLogger* logger,
79  const int level,
80  const std::string& path) :
81  JDAQClient(name, server, logger, level),
82  datawriter(),
83  path (path),
84  hostname (hostname)
85  {
87 
88  JControlHost::Throw(true);
89 
90  // map ControlHost tag to TTree writer.
91 
93  }
94 
95 
96  virtual void actionInit(int length, const char* buffer) override
97  {
98  using namespace std;
99  using namespace JPP;
100 
101  // start server
102 
103  try {
104 
105  datawriter.reset(new JControlHost(hostname));
106 
108 
109  for (JTreeWriter_t::iterator i = writer.begin(); i != writer.end(); ++i) {
110  buffer.add(JSubscriptionAll(i->first));
111  }
112 
114 
115  datawriter->Subscribe(buffer);
116  datawriter->SendMeAlways();
117 
118  JNoticeStream(logger) << "Established connection to " << hostname;
119  }
120  catch(const JControlHostException& exception) {
121  JErrorStream(logger) << exception;
122  }
123  }
124 
125 
126  virtual void actionConfigure(int length, const char* buffer) override
127  {
128  using namespace std;
129 
130  long long int update_s = 10;
131  long long int logger_s = 5;
132 
133  JProperties properties(JEquationParameters("=", ";", "", ""));
134 
135  properties["path"] = path;
136  properties["update_s"] = update_s;
137  properties["logger_s"] = logger_s;
138 
139  properties.read(string(buffer, length));
140 
141  if (update_s <= 0) { update_s = 1; }
142  if (logger_s <= 0) { logger_s = 1; }
143 
144  setClockInterval(update_s * 1000000LL);
145 
146  JDebugStream(logger) << "Path <" << path << ">";
147  JDebugStream(logger) << "Update period [s] " << update_s;
148 
153 
154  numberOfEvents = 0;
155  numberOfBytes = 0;
156  }
157 
158 
159  virtual void actionReset(int length, const char* buffer) override
160  {
161  datawriter.reset();
162  }
163 
164 
165  virtual void actionQuit(int length, const char* buffer) override
166  {}
167 
168 
169  virtual void actionStart(int length, const char* buffer) override
170  {
171  using namespace std;
172  using namespace JPP;
173 
174  JNoticeStream(logger) << string(buffer, length);
175 
176  ostringstream os;
177 
178  for (int i = 0; !writer.is_open() && i != MAXIMUM_FILE_NUMBER; ++i) {
179 
180  os.str("");
181 
182  os << getFullPath(path)
183  << "KM3NeT"
184  << "_" << FILL(8,'0') << getDetectorID()
185  << "_" << FILL(8,'0') << getRunNumber();
186 
187  if (i != 0) {
188  os << "_" << i;
189  }
190 
191  os << ".root";
192 
193  try {
194  writer.open(os.str().c_str());
195  }
196  catch(JException& exception) {
197  JErrorStream(logger) << exception;
198  }
199  }
200 
201  if (writer.is_open())
202  JNoticeStream(logger) << "Output file " << os.str();
203  else
204  JErrorStream (logger) << "File not opened " << os.str();
205 
206  numberOfEvents = 0;
207  numberOfBytes = 0;
208 
210 
211  timer.reset();
212 
213  logErrorRun .reset();
214  logErrorFile .reset();
215  logErrorTag .reset();
217 
219  }
220 
221 
222  virtual void actionStop(int length, const char* buffer) override
223  {
224  typeout();
225 
226  if (timer.usec_wall > 0) {
227  JNoticeStream(logger) << "I/O " << (int) (numberOfBytes / timer.usec_wall) << " MB/s";
228  }
229 
230  if (!run_db.is_written(getRunNumber())) {
231  JErrorStream(logger) << "No trigger parameters written for run " << getRunNumber();
232  }
233 
234  writer.close();
235 
236  // Release resources.
237 
239 
240  this->buffer.swap(null);
241  }
242 
243 
244  virtual void setSelect(JFileDescriptorMask& mask) const override
245  {
246  if (datawriter.is_valid()) {
247  mask.set(*datawriter);
248  }
249  }
250 
251 
252  virtual void actionSelect(const JFileDescriptorMask& mask) override
253  {
254  using namespace std;
255  using namespace JPP;
256 
257  if (datawriter.is_valid() && mask.has(*datawriter)) {
258 
259  try {
260 
261  JPrefix prefix;
262 
263  datawriter->WaitHead(prefix);
264 
265  timer.start();
266 
267  buffer.resize(prefix.getSize());
268 
269  datawriter->GetFullData(buffer.data(), buffer.size());
270 
271 
272  if (prefix.getTag() == IO_TRIGGER_PARAMETERS) {
273 
274  const string __str__(buffer.data(), buffer.size());
275 
276  istringstream in(__str__);
277 
278  if (!run_db.read(in)) {
279 
280  JErrorStream(logger) << "Fatal error reading trigger parameters " << __str__;
281 
282  ev_error();
283  }
284  }
285 
286 
287  if (isRunning()) {
288 
289  // Write trigger parameters for current run if not yet done
290 
292 
293  JTreeWriter_t::iterator i = writer.find(prefix.toString());
294 
295  if (i != writer.end()) {
296 
297  TFile* out = i->second->GetCurrentFile();
298 
299  if (out != NULL && out->IsOpen()) {
300 
301  JDAQPreamble preamble;
302  Version_t version;
303  JDAQHeader header;
304 
305  JByteArrayReader in(buffer.data(), buffer.size());
306 
307  in >> preamble >> version >> header;
308 
309  in.seekg(0); // rewind
310 
311  if (header.getRunNumber() == getRunNumber()) {
312 
313  const Int_t nb = i->second->copy(in);
314 
315  if (nb < (int) buffer.size() || in.tellg() != (int) buffer.size()) {
316  JWarningStream(logger) << "Inconsistency at copy of "
317  << prefix.toString() << ' '
318  << buffer.size() << ' '
319  << in.tellg() << ' '
320  << nb;
321  }
322 
323  if (prefix.getTag() == IO_EVENT)
324  numberOfEvents += 1;
325  numberOfBytes += buffer.size();
326 
327  if (prefix.getTag() == IO_EVENT && numberOfEvents == 1) {
328  typeout();
329  }
330 
331  } else {
332  JErrorStream(logErrorRun) << "Inconsistent run number "
333  << header.getRunNumber()
334  << " != "
335  << getRunNumber();
336  }
337  } else {
338  JErrorStream(logErrorFile) << "Output file not open";
339  }
340  } else {
341  if (prefix.getTag() != IO_TRIGGER_PARAMETERS) {
342  JErrorStream(logErrorTag) << "Unknown tag <" << prefix.toString() << ">, no data written";
343  }
344  }
345  } else {
346  JWarningStream(logErrorState) << "Not in running state <" << prefix.toString() << ">, no data written";
347  }
348 
349  timer.stop();
350  }
351  catch(const JControlHostException& exception) {
352  JErrorStream(logger) << exception;
353  }
354  }
355  }
356 
357 
358  virtual void actionRunning() override
359  {
360  typeout();
361  }
362 
363 
364  /**
365  * Report status of data writing.
366  */
367  void typeout()
368  {
369  std::ostringstream message;
370 
372 
373  logger.typeout(RC_LOG, message.str());
374  logger.status(message.str());
375  }
376 
377  JMeta meta; //!< meta data
378 
379  static const int MAXIMUM_FILE_NUMBER = 100; //!< maximum file number for overwrite protection.
380 
381  private:
382 
384  std::string path; // directory for output file
385 
386  JEEP::JTimer timer; // timer for I/O measurement
387  Long64_t numberOfEvents; // total number of events
388  long long int numberOfBytes; // total number of bytes
389 
394 
395  std::string hostname; //!< host name of data server
396  JTreeWriter_t writer; //!< TTree writer
397  std::vector<char> buffer; //!< internal buffer for incoming data
398 
399 
400  /**
401  * Auxiliary data structure for I/O of trigger parameters.
402  */
403  struct JValue_t {
404  /**
405  * Default constructor.
406  */
408  count(0),
409  is_written(false)
410  {}
411 
412  JTriggerParameters parameters; //!< trigger parameters
413  int count; //!< reader count
414  bool is_written; //!< writer status
415  };
416 
417 
418  /**
419  * Map run number to trigger parameters.
420  */
421  struct JRunDB :
422  public std::map<int, JValue_t>
423  {
424  /**
425  * Remove all entries before given run.
426  *
427  * \param run run number
428  */
429  inline void reset(const int run)
430  {
431  while (!this->empty() && this->begin()->first < run) {
432  this->erase(this->begin());
433  }
434  }
435 
436  /**
437  * Check if trigger parameters have been written for given run.
438  *
439  * \param run run number
440  * \return true if written; else false.
441  */
442  inline bool is_written(const int run) const
443  {
444  const_iterator p = this->find(run);
445 
446  return p != this->end() && p->second.is_written;
447  }
448 
449  /**
450  * Read trigger parameters.
451  *
452  * \param in input stream
453  * \return true if OK; else not
454  */
455  bool read(std::istream& in)
456  {
457  int run = -1;
459 
460  in >> run >> parameters;
461 
462  in.clear(std::ios::eofbit);
463 
464  if (in && run != -1) {
465 
466  JValue_t& value = (*this)[run];
467 
468  if (value.count == 0) {
469  value.parameters = parameters;
470  }
471 
472  value.count += 1;
473 
474  return parameters.equals(value.parameters);
475  }
476 
477  return false;
478  }
479 
480  /**
481  * Write trigger parameters for given run if not yet done.
482  *
483  * \param run run number
484  * \param file pointer to ROOT file
485  */
486  inline void write(const int run, TFile* file)
487  {
488  if (file != NULL) {
489 
490  iterator p = this->find(run);
491 
492  if (p != this->end() && p->second.count != 0 && !p->second.is_written) {
493 
494  file->WriteTObject(&p->second.parameters);
495 
496  p->second.is_written = true;
497  }
498  }
499  }
500  };
501 
503  };
504 }
505 
506 
507 /**
508  * \file
509  *
510  * Application for writing real-time data to disk.
511  * \author mdejong
512  */
513 int main(int argc, char* argv[])
514 {
515  using namespace std;
516  using namespace JPP;
517  using namespace KM3NETDAQ;
518 
519  string server;
520  string logger;
521  string hostname;
522  string client_name;
523  bool use_cout;
524  string path;
525  int debug;
526 
527  try {
528 
529  JParser<> zap("Application for writing real-time data to disk.");
530 
531  zap['H'] = make_field(server) = "localhost";
532  zap['M'] = make_field(logger) = "localhost";
533  zap['D'] = make_field(hostname) = "localhost";
534  zap['u'] = make_field(client_name) = "%";
535  zap['c'] = make_field(use_cout);
536  zap['p'] = make_field(path) = "";
537  zap['d'] = make_field(debug) = 3;
538 
539  zap(argc, argv);
540  }
541  catch(const exception &error) {
542  FATAL(error.what() << endl);
543  }
544 
545 
546  JLogger* out = NULL;
547 
548  if (use_cout)
549  out = new JStreamLogger(cout);
550  else
551  out = new JControlHostLogger(logger);
552 
553  JDataWriter dwriter(getProcessName(client_name, argv[0]), server, hostname, out, debug, path);
554 
555  dwriter.meta = JMeta(argc, argv);
556 
557  dwriter.enter();
558  dwriter.run();
559 }
JDataWriter(const std::string &name, const std::string &server, const std::string &hostname, JLogger *logger, const int level, const std::string &path)
Constructor.
Definition: JDataWriter.cc:75
ControlHost prefix.
Definition: JPrefix.hh:31
Message logger with time scheduler.
Auxiliary class for ROOT I/O of application specific meta data.
Definition: JMeta.hh:70
Utility class to parse command line options.
Definition: JParser.hh:1500
virtual void actionStop(int length, const char *buffer) override
Definition: JDataWriter.cc:222
General exception.
Definition: JException.hh:23
Runcontrol client to write data to disk.
Definition: JDataWriter.cc:61
bool read(const JEquation &equation)
Read equation.
Definition: JProperties.hh:677
Exceptions.
std::vector< char > buffer
internal buffer for incoming data
Definition: JDataWriter.cc:397
void status(const JMessage_t &message)
int main(int argc, char *argv[])
Definition: Main.cc:15
static const int MAXIMUM_FILE_NUMBER
maximum file number for overwrite protection.
Definition: JDataWriter.cc:379
ROOT TTree parameter settings of various packages.
virtual void actionQuit(int length, const char *buffer) override
Definition: JDataWriter.cc:165
JDAQStateMachine::ev_configure_event ev_configure
JDAQStateMachine::ev_error_event ev_error
ControlHost class.
std::string getProcessName(const std::string &name, const std::string &process)
Get process name of run control client.
Message logging based on std::ostream.
bool has(const int file_descriptor) const
Has file descriptor.
void set(const int file_descriptor)
Set file descriptor.
void reset(const int run)
Remove all entries before given run.
Definition: JDataWriter.cc:429
JMessageScheduler logErrorState
Definition: JDataWriter.cc:393
Interface for logging messages.
Definition: JLogger.hh:22
Message logging based on ControlHost.
Utility class to parse parameter values.
Definition: JProperties.hh:496
void setClockInterval(const long long int interval_us)
Set interval time.
Definition: JDAQClient.hh:164
Auxiliary data structure for I/O of trigger parameters.
Definition: JDataWriter.cc:403
std::string hostname
host name of data server
Definition: JDataWriter.cc:395
*fatal Wrong number of arguments esac JCookie sh typeset Z DETECTOR typeset Z SOURCE_RUN typeset Z TARGET_RUN set_variable PARAMETERS_FILE $WORKDIR parameters
Definition: diff-Tuna.sh:38
Simple data structure to support I/O of equations (see class JLANG::JEquation).
Time keeper.
Definition: JTimekeeper.hh:34
static const JNET::JTag IO_TRIGGER_PARAMETERS
Definition: JDAQTags.hh:68
JTreeWriter_t writer
TTree writer.
Definition: JDataWriter.cc:396
std::string name
Definition: JDAQCHSM.chsm:154
void replaceEvent(const JTag &oldTag, const JTag &newTag, JDAQEvent_t &event)
Replace tag of given event in event table.
Definition: JDAQClient.hh:492
JSharedPointer< JControlHost > server
message server
Definition: JDAQClient.hh:800
Auxiliary class for a type holder.
Definition: JType.hh:19
void run()
Run as run control client following command messages via JNET::JControlHost.
Definition: JDAQClient.hh:661
std::string getFullPath(const std::string &path)
Get full path, i.e. add JEEP::PATHNAME_SEPARATOR if necessary.
Definition: JeepToolkit.hh:128
bool is_written(const int run) const
Check if trigger parameters have been written for given run.
Definition: JDataWriter.cc:442
virtual void setSelect(JFileDescriptorMask &mask) const override
Set the file descriptor mask for the select call.
Definition: JDataWriter.cc:244
int getSize() const
Get size.
Definition: JPrefix.hh:62
Subscription list.
void stop()
Stop timer.
Definition: JTimer.hh:113
virtual void actionSelect(const JFileDescriptorMask &mask) override
Action method following last select call.
Definition: JDataWriter.cc:252
Utility class to parse parameter values.
virtual bool is_open() const override
Check is file is open.
Definition: JRootFile.hh:76
then echo The file $DIR KM3NeT_00000001_00000000 root already please rename or remove it first
virtual void actionConfigure(int length, const char *buffer) override
Definition: JDataWriter.cc:126
long long int numberOfBytes
Definition: JDataWriter.cc:388
virtual void actionRunning() override
This method is repeatedly called when this client machine is in state Running and the clock interval ...
Definition: JDataWriter.cc:358
void reset()
Reset timer.
Definition: JTimer.hh:76
Map run number to trigger parameters.
Definition: JDataWriter.cc:421
JMessageScheduler logErrorRun
Definition: JDataWriter.cc:390
Type list.
Definition: JTypeList.hh:22
int getDetectorID() const
Get detector identifier.
Definition: JDAQCHSM.chsm:89
static JKey_t getKey(JType< T > type)
Get key.
TFile * getFile() const
Get file.
Definition: JRootFile.hh:65
Scheduling of actions via fixed latency intervals.
virtual void actionInit(int length, const char *buffer) override
Definition: JDataWriter.cc:96
I/O formatting auxiliaries.
The template JSharedPointer class can be used to share a pointer to an object.
static const JNET::JTag RC_LOG
Definition: JDAQTags.hh:50
JMessageScheduler logErrorFile
Definition: JDataWriter.cc:391
JSUPPORT::JAutoTreeWriter< JNET::JTag > JTreeWriter_t
Type definition of auto map.
Definition: JDataWriter.cc:35
#define make_field(A,...)
macro to convert parameter to JParserTemplateElement object
Definition: JParser.hh:1961
Byte array binary input.
Definition: JByteArrayIO.hh:25
JValue_t()
Default constructor.
Definition: JDataWriter.cc:407
Auxiliary methods for handling file names, type names and environment.
Auxiliary class for method select.
Auxiliary class for CPU timing and usage.
Definition: JTimer.hh:32
ROOT I/O of application specific meta data.
JMessageScheduler logErrorTag
Definition: JDataWriter.cc:392
virtual void typeout(const std::string &tag, const std::string &message) override
Report message.
JSubscriptionList & add(const JSubscription &subscription)
Add subscription.
Level specific message streamers.
Exception for ControlHost.
Definition: JException.hh:450
int debug
debug level
Definition: JSirene.cc:63
JTriggerParameters parameters
trigger parameters
Definition: JDataWriter.cc:412
bool putObject(TDirectory &dir, const TObject &object)
Write object to ROOT directory.
char getTokenDelimeter()
Get the token delimeter for command messages.
bool isRunning() const
Check if this client is in runnig state.
Definition: JDAQClient.hh:479
virtual void close() override
Close file.
Auxiliary class for all subscription.
Definition: JControlHost.hh:97
virtual void open(const char *file_name) override
Open file.
const JTag & getTag() const
Get tag.
Definition: JTag.hh:86
Auxiliary data structure for sequence of same character.
Definition: JManip.hh:328
JMeta meta
meta data
Definition: JDataWriter.cc:377
static const JNET::JTag RC_DWRITER
Definition: JDAQTags.hh:49
#define FATAL(A)
Definition: JMessage.hh:67
virtual void actionStart(int length, const char *buffer) override
Definition: JDataWriter.cc:169
void write(const int run, TFile *file)
Write trigger parameters for given run if not yet done.
Definition: JDataWriter.cc:486
std::string toString() const
Convert tag to string.
Definition: JTag.hh:171
int getRunNumber() const
Get run number.
Definition: JDAQCHSM.chsm:100
void insert()
Insert (list of) data type(s).
void typeout()
Report status of data writing.
Definition: JDataWriter.cc:367
std::vector< int > count
Definition: JAlgorithm.hh:180
const std::string & getFullName() const
Get full name of this run control client.
Definition: JDAQClient.hh:119
Control unit client base class.
Definition: JDAQClient.hh:272
Utility class to parse command line options.
virtual bool enter(const JArgs &args)
Enter the state machine.
Definition: JDAQClient.hh:363
JMessageLogger logger
message logger
Definition: JDAQClient.hh:801
Fixed parameters andd ControlHost tags for KM3NeT DAQ.
static const JNET::JTag RC_CMD
Definition: JDAQTags.hh:44
static const JNET::JTag IO_EVENT
Definition: JDAQTags.hh:66
virtual void actionReset(int length, const char *buffer) override
Definition: JDataWriter.cc:159
KM3NeT DAQ constants, bit handling, etc.
then fatal Wrong number of arguments fi set_variable DETECTOR $argv[1] set_variable INPUT_FILE $argv[2] eval JPrintDetector a $DETECTOR O IDENTIFIER eval JPrintDetector a $DETECTOR O SUMMARY source JAcoustics sh $DETECTOR_ID CHECK_EXIT_CODE typeset A TRIPODS get_tripods $WORKDIR tripod txt TRIPODS for EMITTER in
Definition: JCanberra.sh:41
JLANG::JSharedPointer< JControlHost > datawriter
Definition: JDataWriter.cc:383
version
Definition: JCalibratePMT.sh:7
static void Throw(const bool option)
Enable/disable throw option.
Definition: JThrow.hh:37
esac $JPP_BIN JLogger sh $LOGGER until pgrep JGetMessage</dev/null > dev null
unsigned long long usec_wall
Definition: JTimer.hh:224
void start()
Start timer.
Definition: JTimer.hh:89
bool read(std::istream &in)
Read trigger parameters.
Definition: JDataWriter.cc:455
then usage $script< string identifier >< detectorfile > event file(toashort file)+" "\nNote that the event files and toashort files should be one-to-one related." fi if (( $