Jpp 21.0.0
the software that should make you happy
Loading...
Searching...
No Matches
JDataFilter.cc
Go to the documentation of this file.
1#include <string>
2#include <iostream>
3#include <iomanip>
4#include <deque>
5#include <limits>
6#include <algorithm>
7#include <unistd.h>
8#include <random>
9#include <filesystem>
10
16
18#include "JLang/JLangToolkit.hh"
19#include "JLang/JException.hh"
20#include "JLang/JVectorize.hh"
21#include "JLang/JStatus.hh"
22#include "Jeep/JParser.hh"
23#include "Jeep/JProperties.hh"
24#include "Jeep/JTimer.hh"
25#include "Jeep/JTimekeeper.hh"
26#include "Jeep/JMessage.hh"
27#include "Jeep/JPrint.hh"
28#include "Jeep/JeepToolkit.hh"
30#include "JDAQ/JDAQTags.hh"
31#include "JDAQ/JDAQEventIO.hh"
35#include "JTrigger/JHit.hh"
40#include "JTrigger/JHitL0.hh"
41#include "JTrigger/JHitL1.hh"
42#include "JTrigger/JBuildL1.hh"
43#include "JTrigger/JBuildL2.hh"
55#include "JTrigger/JChecksum.hh"
58#include "JNet/JControlHost.hh"
60#include "JNet/JTCPSocket.hh"
62#include "JNet/JServerSocket.hh"
64#include "JTools/JStats.hh"
65#include "JSupport/JSupport.hh"
67#include "JSupport/JMeta.hh"
68#include "JSystem/JTime.hh"
70#include "JSystem/JNetwork.hh"
72
73
74namespace JNET {
75
76 /**
77 * Get size of packeet.
78 *
79 * \param preamble DAQ data preamble
80 * \return size [B]
81 */
82 template<>
84 {
85 return preamble.getLength();
86 }
87}
88
89namespace KM3NETDAQ {
90
91 using namespace JPP;
92
93
94 /**
95 * Get expected number of frames according a given allowed fraction of active modules.
96 *
97 * \param number_of_frames number of frames
98 * \param factor factor
99 * \return number of frames
100 */
101 inline size_t getNumberOfFrames(const size_t number_of_frames, const double factor)
102 {
103 if (factor <= 0.0) {
104 return 1;
105 }
106
107 if (factor >= 1.0) {
108 return number_of_frames;
109 }
110
111 const size_t n = (size_t) (number_of_frames * factor);
112
113 return (n == 0 ? 1 : n);
114 }
115
116
117 /**
118 * Main class for real-time filtering of data.
119 *
120 * This class implements the action methods for each transition of the state machine.\n
121 * When the state machine is entered, data are continually collected using
122 * custom implementation of virtual methods
123 * JDataFilter::setSelect and
124 * JDataFilter::actionSelect.
125 *
126 * In state <tt>Running</tt>, all incoming data from the DataQueue.cc are buffered, referred to as "queue".\n
127 * These data are formatted as a JDAQSuperFrame and aggregated into a JDAQTimeslice.\n
128 * When a JDAQTimeslice is complete,
129 * it processed in the same way as applications JTriggerProcessor.cc and JTriggerEfficiency.cc.
130 *
131 * The completeness of a time slice is defined by two parameters, namely
132 * <tt>frames_per_slice</tt> and
133 * <tt>factor_per_slice</tt>.\n
134 * These are parsed in method actionConfigure as follows.
135 * <pre>
136 * numberOfFramesPerSlice = <frames per slice> = 1;
137 * factorOfFramesPerSlice = <factor per slice> = 1.0;
138 * </pre>
139 * The expected number of frames in a time slices is defined by their product.\n
140 * Note that the first parameter can change during operation (see below).
141 *
142 * A timeout may occur when the total amount of data or the number of incomplete time slices
143 * in the queue exceeds one of the limits <tt>queueSize</tt> or <tt>queueDepth</tt>.\n
144 * These are parsed in method actionConfigure as follows.
145 * <pre>
146 * queueSize = <maximal queue size [B]>;
147 * queueDepth = <maximal queue depth>;
148 * </pre>
149 * Note that these values apply per JDataFilter.\n
150 *
151 * The parameter <tt>frames_per_slice</tt> is subject to a servo mechanism.\n
152 * When a timeout occurs,
153 * it is set to the number of frames in the oldest time slice.\n
154 * When data are received with a frame index below the current frame index,
155 * it is incremented by one.
156 *
157 * In addition, a circular buffer based on a ROOT TTree for each JDAQTimeslice type can be maintained.\n
158 * The following parameters can be used to configure the circular buffer.\n
159 * <pre>
160 * path = <write directory for temporary circular buffer>;
161 * archive = <write directory for archival of circular buffer>;
162 * c_sizeL0 = <L0 buffer size>;
163 * c_sizeL1 = <L1 buffer size>;
164 * c_sizeL2 = <L2 buffer size>;
165 * c_sizeSN = <SN buffer size>;
166 * </pre>
167 *
168 * Note that when one (or more) of the buffer sizes is non-zero and the path corresponds to a valid directory:
169 * - There will always be a file created which is deleted when the state machine is exited;
170 * - The temporary file name is <tt><path>/KM3NeT_<tag>.root</tt>;
171 * - Following an alert, the temporary file is archived to a file with name <tt><path>/KM3NeT_YYYY-MM-DD_<tag>[_<index>].root</tt>;
172 * - After archival of the temporary file, a new temporary file will be opened;
173 * - L0, L1, L2 and SN buffer sizes are per JDataFilter;
174 * - The tag KM3NETDAQ::RC_ALERT defined in JDAQTags.hh has tentatively been reserved to trigger the archival of the temporary file following an external alert;
175 *
176 * In this, <tt>YYYY</tt>, <tt>MM</tt> and <tt>DD</tt> correspond to the year, month and day at the time of the alert, respectively.\n
177 * The <tt><tag></tt> corresponds to the unique JNET::JTag of the JDataFilter process.\n
178 * The <tt><index></tt> is optional and will only be used to prevent overwriting of an existing file
179 * (e.g. when there is more than one alert on a given day).
180 *
181 * Data can be discarded for various reasons.\n
182 * The list of criteria includes validity ranges of the PMT number and TDC values as well as the sorted times per PMT.\n
183 * The discarded data can be written to disk according to the parameters:
184 * <pre>
185 * dumpLimit = <maximum number of time slices to be dumped>
186 * dumpMask = <mask for data to be dumped>
187 * </pre>
188 * The first limits the number of time slices with discarded data that will be dumped and \n
189 * the latter corresponds to bits according to the enumeration JChecksum::error_types.\n
190 * The discarded data will be stored as JDAQTimeslice.
191 *
192 * Note that the application JConvert.cc can be used to readily convert multiple input files to a single output file.
193 *
194 * The script <tt>$JPP_DIR/tests/JDataFilter/JDataFilter.sh</tt> can be used to test this application.
195 */
197 public JDAQClient
198 {
199 public:
200
203
204 typedef double hit_type;
207 typedef JTimeslice <hit_type> JTimeslice_t;
208 typedef JBuildL1 <hit_type> JBuildL1_t;
209 typedef JBuildL2 <hit_type> JBuildL2_t;
210
211
212
213 /**
214 * Circular buffer.
215 */
217 public JTreeRecorder<JDAQTimesliceTypes_t>
218 {
221
222
223 static const int MAXIMUM_FILE_NUMBER = 100; //!< maximum file number for overwrite protection.
224
225
226 /**
227 * Constructor.
228 *
229 * \param path directory for temporary storage
230 * \param archive directory for permanent archival
231 * \param tag tag
232 */
233 JCircularBuffer_t(const std::string& path,
234 const std::string& archive,
235 const JTag& tag) :
236 path (path),
238 tag (tag)
239 {
240 disable();
241 }
242
243
244 /**
245 * Open file.
246 *
247 * If file with same name exists, remove it beforehand.
248 */
249 void open()
250 {
251 using namespace std;
252 using namespace JPP;
253
254 gErrorIgnoreLevel = kFatal;
255
256 std::ostringstream os;
257
258 os << getFullPath(path) << "KM3NeT" << "_" << tag << ".root";
259
260 error_code error;
261
262 if (filesystem::is_regular_file(os.str(), error)) {
263 filesystem::remove(os.str());
264 }
265
266 this->open(os.str().c_str());
267 }
268
269
270 /**
271 * Close file.
272 *
273 * If option is true, archive file; else delete file.
274 *
275 * \param option option
276 */
277 void close(const bool option)
278 {
279 using namespace std;
280 using namespace JPP;
281
282 const JDateAndTime cal;
283
284 if (this->is_open()) {
285
286 const string file_name = this->getFile()->GetName();
287
288 this->close();
289
290 if (option) {
291
292 for (int i = 0; i != MAXIMUM_FILE_NUMBER; ++i) {
293
294 ostringstream os;
295
296 os << getFullPath(this->archive)
297 << "KM3NeT"
298 << "_" << cal.getYear() << '-' << FILL(2,'0') << cal.getMonth() << '-' << FILL(2,'0') << cal.getDay()
299 << "_" << this->tag;
300
301 if (i != 0) {
302 os << "_" << i;
303 }
304
305 os << ".root";
306
307 error_code error;
308
309 if (!filesystem::is_regular_file(os.str(), error)) {
310
311 filesystem::rename(file_name, os.str());
312
313 return;
314 }
315 }
316
317 } else {
318
319 filesystem::remove(file_name);
320 }
321 }
322 }
323
324
325 /**
326 * Disable writing.
327 */
328 void disable()
329 {
330 sizeL0 = 0;
331 sizeL1 = 0;
332 sizeL2 = 0;
333 sizeSN = 0;
334 }
335
336
337 /**
338 * Check whether writing of data is enabled.
339 *
340 * \return true if writing enabled; else false
341 */
342 bool is_enabled() const
343 {
344 return (sizeL0 > 0 ||
345 sizeL1 > 0 ||
346 sizeL2 > 0 ||
347 sizeSN > 0);
348 }
349
350
351 /**
352 * Write circular buffer to output stream.
353 *
354 * \param out output stream
355 * \param object circular buffer
356 * \return output stream
357 */
358 friend inline std::ostream& operator<<(std::ostream& out, const JCircularBuffer_t& object)
359 {
360 if (object.is_open())
361 out << object.getFile()->GetName();
362 else
363 out << "void";
364
365 out << ' ';
366
367 out << object.sizeL0 << '/'
368 << object.sizeL1 << '/'
369 << object.sizeL2 << '/'
370 << object.sizeSN << '/';
371
372 return out;
373 }
374
375 Long64_t sizeL0; //!< Number of L0 time slices
376 Long64_t sizeL1; //!< Number of L1 time slices
377 Long64_t sizeL2; //!< Number of L2 time slices
378 Long64_t sizeSN; //!< Number of SN time slices
379
380 std::string path; //!< Directory for temporary storage
381 std::string archive; //!< Directory for permanent archival
382 JTag tag; //!< Unique tag of this process
383 };
384
385
386 /**
387 * Sort DAQ process by index.
388 *
389 * \param first first DAQ process
390 * \param second second DAQ process
391 * \return true if index of first DAQ process less than that of second; else false
392 */
393 static inline bool compare(const JDAQProcess& first, const JDAQProcess& second)
394 {
395 return first.index < second.index;
396 }
397
398
399 /**
400 * Constructor.
401 *
402 * \param name name of client
403 * \param server name of command message server
404 * \param hostname name of data server
405 * \param logger pointer to logger
406 * \param level debug level
407 * \param port server port
408 * \param backlog server backlog
409 * \param path directory for temporary storage
410 * \param archive directory for parmanent archival
411 */
412 JDataFilter(const std::string& name,
413 const std::string& server,
414 const std::string& hostname,
416 const int level,
417 const int port,
418 const int backlog,
419 const std::string& path,
420 const std::string& archive) :
423 port (port),
425 c_buffer (path, archive, getUniqueTag())
426 {
427 replaceEvent(RC_CMD, RC_DFILTER, ev_configure); /// replace tag to receive dfilter specific messages in configure
428
430
431 totalCPURAM = getRAM();
433 dataqueue_slice_index.clear();
434 reporting = false;
435
436 this->server->setReceiveBufferSize(DFILTER_RECEIVE_BUFFER_SIZE);
437 }
438
439
440 virtual void actionEnter() override
441 {}
442
443
444 virtual void actionExit() override
445 {
446 if (c_buffer.is_open()) {
447
448 JStatusStream(logger) << "Close and remove circular buffer " << c_buffer;
449
450 c_buffer.close(false);
451 }
452
453 datawriter.reset();
454 }
455
456
457 virtual void actionInit(int length, const char* buffer) override
458 {
459 JDebugStream(logger) << "actionInit() " << std::string(buffer,length);
460
461 try {
462
463 JDebugStream(logger) << "Start server.";
464
465 if (serversocket.is_valid()) {
466 serversocket->shutdown();
467 }
468
470 }
471 catch(const std::exception& error) {
472 JErrorStream(logger) << "Error \"" << error.what() << "\"; trigger ev_error.";
473 ev_error();
474 }
475 }
476
477
478 virtual void actionConfigure(int length, const char* buffer) override
479 {
480 using namespace std;
481
482 JDebugStream(logger) << "actionConfigure() " << endl << std::string(buffer,length);
483
484 string _hostname_ = "";
485
486 long long int update_s = 20;
487 long long int logger_s = 10;
488
489 parameters .reset();
490 dataFilters.clear();
491 dataQueues .clear();
492
493 reporting = false;
494 dumpCount = 0;
495 dumpLimit = numeric_limits<int>::max();
496 dumpMask = 0;
500 //dumpMask.set(JChecksum::EUDP_t);
502
503 detector.comment.clear();
504 detector.clear();
505
506 JProperties properties(JEquationParameters("=", ";", "", ""), 0);
507
508 properties["dataWriter"] = _hostname_;
509 properties["numberOfFramesPerSlice"] = frames_per_slice = 1;
510 properties["factorOfFramesPerSlice"] = factor_per_slice = 1.0;
511 properties["detector"] = detector;
512 properties["triggerParameters"] = parameters;
513 properties["queueSize"] = maxQueueSize = (totalCPURAM - GIGABYTE); // leave 1 GB left ...
514 properties["queueDepth"] = maxQueueDepth = 20; // to be optimized
515 properties["frameIndex"] = maximal_frame_index = 100000;
516 properties["logger_s"] = logger_s;
517 properties["update_s"] = update_s;
518 properties["JDataFilter"] = dataFilters;
519 properties["DataQueue"] = dataQueues;
520 properties["path"] = c_buffer.path;
521 properties["archive"] = c_buffer.archive;
522 properties["c_sizeL0"] = c_buffer.sizeL0;
523 properties["c_sizeL1"] = c_buffer.sizeL1;
524 properties["c_sizeL2"] = c_buffer.sizeL2;
525 properties["c_sizeSN"] = c_buffer.sizeSN;
526 properties["dumpLimit"] = dumpLimit;
527 properties["dumpMask"] = dumpMask;
528
529 try {
530 properties.read(string(buffer, length));
531 }
532 catch(const std::exception& error) {
533 JErrorStream(logger) << error.what();
534 }
535
536 if (update_s <= 0) { update_s = 20; }
537 if (logger_s <= 0) { logger_s = 10; }
538
539 setClockInterval(update_s * 1000000LL);
540
541 _hostname_ = trim(_hostname_);
542
543 if (_hostname_ != "" && _hostname_ != hostname) {
544
545 datawriter.reset();
546
547 hostname = _hostname_;
548 }
549
550 bool status = datawriter.is_valid();
551
552 if (status) {
553
554 try {
555 status = datawriter->Connected() == 0;
556 }
557 catch (const exception&) {
558 status = false;
559 }
560 }
561
562 if (!status) {
563
565
566 datawriter->MyId(getFullName());
567 }
568
569 datawriter->setSendBufferSize(DFILTER_SEND_BUFFER_SIZE);
570
571 // process processlist
572
573 if (dataFilters.empty()) {
574 JNoticeStream(logger) << "No DataFilters in process list, or no process list. "
575 << "Assuming that this process is the only process on this CPU and setting parameters accordingly.";
576 }
577
578 sort(dataFilters.begin(), dataFilters.end(), compare);
579
580 unsigned int numberOfDataFiltersOnThisMachine = 0;
581 vector<JDAQProcess>::iterator thisProcess = dataFilters.end();
582
584
585 for (vector<JDAQProcess>::iterator i = dataFilters.begin(); i != dataFilters.end(); ++i) {
586
587 if (find(IP.begin(), IP.end(), i->hostname) != IP.end()) {
588
589 numberOfDataFiltersOnThisMachine++;
590
591 if (i->port == this->port) {
592 thisProcess = i;
593 }
594 }
595 }
596
597 if (numberOfDataFiltersOnThisMachine == 0) {
598 JNoticeStream(logger) << "Zero data filters on this machine according to process list (if it exists). "
599 << "Assuming one datafilter on this machine.";
600 numberOfDataFiltersOnThisMachine = 1;
601 }
602
603 if (thisProcess == dataFilters.end()) {
604
605 JErrorStream error(logger);
606
607 error << "This process cannot be found in the process list. Why do I exist?";
608 error << " my IP addresses:";
609
610 for (vector<string>::const_iterator i = IP.begin(); i != IP.end(); ++i) {
611 error << ' ' << *i;
612 }
613
614 error << " my port: " << this->port;
615 error << " process list";
616
617 for (vector<JDAQProcess>::iterator i = dataFilters.begin(); i != dataFilters.end(); ++i) {
618 error << ' ' << i->hostname << ':' << i->port;
619 }
620 }
621
622 if (thisProcess != dataFilters.end() && thisProcess->index != getName()) {
623 JErrorStream(logger) << "Mismatch between given process names: "
624 << "I am called " << getName()
625 << ", but in the process list I am referred to as " << thisProcess->index;
626 }
627
628 if (dataFilters.begin() == thisProcess || dataFilters.empty()) { // set reporting
629 reporting = true;
630 }
631
632 if (maxQueueSize > (totalCPURAM-GIGABYTE)/(numberOfDataFiltersOnThisMachine)) { // check maximum size of queue
633
634 maxQueueSize = (totalCPURAM-GIGABYTE)/(numberOfDataFiltersOnThisMachine);
635
636 JNoticeStream(logger) << "Maximum queue size is too large given the number of processes on this machine. "
637 << "Queue size reduced to "
638 << maxQueueSize << " bytes." ;
639 }
640
641 // detector
642
643 if (parameters.disableHighRateVeto) {
644
645 JNoticeStream(logger) << "Disabling high-rate veto of all PMTs.";
646
647 detector.setPMTStatus(HIGH_RATE_VETO_DISABLE);
648 }
649
650 // trigger parameters
651
653
654 triggerNB .reset(new JTriggerNB (parameters));
658
660
661 if (reporting) {
662 JNoticeStream(logger) << "This data filter process will report.";
663 JNoticeStream(logger) << "Detector version/size " << detector.getVersion() << '/' << detector.size();
664 JDebugStream (logger) << "Trigger parameters: " << parameters;
665 JDebugStream (logger) << "Detector description: " << endl << detector;
666 JNoticeStream(logger) << "Update period [s]: " << getClockInterval();
667 }
668
669 timesliceRouter.reset(new JTimesliceRouter(parameters.numberOfBins));
670
671 // set L1, L2 and SN builders
672
673 buildL1.reset(new JBuildL1_t(parameters));
674 buildL2.reset(new JBuildL2_t(parameters.L2));
675 buildSN.reset(new JBuildL2_t(parameters.SN));
676 buildNB.reset(new JBuildL2_t(parameters.NB));
677
678 if (buildL1.get() == NULL) { JErrorStream(logger) << "Failed to allocate buildL1."; }
679 if (buildL2.get() == NULL) { JErrorStream(logger) << "Failed to allocate buildL2."; }
680 if (buildSN.get() == NULL) { JErrorStream(logger) << "Failed to allocate buildSN."; }
681 if (buildNB.get() == NULL) { JErrorStream(logger) << "Failed to allocate buildSN."; }
682
683 logErrorRun = JMessageScheduler(logger, JTimekeeper(logger_s * 1000000LL));
684 logErrorDetector = JMessageScheduler(logger, JTimekeeper(logger_s * 1000000LL));
685 logErrorIndex = JMessageScheduler(logger, JTimekeeper(logger_s * 1000000LL));
686 logErrorIncomplete = JMessageScheduler(logger, JTimekeeper(logger_s * 1000000LL));
688
689 if (c_buffer.is_enabled()) {
690
691 if (!c_buffer.is_open()) {
692
693 c_buffer.open();
694
695 if (c_buffer.is_open()) {
696
698
699 JStatusStream(logger) << "Created circular buffer " << c_buffer;
700
701 } else {
702
703 JErrorStream (logger) << "Failed to create circular buffer in directory <" << c_buffer.path << ">; disable functionality.";
704 }
705
706 } else {
707
708 JNoticeStream(logger) << "Continue using circular buffer " << c_buffer;
709 }
710 }
711
712 if (c_buffer.is_open()) {
713 if (c_buffer.sizeL0 > 0) { static_cast<JTreeWriterObjectOutput<JDAQTimesliceL0>&>(c_buffer).SetCircular(c_buffer.sizeL0); }
714 if (c_buffer.sizeL1 > 0) { static_cast<JTreeWriterObjectOutput<JDAQTimesliceL1>&>(c_buffer).SetCircular(c_buffer.sizeL1); }
715 if (c_buffer.sizeL2 > 0) { static_cast<JTreeWriterObjectOutput<JDAQTimesliceL2>&>(c_buffer).SetCircular(c_buffer.sizeL2); }
716 if (c_buffer.sizeSN > 0) { static_cast<JTreeWriterObjectOutput<JDAQTimesliceSN>&>(c_buffer).SetCircular(c_buffer.sizeSN); }
717 } else {
719 }
720 }
721
722
723 virtual void actionStart(int length, const char* buffer) override
724 {
725 using namespace std;
726
727 if (reporting) {
728 JNoticeStream(logger) << "Start run " << getRunNumber();
729 }
730
731 timeslices.clear();
732
734 dataqueue_slice_index.clear();
735 queueSize = 0;
736
737 numberOfEvents = 0;
738 numberOfBytes = 0;
741
745 number_of_reads = 0;
746
747 minFrameNumber = numeric_limits<int>::max();
748 maxFrameNumber = numeric_limits<int>::min();
749
750 // Reset global trigger counter.
751
753
759
760 timer.reset();
761 timer.start();
762
763 Qt.reset();
764 Qx.reset();
765
766 // send trigger parameters to the datawriter
767
768 ostringstream os;
769
770 os << getRunNumber() << ' ' << parameters;
771
772 datawriter->PutFullString(IO_TRIGGER_PARAMETERS, os.str());
773 }
774
775
776 virtual void actionPause(int length, const char* buffer) override
777 {
778 using namespace std;
779
780 if (!timeslices.empty()) {
781
782 JNoticeStream(logger) << "Flushing " << timeslices.size() << " slices.";
783
784 for (deque<JDAQTimesliceL0>::const_iterator i = timeslices.begin(); i != timeslices.end(); ++i) {
785 queueSize -= getSizeof(*i);
786 }
787
788 timeslices.clear();
789 }
790
791 { // force clearance of memory
792
793 deque<JDAQTimesliceL0> buffer;
794
795 timeslices.swap(buffer);
796 }
797
798 if (queueSize != 0) {
799 JWarningStream(logger) << "Pending data in queue " << queueSize << " [B]";
800 }
801
803 dataqueue_slice_index.clear();
804 queueSize = 0;
805
806 timer.stop();
807 }
808
809
810 virtual void actionContinue(int length, const char* buffer) override
811 {
812 timer.start();
813 }
814
815
816 virtual void actionStop(int length, const char* buffer) override
817 {
818 typeout();
819 }
820
821
822 virtual void actionReset(int length, const char* buffer) override
823 {
824 if (serversocket.is_valid()) {
825 serversocket->shutdown();
826 }
827
828 serversocket.reset();
829 }
830
831
832 virtual void actionQuit(int length, const char* buffer) override
833 {
834 datawriter.reset();
835 }
836
837
838 virtual void setSelect(JFileDescriptorMask& mask) const override
839 {
840 if (serversocket.is_valid()) {
841 mask.set(*serversocket);
842 }
843
844 for (JChannelList_t::const_iterator channel = channelList.begin(); channel != channelList.end(); ++channel) {
845 if (!channel->isReady()) {
846 mask.set(channel->getFileDescriptor());
847 }
848 }
849 }
850
851
852 virtual void actionSelect(const JFileDescriptorMask& mask) override
853 {
854 using namespace std;
855
856 for (JChannelList_t::iterator channel = channelList.begin(); channel != channelList.end(); ) {
857
858 try {
859
860 if (mask.has(channel->getFileDescriptor())) {
861 channel->read();
862 }
863
864 if (channel->isReady()) {
865
867 number_of_reads += channel->getCounter();
868 number_of_bytes_received += channel->size();
869
870 if (isRunning()) {
871
872 try {
873 updateFrameQueue(*channel);
874 }
875 catch(const std::exception& error) {
876
877 JErrorStream(logErrorRun) << "Update frame queue " << channel->getFileDescriptor() << ' ' << channel->size() << ' ' << error.what();
878
880 }
881
882 } else {
883
884 JErrorStream(logErrorRun) << "Receiving data while not running.";
885
887 }
888
889 channel->reset();
890 }
891
892 ++channel;
893 }
894 catch(const std::exception& error) {
895
896 if (isRunning()) {
897 JErrorStream(logger) << "Disconnect channel " << channel->getFileDescriptor() << ' ' << error.what();
898 }
899
900 channel->shutdown();
901
902 channel = channelList.erase(channel);
903 }
904 }
905
906
907 if (serversocket.is_valid()) {
908
909 if (mask.has(*serversocket)) {
910
911 JTCPSocket socket(serversocket->getFileDescriptor());
912
914
915 socket.setKeepAlive (true);
916 socket.setNonBlocking(false);
917
918 JStatusStream(logger) << "New channel" << '[' << socket.getFileDescriptor() << ']' << ' ' << socket.getReceiveBufferSize();
919
920 channelList.push_back(JSocketInputChannel_t(socket));
921 }
922 }
923
924
925 if (!timeslices.empty()) {
926
927 const size_t number_of_frames = getNumberOfFrames(frames_per_slice, factor_per_slice);
928 const size_t maximum_in_queue = getMaximum(make_array(next(timeslices.begin()), timeslices.end(), &JDAQTimesliceL0::size), (size_t) 0);
929
930 if (((timeslices[0].size() >= number_of_frames && // normal
931 timeslices[0].getFrameIndex() < dataqueue_slice_index.min()) ||
932
933 (maximum_in_queue >= number_of_frames && // intermittent problem
934 timeslices[0].getFrameIndex() < dataqueue_slice_index.min()) ||
935
936 (timeslices.size() >= maxQueueDepth) || // timeout
937 (queueSize >= maxQueueSize))) {
938
939
940 const JDAQTimesliceL0& pending_slice = timeslices.front();
941 queueSize -= getSizeof(pending_slice);
942
943 current_slice_index = pending_slice.getFrameIndex();
944 minFrameNumber = min(minFrameNumber, pending_slice.getFrameIndex());
945 maxFrameNumber = max(maxFrameNumber, pending_slice.getFrameIndex());
946
947 for (JDAQTimesliceL0::const_iterator i = pending_slice.begin(); i != pending_slice.end(); ++i) {
948 modules.insert(i->getModuleID());
949 }
950
951
952 if (isRunning()) {
953
954 const localtime_t t0 = getLocalTime();
955
956 if (!pending_slice.empty()) {
957 processTimeSlice(pending_slice);
958 }
959
960 const localtime_t t1 = getLocalTime();
961
963
964 Qt.put(t1 - t0);
965
966 } else {
967
968 JErrorStream(logErrorRun) << "Skip processing of data while not running.";
969 }
970
971
972 if (modules.size() > frames_per_slice) {
973
974 JErrorStream(logErrorOvercomplete) << "More active modules than expected "
975 << modules.size() << " > " << frames_per_slice
976 << " adjusting frames per slice to " << modules.size();
977
978 frames_per_slice = modules.size();
979 }
980
981
982 if (pending_slice.size() < number_of_frames) {
983
985
986 ostringstream error;
987
988 error << "Timeout -> processed incomplete timeslice: "
989 << "Frame index = " << pending_slice.getFrameIndex() << ';'
990 << "Size of timeslice = " << pending_slice.size() << ';'
991 << "Queue depth = " << timeslices.size() << ';'
992 << "Queue size = " << queueSize << ';'
993 << "DataQueue min = " << dataqueue_slice_index.min() << ';'
994 << "DataQueue max = " << dataqueue_slice_index.max() << ';';
995
996 if (maximum_in_queue >= number_of_frames) {
997
998 error << " intermittent problem -> continues as-is";
999
1000 } else {
1001
1002 modules.clear(); // remove history
1003
1004 for (JDAQTimesliceL0::const_iterator i = pending_slice.begin(); i != pending_slice.end(); ++i) {
1005 modules.insert(i->getModuleID());
1006 }
1007
1008 error << " adjusting frames per timeslice from " << frames_per_slice << " to " << modules.size();
1009
1010 frames_per_slice = modules.size();
1011 }
1012
1013 JErrorStream(logErrorIncomplete) << error.str();
1014 }
1015
1016
1017 timeslices.pop_front();
1018 }
1019 }
1020 }
1021
1022
1023 virtual void actionRunning() override
1024 {
1025 if (reporting) {
1026 typeout();
1027 }
1028 }
1029
1030
1031 /**
1032 * Update queue with data frames.
1033 *
1034 * Note that any discarded data will be reported.
1035 *
1036 * \param channel incoming data channel
1037 */
1039 {
1040 using namespace std;
1041
1042 JByteArrayReader in(channel.data(), channel.size());
1043
1044 JDAQPreamble preamble;
1045 JDAQSuperFrameHeader header;
1046
1047 in >> preamble;
1048 in >> header;
1049
1050 if (preamble.getLength() != channel.size()) {
1051
1052 JErrorStream(logErrorRun) << "Size of received data does not match size reported by preamble: "
1053 << "preamble.getLength() = " << preamble.getLength() << ';'
1054 << "channel.size(): " << channel.size() << ';';
1055
1057
1058 return;
1059 }
1060
1061 if (header.getRunNumber() != getRunNumber()) {
1062
1063 JErrorStream(logErrorRun) << "Run number " << header.getRunNumber()
1064 << " != " << getRunNumber()
1065 << " -> Dropping frame.";
1066
1068
1069 return;
1070 }
1071
1072 if (header.getFrameIndex() <= current_slice_index) {
1073
1075
1076 if (modules.insert(header.getModuleID()).second) {
1077
1078 frames_per_slice = modules.size();
1079
1080 JErrorStream(logErrorIndex) << "Frame index " << header.getFrameIndex() << " <= " << current_slice_index
1081 << " module " << header.getModuleID()
1082 << " -> dropping frame;"
1083 << " increase number of frames expected to: " << frames_per_slice;
1084 }
1085
1086 return;
1087 }
1088
1090
1092
1093 JErrorStream(logErrorIndex) << "Frame index " << header.getFrameIndex() << " > " << current_slice_index + maximal_frame_index
1094 << " module " << header.getModuleID()
1095 << " -> Dropping frame.";
1096
1097 return;
1098 }
1099
1100 deque<JDAQTimesliceL0>::iterator timesliceIterator = timeslices.begin();
1101
1102 while (timesliceIterator != timeslices.end() && timesliceIterator->getFrameIndex() < header.getFrameIndex()) {
1103 ++timesliceIterator;
1104 }
1105
1106 if (timesliceIterator != timeslices.end() && timesliceIterator->getFrameIndex() == header.getFrameIndex()) {
1107
1108 // The corresponding time slice already exists
1109
1110 } else {
1111
1112 // This is the first frame of this time slice; insert a new time slice in the buffer at the right position in the list
1113
1114 timesliceIterator = timeslices.insert(timesliceIterator, JDAQTimesliceL0());
1115
1116 timesliceIterator->setDAQChronometer(header.getDAQChronometer());
1117
1118 queueSize += getSizeof(*timesliceIterator);
1119 }
1120
1121 timesliceIterator->push_back(JDAQSuperFrame(header));
1122
1123 in >> static_cast<JDAQFrame&>(*(timesliceIterator->rbegin()));
1124
1125 queueSize += getSizeof(*timesliceIterator->rbegin());
1126
1128 }
1129
1130
1131 /**
1132 * Process time slice.
1133 *
1134 * \param timeslice time slice
1135 */
1136 void processTimeSlice(const JDAQTimesliceL0& timeslice)
1137 {
1138 using namespace std;
1139
1140 try {
1141
1142 timesliceRouter->configure(timeslice);
1143
1144 if (parameters.writeSummary()) {
1145 this->put(JDAQSummaryslice(timeslice));
1146 }
1147
1148 if (parameters.trigger3DMuon.enabled ||
1149 parameters.trigger3DShower.enabled ||
1150 parameters.triggerMXShower.enabled ||
1151 parameters.triggerNB.enabled ||
1152 parameters.triggerRandom.enabled ||
1153 parameters.writeL0.prescale ||
1154 parameters.writeL1.prescale ||
1155 parameters.writeL2.prescale ||
1156 parameters.writeSN.prescale ||
1157 c_buffer.is_enabled()) {
1158
1159 JTimeslice_t timesliceL0(timeslice.getDAQChronometer());
1160 JTimeslice_t timesliceL1(timeslice.getDAQChronometer());
1161 JTimeslice_t timesliceL2(timeslice.getDAQChronometer());
1162 JTimeslice_t timesliceSN(timeslice.getDAQChronometer());
1163 JTimeslice_t timesliceNB(timeslice.getDAQChronometer());
1164 JDAQTimeslice timesliceTX(timeslice.getDAQChronometer());
1165
1166 for (JDAQTimesliceL0::const_iterator frame = timeslice.begin(); frame != timeslice.end(); ++frame) {
1167
1168 if (moduleRouter->hasModule(frame->getModuleID())) {
1169
1170 const JChecksum::result_type& result = checksum(*frame);
1171
1172 if (!result) {
1173
1174 JWarningStream(logger) << "Invalid data at "
1175 << "run = " << timeslice.getRunNumber() << ";"
1176 << "frame index = " << timeslice.getFrameIndex() << ";"
1177 << "module = " << frame->getModuleID() << ";"
1178 << "discard" << (dumpCount < dumpLimit ? " and dump" : "");
1179
1180 if (dumpCount < dumpLimit && result.has(dumpMask)) {
1181 timesliceTX.push_back(*frame);
1182 }
1183
1184 continue;
1185 }
1186
1187 const JModule& module = moduleRouter->getModule(frame->getModuleID());
1188 JSuperFrame2D_t& buffer = JSuperFrame2D_t::demultiplex(*frame, module);
1189
1190 // Apply high-rate veto
1191
1192 buffer.applyHighRateVeto(parameters.highRateVeto_Hz);
1193
1194 // L0
1195
1196 timesliceL0.push_back(JSuperFrame1D_t(buffer));
1197
1198 // Nano-beacon trigger
1199
1200 if (parameters.triggerNB.enabled) {
1201
1202 JSuperFrame2D_t::iterator __end = partition(buffer.begin(), buffer.end(), parameters.triggerNB.pmts);
1203
1204 if (buffer.begin() != __end) {
1205
1206 timesliceNB.push_back(JSuperFrame1D_t(frame->getDAQChronometer(),
1207 frame->getModuleIdentifier(),
1208 module.getPosition()));
1209
1210 JSuperFrame1D_t zbuf;
1211
1212 (*buildL1)(buffer.begin(), __end, back_inserter(zbuf));
1213
1214 (*buildNB)(buffer.begin(), __end, zbuf, back_inserter(*timesliceNB.rbegin()));
1215 }
1216 }
1217
1218 // L1
1219
1220 timesliceL1.push_back(JSuperFrame1D_t(frame->getDAQChronometer(),
1221 frame->getModuleIdentifier(),
1222 module.getPosition()));
1223
1224 (*buildL1)(*timesliceL0.rbegin(), back_inserter(*timesliceL1.rbegin()));
1225
1226 // L2
1227
1228 timesliceL2.push_back(JSuperFrame1D_t(frame->getDAQChronometer(),
1229 frame->getModuleIdentifier(),
1230 module.getPosition()));
1231
1232 (*buildL2)(buffer, *timesliceL1.rbegin(), back_inserter(*timesliceL2.rbegin()));
1233
1234 // SN
1235 {
1236 JTimeslice_t::value_type tv(frame->getDAQChronometer(),
1237 frame->getModuleIdentifier(),
1238 module.getPosition());
1239
1240 (*buildSN)(buffer, *timesliceL1.rbegin(), back_inserter(tv));
1241
1242 if (!tv.empty()) {
1243 timesliceSN.push_back(tv);
1244 }
1245 }
1246
1247 } else {
1248
1249 JErrorStream(logErrorDetector) << "No detector information for module " << frame->getModuleID();
1250 }
1251 }
1252
1253 if (!timesliceTX.empty()) {
1254
1255 if (dumpCount < dumpLimit) {
1256
1257 this->put(timesliceTX);
1258
1259 dumpCount += 1;
1260 }
1261 }
1262
1263 // Triggers
1264
1265 if (parameters.triggerNB.enabled) {
1266
1267 const JTriggerInput trigger_input(timesliceNB);
1268
1269 for (JTriggerInput::const_iterator hit = trigger_input.begin(); hit != trigger_input.end(); ++hit) {
1270
1271 if (parameters.triggerNB.write()) {
1272
1273 JTriggeredEvent tev(timesliceNB.getDAQChronometer(),
1274 getTriggerMask(triggerNB->getTriggerBit()),
1275 *hit,
1277 *moduleRouter,
1278 parameters.TMaxLocal_ns,
1279 parameters.triggerNB.DMax_m,
1280 getTimeRange(parameters.triggerNB));
1281
1282 this->put(tev);
1283 }
1284 }
1285 }
1286
1287 if (parameters.triggerRandom.enabled) {
1288
1289 if (parameters.triggerRandom.rate_Hz > 0.0) {
1290
1291 exponential_distribution<double> f1(parameters.triggerRandom.rate_Hz * 1.0e-9);
1292
1293 while (rabbit.t1_ns < getTimeOfFrame(timeslice.getFrameIndex())) {
1294 rabbit.t1_ns += f1(rabbit.gr);
1295 }
1296
1297 for (double t1_ns; (t1_ns = rabbit.t1_ns - getTimeOfFrame(timeslice.getFrameIndex())) <= getFrameTime(); ) {
1298
1299 JTriggeredEvent tev(t1_ns,
1300 parameters.triggerRandom.TMax_ns,
1303 *moduleRouter);
1304
1305 this->put(tev);
1306
1307 rabbit.t1_ns += f1(rabbit.gr);
1308 }
1309 }
1310 }
1311
1312 JTriggerInput trigger_input(timesliceL2);
1313 JTriggerOutput trigger_output;
1314
1315 (*trigger3DMuon) (trigger_input, back_inserter(trigger_output));
1316 (*trigger3DShower)(trigger_input, back_inserter(trigger_output));
1317 (*triggerMXShower)(trigger_input, timesliceL0, back_inserter(trigger_output));
1318
1319 trigger_output.merge(JEventOverlap(parameters.TMaxEvent_ns));
1320
1321 for (JTriggerOutput::const_iterator event = trigger_output.begin(); event != trigger_output.end(); ++event) {
1322
1323 const JTriggeredEvent object(*event, *timesliceRouter, *moduleRouter, parameters.TMaxLocal_ns, getTimeRange(parameters));
1324
1325 this->put(object);
1326
1327 numberOfEvents += 1;
1328 }
1329
1330 if (parameters.writeL1() || c_buffer.sizeL1 > 0) {
1331
1332 const JTimesliceL1<JDAQTimesliceL1> object(timesliceL1, *timesliceRouter, *moduleRouter, parameters.TMaxLocal_ns);
1333
1334 if (parameters.writeL1) { this->put(object); }
1335 if (c_buffer.sizeL1 > 0) { c_buffer.put(object); }
1336 }
1337
1338 if (parameters.writeL2() || c_buffer.sizeL2 > 0) {
1339
1340 const JTimesliceL1<JDAQTimesliceL2> object(timesliceL2, *timesliceRouter, *moduleRouter, parameters.L2.TMaxLocal_ns);
1341
1342 if (parameters.writeL2) { this->put(object); }
1343 if (c_buffer.sizeL2 > 0) { c_buffer.put(object); }
1344 }
1345
1346 if (parameters.writeSN() || c_buffer.sizeSN > 0) {
1347
1348 const JTimesliceL1<JDAQTimesliceSN> object(timesliceSN, *timesliceRouter, *moduleRouter, parameters.SN.TMaxLocal_ns);
1349
1350 if (parameters.writeSN) { this->put(object); }
1351 if (c_buffer.sizeSN > 0) { c_buffer.put(object); }
1352 }
1353
1354 if (parameters.writeL0() || c_buffer.sizeL0 > 0) {
1355
1356 if (parameters.writeL0) { this->put(timeslice); }
1357 if (c_buffer.sizeL0 > 0) { c_buffer.put(timeslice); }
1358 }
1359 }
1360
1361 } catch(const std::exception& error) {
1362
1363 JErrorStream(logger) << "Error = " << error.what() << ";"
1364 << "run = " << timeslice.getRunNumber() << ";"
1365 << "frame index = " << timeslice.getFrameIndex() << ";"
1366 << "time slice not correctly processed;"
1367 << "discard" << (dumpCount < dumpLimit ? " and dump" : "");
1368
1369 if (dumpCount < dumpLimit) {
1370
1371 this->put(static_cast<const JDAQTimeslice&>(timeslice));
1372
1373 dumpCount += 1;
1374 }
1375 }
1376
1377 timesliceRouter->reset();
1378 }
1379
1380
1381 /**
1382 * Report status to message logger.
1383 */
1384 void typeout()
1385 {
1386 timer.stop();
1387
1388 const double T_us = (double) timer.usec_wall;
1389
1390 JStatusStream(logger) << "Elapsed real (wall) time [s] " << T_us / 1e6;
1391 JStatusStream(logger) << "Elapsed user CPU time [s] " << (double) timer.usec_ucpu/ 1e6;
1392 JStatusStream(logger) << "Elapsed system CPU time [s] " << (double) timer.usec_scpu/ 1e6;
1393 JStatusStream(logger) << "Elapsed real time per time slice [ms] " << Qt.getMean(0.0) * 1.0e-3 << " <= " << Qt.getXmax() * 1.0e-3;
1394 JStatusStream(logger) << "Number of packets received/discarded " << number_of_packets_received << "/" << number_of_packets_discarded;
1395 JStatusStream(logger) << "Number of events/MB/us " << numberOfEvents << "/" << numberOfBytes/1e6 << "/" << Qx.getMean(0.0);
1396
1398 JStatusStream(logger) << "Number of reads/packet " << (double) number_of_reads / (double) number_of_packets_received;
1399 }
1400
1401 JStatusStream(logger) << "Current queue depth/size " << timeslices.size() << "/" << queueSize;
1402 JStatusStream(logger) << "Current number of frames per slice expected: " << frames_per_slice << ' ' << FIXED(5,3) << factor_per_slice;
1403
1404 JStatusStream(logger) << "Number of timeslices processed total/incomplete " << numberOfTimeslicesProcessed << "/" << numberOfIncompleteTimeslicesProcessed;
1405
1406 const double processedSlicesTime_us = numberOfTimeslicesProcessed * getFrameTime() / 1000;
1407 const double processedDetectorTime_us = (maxFrameNumber - minFrameNumber) * getFrameTime() / 1000;
1408
1409 if (processedSlicesTime_us > 0) {
1410 JStatusStream(logger) << "Performance factor (inaccurate estimate): " << T_us / processedSlicesTime_us;
1411 }
1412 if (processedDetectorTime_us > 0) {
1413 JStatusStream(logger) << "Performance factor whole detector (inaccurate estimate): " << T_us / processedDetectorTime_us;
1414 }
1415
1416 timer.start();
1417 }
1418
1419
1420 /**
1421 * Tagged action to handle alerts.
1422 *
1423 * \param tag tag
1424 * \param length number of characters
1425 * \param buffer message
1426 */
1427 virtual void actionTagged(const JTag& tag, int length, const char* buffer) override
1428 {
1429 using namespace std;
1430
1431 JDebugStream(logger) << "Received message <" << tag.toString() << "> \"" << string(buffer, length) << "\"";
1432
1433 if (tag == RC_ALERT) {
1434
1435 if (c_buffer.is_open()) {
1436
1437 JStatusStream(logger) << "Archive circular buffer in <" << c_buffer.archive << ">";
1438
1439 c_buffer.close(true);
1440 }
1441
1442 if (c_buffer.is_enabled()) {
1443
1444 c_buffer.open();
1445
1446 if (c_buffer.is_open()) {
1447
1448 JStatusStream(logger) << "Created circular buffer " << c_buffer;
1449
1451
1452 } else {
1453
1454 JErrorStream (logger) << "Failed to create circular buffer in directory <" << c_buffer.path << ">; disable functionality.";
1455
1456 c_buffer.disable();
1457 }
1458 }
1459
1460 } else {
1461
1462 JWarningStream(logger) << "Tag <" << tag.toString() << "> not implemented";
1463 }
1464 }
1465
1466 JMeta meta; //!< meta data
1467
1468 private:
1469
1471 JSinglePointer<JControlHost_t> datawriter; //!< controlhost of data server (to which data writer should be connected)
1472 std::string hostname; //!< host name of data server
1473
1474 /**
1475 * Auxiliary method to send object to data server.
1476 *
1477 * \param object object to be sent
1478 */
1479 template<class T>
1480 void put(const T& object)
1481 {
1482 try {
1483
1484 const localtime_t t0 = getLocalTime();
1485
1486 datawriter->put(object);
1487
1488 const localtime_t t1 = getLocalTime();
1489
1490 numberOfBytes += getSizeof(object);
1491
1492 Qx.put(t1 - t0);
1493 }
1494 catch(const std::exception& error) {
1495 JErrorStream(logger) << "Error \"" << error.what() << "\"; trigger ev_error.";
1496 ev_error();
1497 }
1498 }
1499
1500
1501 int port; //!< server socket port
1503
1504 JSinglePointer<JServerSocket> serversocket; //!< server for data queue connections
1505 JChannelList_t channelList; //!< connections to data queue
1506
1509
1510 std::deque<JDAQTimesliceL0> timeslices; //!< buffer with pending time slice data
1516
1517 struct :
1518 public std::map<int, int>
1519 {
1520 /**
1521 * Get minimal frame index.
1522 *
1523 * \return frame index
1524 */
1525 int min() const
1526 {
1527 if (this->empty()) {
1528
1529 return -1;
1530
1531 } else {
1532
1533 int min = std::numeric_limits<int>::max();
1534
1535 for (const_iterator i = this->begin(); i != this->end(); ++i) {
1536 if (i->second < min) {
1537 min = i->second;
1538 }
1539 }
1540
1541 return min;
1542 }
1543 }
1544
1545 /**
1546 * Get maximal frame index.
1547 *
1548 * \return frame index
1549 */
1550 int max() const
1551 {
1552 if (this->empty()) {
1553
1554 return -1;
1555
1556 } else {
1557
1558 int max = std::numeric_limits<int>::lowest();
1559
1560 for (const_iterator i = this->begin(); i != this->end(); ++i) {
1561 if (i->second > max) {
1562 max = i->second;
1563 }
1564 }
1565
1566 return max;
1567 }
1568 }
1569
1571
1572 // trigger
1573
1576
1583
1588
1594
1596 int dumpLimit; //!< maximum number of time slices to be dumped
1597 JStatus dumpMask; //!< mask for data to be dumped
1598
1599 // process management
1600
1603
1604 // memory management
1605
1606 long long int totalCPURAM;
1608 long long int maxQueueSize;
1609 long long int queueSize;
1610
1611 // statistics
1612
1614
1615 long long int numberOfEvents;
1616 long long int numberOfBytes;
1619
1622
1623 // temporary
1624
1627 long long int number_of_reads;
1629
1630 // circular buffer
1631
1633
1634 // random trigger
1635
1637
1639 gr(rd()),
1640 t1_ns(0.0)
1641 {}
1642
1643 std::random_device rd;
1644 std::mt19937_64 gr;
1645 double t1_ns;
1646
1648 };
1649}
1650
1651/**
1652 * \file
1653 *
1654 * Application for real-time filtering of data.
1655 * For more information, see KM3NETDAQ::JDataFilter.
1656 *
1657 * \author rbruijn and mdejong
1658 */
1659int main(int argc, char* argv[])
1660{
1661 using namespace std;
1662 using namespace JPP;
1663 using namespace KM3NETDAQ;
1664
1665 string server;
1666 string logger;
1667 string hostname;
1668 string client_name;
1669 int port;
1670 int backlog;
1671 bool use_cout;
1672 string path;
1673 string archive;
1674 int debug;
1675
1676
1677 try {
1678
1679 JParser<> zap("Application for real-time filtering of data.");
1680
1681 zap['H'] = make_field(server, "host name of server for command messages") = "localhost";
1682 zap['M'] = make_field(logger, "host name of server for logger messages") = "localhost";
1683 zap['D'] = make_field(hostname, "host name of server of data writer") = "";
1684 zap['u'] = make_field(client_name, "client name") = "%";
1685 zap['P'] = make_field(port, "port to listen for incoming data from data queue");
1686 zap['q'] = make_field(backlog, "back log") = 1024;
1687 zap['c'] = make_field(use_cout, "print to terminal");
1688 zap['p'] = make_field(path, "directory for temporary storage of circular buffer") = "/tmp/";
1689 zap['A'] = make_field(archive, "directory for permanent archival of circular buffer") = "/tmp/";
1690 zap['d'] = make_field(debug, "debug level") = 0;
1691
1692 zap(argc, argv);
1693 }
1694 catch(const std::exception& error) {
1695 FATAL(error.what() << endl);
1696 }
1697
1698
1699 JLogger* out = NULL;
1700
1701 if (use_cout)
1702 out = new JStreamLogger(cout);
1703 else
1704 out = new JControlHostLogger(logger);
1705
1706 JDataFilter dfilter(client_name,
1707 server,
1708 hostname,
1709 out,
1710 debug,
1711 port,
1712 backlog,
1713 path,
1714 archive);
1715
1716 dfilter.meta = JMeta(argc, argv);
1717
1718 dfilter.enter();
1719 dfilter.run();
1720}
Fixed parameters and ControlHost tags for KM3NeT DAQ.
KM3NeT DAQ constants, bit handling, etc.
Data structure for detector geometry and calibration.
Exceptions.
Basic data structure for L0 hit.
Basic data structure for L1 hit.
Tools for handling different hit types.
General purpose messaging.
#define FATAL(A)
Definition JMessage.hh:67
int debug
debug level
Definition JSirene.cc:74
ROOT I/O of application specific meta data.
Hostname and IP address functions.
Utility class to parse command line options.
#define make_field(A,...)
macro to convert parameter to JParserTemplateElement object
Definition JParser.hh:2107
Physics constants.
I/O formatting auxiliaries.
Utility class to parse parameter values.
ROOT TTree parameter settings of various packages.
System auxiliaries.
System time information.
Scheduling of actions via fixed latency intervals.
Setting of trigger bits.
Basic data structure for time and time over threshold information of hit.
Auxiliary methods to convert data members or return values of member methods of a set of objects to a...
Auxiliary methods for handling file names, type names and environment.
void merge(const JMatch_t &match)
Merge events.
int getRunNumber() const
Get run number.
Definition JDAQCHSM.hh:111
std::string name
Definition JDAQCHSM.hh:165
JDAQStateMachine::ev_error_event ev_error
JDAQStateMachine::ev_configure_event ev_configure
Detector data structure.
Definition JDetector.hh:96
Router for direct addressing of module data in detector data structure.
Data structure for a composite optical module.
Definition JModule.hh:76
Utility class to parse parameter values.
bool read(const JEquation &equation)
Read equation.
Time keeper.
Auxiliary class for CPU timing and usage.
Definition JTimer.hh:33
unsigned long long usec_ucpu
Definition JTimer.hh:239
unsigned long long usec_wall
Definition JTimer.hh:238
void stop()
Stop timer.
Definition JTimer.hh:127
void reset()
Reset timer.
Definition JTimer.hh:93
unsigned long long usec_scpu
Definition JTimer.hh:240
void start()
Start timer.
Definition JTimer.hh:106
const JPosition3D & getPosition() const
Get position.
Byte array binary input.
const char * data() const
Get data.
int size() const
Get size.
int getFileDescriptor() const
Get file descriptor.
virtual bool is_open() const =0
Check is device is open.
Simple data structure to support I/O of equations (see class JLANG::JEquation).
Auxiliary class for method select.
void set(const int file_descriptor)
Set file descriptor.
bool has(const int file_descriptor) const
Has file descriptor.
The template JSinglePointer class can be used to hold a pointer to an object.
Message logging based on ControlHost.
Interface for logging messages.
Definition JLogger.hh:22
Message logger with time scheduler.
Message logging based on std::ostream.
Implemenation of object output through ControlHost.
TCP server socket.
Socket input channel.
void setReceiveBufferSize(const int size)
Set receive buffer size.
Definition JSocket.hh:148
int getReceiveBufferSize() const
Set receive buffer size.
Definition JSocket.hh:159
void setKeepAlive(const bool on)
Set keep alive of socket.
Definition JSocket.hh:104
TCP socket.
Definition JTCPSocket.hh:30
void setNonBlocking(const bool on)
Set non-blocking of I/O.
Definition JTCPSocket.hh:56
ControlHost tag.
Definition JTag.hh:38
std::string toString() const
Convert tag to string.
Definition JTag.hh:171
Utility class to parse command line options.
Definition JParser.hh:1664
TFile * getFile() const
Get file.
Definition JRootFile.hh:66
virtual bool is_open() const override
Check is file is open.
Definition JRootFile.hh:77
JTreeWriter< T, JRootCreateFlatTree< T >::value > * out
virtual bool put(const T &object) override
Object output.
ROOT TTree object output.
1-dimensional frame with time calibrated data from one optical module.
2-dimensional frame with time calibrated data from one optical module.
static JSuperFrame2D< JElement_t, JAllocator_t > demultiplex
Demultiplexer.
std::vector< value_type >::iterator iterator
void applyHighRateVeto(const double rate_Hz)
Apply high-rate veto.
Auxiliary class to build JDAQTimeslice for L1 timeslice.
Time slice with calibrated data.
Definition JTimeslice.hh:29
Data structure for input to trigger algorithm.
Nano-beacon trigger.
Definition JTriggerNB.hh:21
Auxiliary class to build KM3NETDAQ::JDAQEvent for a triggered event.
Simple data structure for the DAQ preamble required for a correct calculation of the object size for ...
const JDAQChronometer & getDAQChronometer() const
Get DAQ chronometer.
int getRunNumber() const
Get run number.
int getFrameIndex() const
Get frame index.
Control unit client base class.
bool isRunning() const
Check if this client is in runnig state.
void replaceEvent(const JTag &oldTag, const JTag &newTag, JDAQEvent_t &event)
Replace tag of given event in event table.
std::shared_ptr< JControlHost > server
message server
void run()
Run as run control client following command messages via JNET::JControlHost.
JMessageLogger logger
message logger
virtual bool enter(const JArgs &args)
Enter the state machine.
void addSubscription(const JSubscription &subscription)
Add custom subscription.
int getModuleID() const
Get module identifier.
Auxiliary class for itemization of process list.
std::string index
index in process list
Data frame of one optical module.
static void reset()
Reset counter of unique instance of this class object.
Main class for real-time filtering of data.
long long int number_of_packets_received
JMessageScheduler logErrorRun
int dumpLimit
maximum number of time slices to be dumped
JSinglePointer< JServerSocket > serversocket
server for data queue connections
JMessageScheduler logErrorDetector
virtual void actionRunning() override
This method is repeatedly called when this client machine is in state Running and the clock interval ...
JCircularBuffer_t c_buffer
virtual void actionSelect(const JFileDescriptorMask &mask) override
Action method following last select call.
long long int numberOfBytes
long long int number_of_packets_discarded
JMessageScheduler logErrorIndex
static bool compare(const JDAQProcess &first, const JDAQProcess &second)
Sort DAQ process by index.
virtual void actionInit(int length, const char *buffer) override
void put(const T &object)
Auxiliary method to send object to data server.
JSocketInputChannel< JDAQAbstractPreamble > JSocketInputChannel_t
long long int number_of_bytes_received
virtual void actionContinue(int length, const char *buffer) override
long long int maxQueueSize
int port
server socket port
long long int totalCPURAM
void processTimeSlice(const JDAQTimesliceL0 &timeslice)
Process time slice.
std::deque< JDAQTimesliceL0 > timeslices
buffer with pending time slice data
std::vector< JDAQProcess > dataQueues
JMessageScheduler logErrorOvercomplete
long long int number_of_reads
std::vector< JSocketInputChannel_t > JChannelList_t
virtual void actionStop(int length, const char *buffer) override
JSinglePointer< JBuildL2_t > buildNB
JSinglePointer< JBuildL2_t > buildL2
JBuildL1< hit_type > JBuildL1_t
JSinglePointer< JBuildL1_t > buildL1
virtual void actionExit() override
virtual void actionQuit(int length, const char *buffer) override
virtual void actionTagged(const JTag &tag, int length, const char *buffer) override
Tagged action to handle alerts.
std::string hostname
host name of data server
virtual void actionConfigure(int length, const char *buffer) override
long long int numberOfTimeslicesProcessed
void updateFrameQueue(const JSocketInputChannel_t &channel)
Update queue with data frames.
JChannelList_t channelList
connections to data queue
long long int numberOfIncompleteTimeslicesProcessed
JSinglePointer< JTrigger3DMuon > trigger3DMuon
JDataFilter(const std::string &name, const std::string &server, const std::string &hostname, JLogger *logger, const int level, const int port, const int backlog, const std::string &path, const std::string &archive)
Constructor.
JSuperFrame1D< hit_type > JSuperFrame1D_t
virtual void setSelect(JFileDescriptorMask &mask) const override
Set the file descriptor mask for the select call.
JMessageScheduler logErrorIncomplete
JSuperFrame2D< hit_type > JSuperFrame2D_t
virtual void actionEnter() override
Interface methods for actions corresponding to state transitions.
JTimeslice< hit_type > JTimeslice_t
JStatus dumpMask
mask for data to be dumped
struct KM3NETDAQ::JDataFilter::rabbit_type rabbit
JSinglePointer< JModuleRouter > moduleRouter
JSinglePointer< JControlHost_t > datawriter
controlhost of data server (to which data writer should be connected)
JSinglePointer< JTimesliceRouter > timesliceRouter
JControlHostObjectOutput< JDAQTypes_t > JControlHost_t
JSinglePointer< JTriggerNB > triggerNB
JBuildL2< hit_type > JBuildL2_t
long long int numberOfEvents
std::vector< JDAQProcess > dataFilters
JSinglePointer< JTrigger3DShower > trigger3DShower
virtual void actionStart(int length, const char *buffer) override
virtual void actionPause(int length, const char *buffer) override
JSinglePointer< JTriggerMXShower > triggerMXShower
virtual void actionReset(int length, const char *buffer) override
std::set< int > modules
JSinglePointer< JBuildL2_t > buildSN
JTriggerParameters parameters
void typeout()
Report status to message logger.
double getMaximalDistance(const JDetector &detector, const bool option=false)
Get maximal distance between modules in detector.
std::string getFullPath(const std::string &path)
Get full path, i.e. add JEEP::PATHNAME_SEPARATOR if necessary.
T getMaximum(const array_type< T > &buffer, const T value)
Get maximum of values.
array_type< JValue_t > make_array(const JValue_t(&array)[N])
Method to create array of values.
Definition JVectorize.hh:69
std::string trim(const std::string &buffer)
Trim string.
static const long long int GIGABYTE
Number of bytes in a mega-byte.
int getSizeOfPacket(const KM3NETDAQ::JDAQAbstractPreamble &preamble)
Get size of packeet.
This name space includes all other name spaces (except KM3NETDAQ, KM3NET and ANTARES).
bool putObject(TDirectory &dir, const TObject &object)
Write object to ROOT directory.
const char * getName()
Get ROOT name of given data type.
static const JLocalTime getLocalTime
Function object to get local time in micro seconds.
long long int localtime_t
Type definition of local time.
unsigned long long int getRAM()
Get RAM of this CPU.
std::vector< std::string > getListOfIPaddresses()
Get list of IP address (decimal-dot notation).
Definition JNetwork.hh:216
return result
Definition JPolint.hh:862
const int n
Definition JPolint.hh:791
static const JChecksum checksum
Function object to perform check-sum of raw data.
Definition JChecksum.hh:200
KM3NeT DAQ data structures and auxiliaries.
Definition DataQueue.cc:39
size_t getNumberOfFrames(const size_t number_of_frames, const double factor)
Get expected number of frames according a given allowed fraction of active modules.
static const JNET::JTag RC_DFILTER
Definition JDAQTags.hh:73
double getFrameTime()
Get frame time duration.
Definition JDAQClock.hh:162
double getTimeOfFrame(const int frame_index)
Get start time of frame in ns since start of run for a given frame index.
Definition JDAQClock.hh:185
static const JNET::JTag RC_ALERT
Definition JDAQTags.hh:79
static const int DFILTER_DQUEUE_BUFFER_SIZE
socket JDataFilter.cc <- DataQueue.cc
Definition JDAQTags.hh:36
static const int DFILTER_RECEIVE_BUFFER_SIZE
socket JDataFilter.cc <- JLigier.cc
Definition JDAQTags.hh:37
static const JNET::JTag RC_CMD
Definition JDAQTags.hh:66
static const int DFILTER_SEND_BUFFER_SIZE
socket JDataFilter.cc -> JDataWriter.cc
Definition JDAQTags.hh:38
static const JNET::JTag IO_TRIGGER_PARAMETERS
Definition JDAQTags.hh:90
size_t getSizeof()
Definition of method to get size of data type.
static const int HIGH_RATE_VETO_DISABLE
Enable (disable) use of high-rate veto test if this status bit is 0 (1);.
Definition pmt_status.hh:14
Auxiliary data structure for sequence of same character.
Definition JManip.hh:330
Auxiliary data structure for floating point format specification.
Definition JManip.hh:448
Detector file.
Definition JHead.hh:227
Match of two events considering overlap in time and position.
Auxiliary class for handling status.
Definition JStatus.hh:31
void set(const int bit)
Set PMT status.
Definition JStatus.hh:209
Type list.
Definition JTypeList.hh:23
Level specific message streamers.
Auxiliary class for all subscription.
Auxiliary class for ROOT I/O of application specific meta data.
Definition JMeta.hh:72
Auxiliary class for date and time.
int getYear() const
year a.d.
int getDay() const
day of the month [1-31]
int getMonth() const
month of the year [1-12]
Auxiliary data structure for running average and standard deviation.
Definition JStats.hh:44
double getXmax() const
Get maximum value.
Definition JStats.hh:201
void put(const double x, const double w=1.0)
Put value.
Definition JStats.hh:119
double getMean() const
Get mean value.
Definition JStats.hh:234
void reset()
Reset.
Definition JStats.hh:79
Auxiliary data structure for result of checksum.
Definition JChecksum.hh:90
@ ETDC_t
TDC value error.
Definition JChecksum.hh:47
@ SIZE_t
size error
Definition JChecksum.hh:50
@ EPMT_t
PMT number error.
Definition JChecksum.hh:46
@ TIME_t
Time order error.
Definition JChecksum.hh:48
Router for fast addressing of hits in KM3NETDAQ::JDAQTimeslice data structure as a function of the op...
const JTag & getUniqueTag() const
Get unique tag of this run control client.
const std::string & getFullName() const
Get full name of this run control client.
void setClockInterval(const long long int interval_us)
Set interval time.
long long int getClockInterval() const
Get interval time.
Timeslice data structure for L0 data.
std::string archive
Directory for permanent archival.
std::string path
Directory for temporary storage.
Long64_t sizeL1
Number of L1 time slices.
Long64_t sizeSN
Number of SN time slices.
friend std::ostream & operator<<(std::ostream &out, const JCircularBuffer_t &object)
Write circular buffer to output stream.
static const int MAXIMUM_FILE_NUMBER
maximum file number for overwrite protection.
JTag tag
Unique tag of this process.
Long64_t sizeL0
Number of L0 time slices.
void close(const bool option)
Close file.
Long64_t sizeL2
Number of L2 time slices.
JCircularBuffer_t(const std::string &path, const std::string &archive, const JTag &tag)
Constructor.
bool is_enabled() const
Check whether writing of data is enabled.
static const int JTRIGGERRANDOM
Random trigger.
Definition trigger.hh:17