source: trunk/FACT++/src/datalogger.cc@ 14365

Last change on this file since 14365 was 14364, checked in by lyard, 12 years ago
fixed missing columns desc and log entries
File size: 74.6 KB
Line 
1//****************************************************************
2/** @class DataLogger
3
4 @brief Logs all message and infos between the services
5
6 This is the main logging class facility.
7 It derives from StateMachineDim and DimInfoHandler. the first parent is here to enforce
8 a state machine behaviour, while the second one is meant to make the dataLogger receive
9 dim services to which it subscribed from.
10 The possible states and transitions of the machine are:
11 \dot
12 // FIXME FIXME: Error states missing...
13 digraph datalogger
14 {
15 node [shape=record, fontname=Helvetica, fontsize=10];
16
17 srt [label="Start" style="rounded"]
18 rdy [label="Ready"]
19 nop [label="NightlyOpen"]
20 wait [label="WaitingRun"]
21 log [label="Logging"]
22
23 //e [label="Error" color="red"];
24 //c [label="BadFolder" color="red"]
25
26
27 cmd_start [label="START" shape="none" height="0"]
28 cmd_stop [label="STOP" shape="none" height="0"]
29 cmd_stopr [label="STOP_RUN_LOGGING" shape="none" height="0"]
30 cmd_startr [label="START_RUN_LOGGING" shape="none" height="0"]
31
32 { rank=same; cmd_startr cmd_stopr }
33 { rank=same; cmd_start cmd_stop }
34
35
36 srt -> rdy
37
38 rdy -> cmd_start [ arrowhead="open" dir="both" arrowtail="tee" weight=10 ]
39 cmd_start -> nop
40
41 nop -> cmd_stop [ arrowhead="none" dir="both" arrowtail="inv" ]
42 wait -> cmd_stop [ arrowhead="none" dir="both" arrowtail="inv" ]
43 log -> cmd_stop [ arrowhead="none" dir="both" arrowtail="inv" ]
44 cmd_stop -> rdy
45
46 wait -> cmd_stopr [ arrowhead="none" dir="both" arrowtail="inv" ]
47 log -> cmd_stopr [ arrowhead="none" dir="both" arrowtail="inv" ]
48 cmd_stopr -> nop
49
50 nop -> cmd_startr [ arrowhead="none" dir="both" arrowtail="inv" weight=10 ]
51 rdy -> cmd_startr [ arrowhead="none" dir="both" arrowtail="inv" ]
52 cmd_startr -> wait [ weight=10 ]
53
54
55 wait -> log
56 log -> wait
57 }
58 \enddot
59
60 For questions or bug report, please contact Etienne Lyard (etienne.lyard@unige.ch) or Thomas Bretz.
61 */
62 //****************************************************************
63#include <unistd.h> //for getting stat of opened files
64//#include <sys/statvfs.h> //for getting disk free space
65//#include <sys/stat.h> //for getting files sizes
66#include <fstream>
67#include <functional>
68
69#include <boost/filesystem.hpp>
70
71#include "Dim.h"
72#include "Event.h"
73#include "StateMachineDim.h"
74#include "LocalControl.h"
75#include "Configuration.h"
76#include "Converter.h"
77#include "DimWriteStatistics.h"
78
79#include "Description.h"
80#include "DimNetwork.h"
81
82#ifdef HAVE_FITS
83#include "Fits.h"
84#endif
85
86#include "DimState.h"
87
88//Dim structures
89///distributes the number of opened subscriptions and fits files
90struct NumSubAndFitsType {
91 uint32_t numSubscriptions;
92 uint32_t numOpenFits;
93};
94///distributes which files were opened.
95struct OpenFileToDim {
96 uint32_t code;
97 char fileName[FILENAME_MAX];
98};
99
100///Run number record. Used to keep track of which run numbers are still active
101struct RunNumberType {
102
103 ///the actual run number
104 int32_t runNumber;
105 ///the time at which the run number was received
106 Time time;
107 ///default constructor
108 RunNumberType()
109 {
110 runNumber = 0;
111 }
112 ///default destructor
113 ~RunNumberType()
114 {
115
116 }
117};
118
119EventImp nullEventImp;
120///Dim subscription type. Stores all the relevant info to handle a Dim subscription
121struct SubscriptionType
122{
123#ifdef HAVE_FITS
124 ///Nightly FITS output file
125 Fits nightlyFile;
126#endif
127 ///the server
128 string server;
129 ///the service
130 string service;
131 ///the converter for outputting the data according to the format
132 shared_ptr<Converter> fConv;
133 ///the current run number used by this subscription
134 int32_t runNumber;
135 ///time of the latest received event
136 Time lastReceivedEvent;
137 ///whether or not the fits buffer was allocated already
138 bool fitsBufferAllocated;
139 ///the actual dimInfo pointer (must be the last in the list to ensure
140 /// that it is the first which is deleted -- and consequently none of
141 /// the other members can still be in use in an infoHandler)
142 //DIM_REPLACE
143 //shared_ptr<DimStampedInfo> dimInfo;
144 unsigned int index;
145
146 ///Dim info constructor
147 //DIM_REPLACE
148// SubscriptionType(DimStampedInfo* info=NULL)
149 SubscriptionType()
150 {
151 fConv = shared_ptr<Converter>();
152 runNumber = 0;
153 lastReceivedEvent = Time::None;
154 fitsBufferAllocated = false;
155 // Should be the last instantiated to make sure that all other
156 // variables which might be used are already initialized
157 //DIM_REPLACE
158 //dimInfo = shared_ptr<DimStampedInfo>(info);
159 index = 0;
160 }
161 ///default destructor
162 ~SubscriptionType()
163 {
164 }
165};
166
167class DataLogger : public StateMachineDim
168//DIM_REPLACE
169//, DimServiceInfoListImp
170{
171public:
172 /// The list of existing states specific to the DataLogger
173 enum
174 {
175 kSM_NightlyOpen = 20, ///< Nightly file openned and writing
176 kSM_WaitingRun = 30, ///< waiting for the run number to open the run file
177 kSM_Logging = 40, ///< both files openned and writing
178 kSM_BadFolder = 0x101, ///< the folder specified for Nightly logging does not exist or has bad permissions
179 kSM_RunWriteError = 0x103, ///< Denotes that an error occured while writing a run file (text or fits).
180 kSM_DailyWriteError = 0x103, ///< Denots that an error occured while writing a daily file (text or fits).
181 } localstates_t;
182
183 DataLogger(ostream &out);
184 ~DataLogger();
185
186 int EvalOptions(Configuration& conf);
187
188private:
189 /************************************************
190 * MEMBER VARIABLES
191 ************************************************/
192 /// ofstream for the NightlyLogfile
193 ofstream fNightlyLogFile;
194 /// ofstream for the Nightly report file
195 ofstream fNightlyReportFile;
196 /// base path of files
197 string fFilePath;
198 ///run numbers
199 list<RunNumberType> fRunNumber;
200 ///old run numbers time-out delay (in seconds)
201 uint32_t fRunNumberTimeout;
202 ///previous run number. to check if changed while logging
203 int fPreviousRunNumber;
204 ///Current Service Quality
205 int fQuality;
206 ///Modified Julian Date
207 double fMjD;
208 ///for obtaining the name of the existing services
209// ServiceList fServiceList;
210 typedef map<const string, map<string, SubscriptionType> > SubscriptionsListType;
211 ///All the services to which we have subscribed to, sorted by server name.
212 SubscriptionsListType fServiceSubscriptions;
213 ///full name of the nightly log file
214 string fFullNightlyLogFileName;
215 ///full name of the nightly report file
216 string fFullNightlyReportFileName;
217 ///variable to track when the statistic were last calculated
218// Time fPreviousStatsUpdateTime;
219 Time fPreviousOldRunNumberCheck;
220 ///boolean to know whether we should close and reopen daily files or not
221 bool fDailyFileDayChangedAlready;
222
223 DimWriteStatistics fFilesStats;
224
225 ///map and mutex for storing services description
226 map<string, vector<Description> > fServiceDescriptionList;
227 mutex fMutex;
228 int HandleDescriptions(DimDescriptions* desc);
229 vector<Description> GetDescription(const string& server, const string& service);
230private:
231 /***************************************************
232 * DIM INFO HANDLER
233 ***************************************************/
234 //overloading of DIM's infoHandler function
235 int infoCallback(const EventImp& evt, unsigned int infoIndex);
236
237 /***************************************************
238 * TRANSITION FUNCTIONS
239 ***************************************************/
240 ///Reporting method for the services info received
241 void Report(const EventImp& evt, SubscriptionType& sub);
242
243 ///Configuration of the nightly file path
244 int ConfigureFilePath(const Event& evt);
245 ///print the current state of the dataLogger
246 int PrintState(const Event& evt);
247 ///checks whether or not the current info being treated is a run number
248 void CheckForRunNumber(const EventImp& evt, unsigned int index);
249 /// start transition
250 int Start();
251 ///from waiting to logging transition
252 //int StartRun();
253 // from logging to waiting transition
254 int StopRunLogging();
255 ///stop and reset transition
256 int GoToReady();
257 ///from NightlyOpen to waiting transition
258 int NightlyToWaitRun();
259 ///from wait for run number to nightly open
260 int BackToNightlyOpen();
261#ifdef HAVE_FITS
262 ///Open fits files
263 void OpenFITSFiles(SubscriptionType& sub, const EventImp& evt);
264 ///Write data to FITS files
265 void WriteToFITS(SubscriptionType& sub, const void* data);
266 ///Allocate the buffers required for fits
267 void AllocateFITSBuffers(SubscriptionType& sub, const EventImp& evt);
268#endif//has_fits
269
270 /***************************************
271 * DIM SERVICES PROVIDED BY THE DATA LOGGER
272 ***************************************/
273 ///monitoring notification loop
274 void ServicesMonitoring();
275 inline void NotifyOpenedFile(const string &name, int type, DimDescribedService* service);
276 ///Service for opened files
277 DimDescribedService* fOpenedNightlyFiles;
278 DimDescribedService* fOpenedRunFiles;
279 DimDescribedService* fNumSubAndFits;
280 NumSubAndFitsType fNumSubAndFitsData;
281
282 /***************************************************
283 * DATA LOGGER's CONFIGURATION STUFF
284 ***************************************************/
285 ///black/white listing
286 set<string> fBlackList;
287 set<string> fWhiteList;
288 ///list of services to be grouped
289 set<string> fGrouping;
290 ///configuration flags
291 bool fDebugIsOn;
292 bool fOpenedFilesIsOn;
293 bool fNumSubAndFitsIsOn;
294 //functions for controlling the services behavior
295 int SetDebugOnOff(const Event& evt);
296 int SetStatsPeriod(const Event& evt);
297 int SetOpenedFilesOnOff(const Event& evt);
298 int SetNumSubsAndFitsOnOff(const Event& evt);
299 int SetRunTimeoutDelay(const Event& evt);
300
301 ///boolean to prevent DIM update while desctructing the dataLogger
302 bool fDestructing;
303 /***************************************************
304 * UTILITIES
305 ***************************************************/
306 ///vectors to keep track of opened Fits files, for grouping purposes.
307 map<string, vector<string> > fOpenedNightlyFits;
308 ///creates a group fits file based on a list of files to be grouped
309 void CreateFitsGrouping(map<string, vector<string> >& filesToGroup);
310
311 bool OpenStreamImp(ofstream &stream, const string &filename, bool mightbeopen);
312 bool OpenStream(shared_ptr<ofstream> stream, const string &filename);
313 ///Open the relevant text files related to a particular run
314 int OpenRunFile(RunNumberType& run);
315 ///add a new run number
316 void AddNewRunNumber(int64_t newRun, Time time);
317 std::vector<int64_t> previousRunNumbers;
318 ///removes the oldest run number, and close the relevant files.
319 void RemoveOldestRunNumber();
320 ///retrieves the size of a file
321 off_t GetFileSize(const string&);
322 ///Get the digits of year, month and day for filenames and paths
323 void GetYearMonthDayForFiles(unsigned short& year, unsigned short& month, unsigned short& day);
324 ///Appends the relevant year month day to a given path
325 void AppendYearMonthDaytoPath(string& path);
326 ///Form the files path
327 string CompileFileNameWithPath(const string &path, const string &service, const string & extension);
328 ///Form the file names only
329 string CompileFileName(const string& service, const string& extension, const Time& time=Time()) const;
330 ///Check whether service is in black and/or white list
331 bool ShouldSubscribe(const string& server, const string& service);
332 ///Subscribe to a given server and service
333// EventImp& SubscribeTo(const string& server, const string& service);
334 ///Open a text file and checks for ofstream status
335 bool OpenTextFile(ofstream& stream, const string& name);
336 ///Checks if the input osftream is in error state, and if so close it.
337 bool CheckForOfstreamError(ofstream& out, bool isDailyStream);
338 ///Goes to Write error states
339 void GoToRunWriteErrorState();
340 void GoToNightlyWriteErrorState();
341 ///Checks if a given path exist
342 bool DoesPathExist(string path);
343 ///Check if old run numbers can be trimmed, and if so, do it
344 void TrimOldRunNumbers();
345 ///Create a given directory
346 bool CreateDirectory(string path);
347 /***************************************************
348 * INHERITED FROM DimServiceInfoList
349 ***************************************************/
350 ///Add a new server subscription
351 void AddServer(const string& server);
352 ///Add a new service subscription
353 void AddService(const Service& svc);
354 ///Remove a given service subscription
355 //FIXME unused
356 void RemoveService(const string, const string, bool);
357 ///Remove all the services associated with a given server
358 //FIXME unused
359 void RemoveAllServices(const string&);
360 ///pointer to the dim's subscription that should distribute the run numbers.
361 //DIM_REPLACE
362 //DimInfo* fRunNumberService;
363 unsigned int fRunNumberService;
364 /***************************************************
365 * Overwritten from MessageImp
366 ***************************************************/
367 vector<string> backLogBuffer;
368 bool shouldBackLog;
369 bool fShouldAutoStart;
370 bool fAutoStarted;
371
372 //Current day variable. Used to close nightly files when night changes
373 int fCurrentDay;
374 Time lastFlush;
375
376 DimDnsServiceList fDimList;
377 vector<DimDescriptions*> fServerDescriptionsList;
378
379 //counter for keeping tracker of services
380 unsigned int servicesCounter;
381public:
382 int Write(const Time &time, const std::string &txt, int qos=kMessage);
383
384}; //DataLogger
385
386
387/**
388 * @brief the two methods below were copied from StateMachineDimControl.cc
389 *
390 */
391int DataLogger::HandleDescriptions(DimDescriptions* desc)
392{
393 fMutex.lock();
394 for (auto it=desc->descriptions.begin(); it != desc->descriptions.end(); it++) {
395 if (fDebugIsOn)
396 {
397 Debug("Adding description for service: " + it->front().name);
398 }
399 fServiceDescriptionList[it->front().name].assign(it->begin(), it->end());
400 }
401 fMutex.unlock();
402
403 return GetCurrentState();
404}
405vector<Description> DataLogger::GetDescription(const string& server, const string& service)
406{
407 const lock_guard<mutex> guard(fMutex);
408 const auto it = fServiceDescriptionList.find(server+"/"+service);
409 return it==fServiceDescriptionList.end()?vector<Description>():it->second;
410}
411// --------------------------------------------------------------------------
412//
413//! Overwritten write function. This way we directly log the datalogger's messages, without going through dim's dns,
414//! thus increasing robustness.
415//! @param time: see MessageImp class param
416//! @param txt: see MessageImp class param
417//! @param qos: see MessageImp class param
418//! @return see MessageImp class param
419//
420int DataLogger::Write(const Time&time, const std::string& txt, int qos)
421{
422 ostringstream ss;
423 ss << "datalogger: " << txt;
424 if (fNightlyLogFile.is_open())
425 {
426 MessageImp mimp(fNightlyLogFile);
427 mimp.Write(time, ss.str(), qos);
428 }
429 else if (shouldBackLog)
430 {
431 ostringstream str;
432 MessageImp mimp(str);
433 mimp.Write(time, ss.str(), qos);
434 backLogBuffer.push_back(str.str());
435 }
436 return StateMachineDim::Write(time, ss.str(), qos);
437}
438// --------------------------------------------------------------------------
439//
440//! Check if a given path exists
441//! @param path the path to be checked
442//! @return whether or not the creation has been successfull
443//
444bool DataLogger::CreateDirectory(string path)
445{
446 try
447 {
448 DimWriteStatistics::CreateDirectory(path);
449 return true;
450 }
451 catch (const runtime_error &e)
452 {
453 Error(e.what());
454 return false;
455 }
456}
457// --------------------------------------------------------------------------
458//
459//! Check if a given path exists
460//! @param path the path to be checked
461//! @return whether or not the given path exists
462//
463bool DataLogger::DoesPathExist(string path)
464{
465 return DimWriteStatistics::DoesPathExist(path, *this);
466}
467
468
469void DataLogger::AddServer(const string& server)
470{
471 Info("Got request to add server " + server );
472 if (server != "DIS_DNS")
473 {
474 DimDescriptions* d = new DimDescriptions(server);
475 d->SetCallbackDescriptions(bind(&DataLogger::HandleDescriptions, this, d));
476 d->Subscribe(*this);
477 fServerDescriptionsList.push_back(d);
478 }
479
480}
481
482// --------------------------------------------------------------------------
483//
484//! Add a new service subscription
485//! @param server the server for which the subscription should be created
486//! @param service the service for which the subscription should be created
487//! @param isCmd whether this is a Dim Command or not. Commands are not logged
488//
489void DataLogger::AddService(const Service& svc)
490{
491 const string& server = svc.server;
492 const string& service = svc.service;
493 const bool isCmd = svc.iscmd;
494
495 //dataLogger does not subscribe to commands
496 if (isCmd)
497 return;
498
499 Info("Got request to add service: "+server+"/"+service);
500
501 //check the given subscription against black and white lists
502 if (!ShouldSubscribe(server, service))
503 return;
504
505 map<string, SubscriptionType> &list = fServiceSubscriptions[server];
506
507 if (list.find(service) != list.end())
508 {
509 // Error("Service " + server + "/" + service + " is already in the dataLogger's list... ignoring update.");
510 return;
511 }
512 //DIM_REPLACE
513// list[service].dimInfo.reset(SubscribeTo(server, service));
514 if (fDebugIsOn)
515 Debug("Subscribing to service "+server+"/"+service);
516 Subscribe(server + "/" + service)
517 (bind(&DataLogger::infoCallback, this, placeholders::_1, servicesCounter));
518 list[service].server = server;
519 list[service].service = service;
520 list[service].index = servicesCounter;
521 fNumSubAndFitsData.numSubscriptions++;
522 //check if this is the run numbers service
523 if ((server == "FAD_CONTROL") && (service == "START_RUN"))
524 fRunNumberService = servicesCounter;
525 servicesCounter++;
526 Info("Added subscription to " + server + "/" + service);
527}
528// --------------------------------------------------------------------------
529//
530//! Remove a given service subscription
531//! @param server the server for which the subscription should be removed
532//! @param service the service that should be removed
533//! @param isCmd whether or not this is a command
534//
535void DataLogger::RemoveService(string server, string service, bool isCmd)
536{
537
538 Info("Got request to remove service: "+server+"/"+service);
539 if (fDestructing)//this function is called by the super class, after the destructor has deleted its own subscriptions
540 return;
541//FIXME unused
542 return;
543
544 if (isCmd)
545 return;
546
547 if (fServiceSubscriptions.find(server) == fServiceSubscriptions.end())
548 {
549 Error("Request to remove service "+service+" from server "+server+", but service not found.");
550 return;
551 }
552
553 if (fServiceSubscriptions[server].erase(service) != 1)
554 {
555 //check the given subscription against black and white lists
556 if (!ShouldSubscribe(server, service))
557 return;
558
559 Error("Subscription "+server+"/"+service+" could not be removed as it is not present");
560 return;
561 }
562 fNumSubAndFitsData.numSubscriptions--;
563
564 if ((server == "FAD_CONTROL") && (service == "START_RUN"))
565 fRunNumberService = 0;
566
567 Info("Removed subscription to " + server + "/" + service);
568}
569// --------------------------------------------------------------------------
570//
571//! Remove all the services associated with a given server
572//! @param server the server for which all the services should be removed
573//
574void DataLogger::RemoveAllServices(const string& server)
575{
576 Info("Got request for removing all services from: "+server);
577 if (fServiceSubscriptions.find(server)==fServiceSubscriptions.end())
578 {
579 Warn("Request to remove all services, but corresponding server " + server + " not found.");
580 return;
581 }
582//FIXME unused
583 return;
584 fNumSubAndFitsData.numSubscriptions -= fServiceSubscriptions[server].size();
585
586 fServiceSubscriptions[server].clear();
587 fServiceSubscriptions.erase(server);
588
589 if (server == "FAD_CONTROL")
590 fRunNumberService = 0;
591
592 if (fDebugIsOn)
593 Debug("Removed all subscriptions to " + server + "/");
594}
595
596// --------------------------------------------------------------------------
597//
598//! Checks if the given ofstream is in error state and if so, close it
599//! @param out the ofstream that should be checked
600//
601bool DataLogger::CheckForOfstreamError(ofstream& out, bool isDailyStream)
602{
603 if (out.good())
604 return true;
605
606 Error("An error occured while writing to a text file. Closing it");
607 if (out.is_open())
608 out.close();
609 if (isDailyStream)
610 GoToNightlyWriteErrorState();
611 else
612 GoToRunWriteErrorState();
613
614 return false;
615}
616
617bool DataLogger::OpenStreamImp(ofstream &stream, const string &filename, bool mightbeopen)
618{
619 if (stream.is_open())
620 {
621 if (!mightbeopen)
622 Error(filename+" was already open when trying to open it.");
623 return mightbeopen;
624 }
625
626 errno = 0;
627 stream.open(filename.c_str(), ios_base::out | ios_base::app);
628 if (!stream /*|| errno!=0*/)
629 {
630 ostringstream str;
631 str << "ofstream::open() failed for '" << filename << "': " << strerror(errno) << " [errno=" << errno << "]";
632 Error(str);
633 return false;
634 }
635
636 if (!stream.is_open())
637 {
638 Error("File "+filename+" not open as it ought to be.");
639 return false;
640 }
641
642 Info("Opened: "+filename);
643
644 return true;
645}
646
647bool DataLogger::OpenStream(shared_ptr<ofstream> stream, const string &filename)
648{
649 return OpenStreamImp(*stream, filename, false);
650}
651
652// --------------------------------------------------------------------------
653//
654//! Open a text file and checks for error code
655//! @param stream the ofstream for which the file should be opened
656//! @name the file name
657//
658bool DataLogger::OpenTextFile(ofstream& stream, const string& name)
659{
660 return OpenStreamImp(stream, name, true);
661}
662
663// --------------------------------------------------------------------------
664//
665//! Create a new dim subscription to a given server and service
666//! @param server the server name
667//! @param service the service name
668//
669/*EventImp& DataLogger::SubscribeTo(const string& server, const string& service)
670{
671
672 //DIM_REPLACE
673 //return new DimStampedInfo((server + "/" + service).c_str(), (void*)NULL, 0, this);
674 EventImp& newSubscription = Subscribe(server + "/" + service);
675 newSubscription.bind(&infoHandler, this, placeholders::_1);
676 return newSubscription;
677}*/
678// --------------------------------------------------------------------------
679//
680//! Check whether a service should be subscribed to, based on the black/white list entries
681//! @param server the server name associated with the service being checked
682//! @param service the service name associated with the service being checked
683//
684bool DataLogger::ShouldSubscribe(const string& server, const string& service)
685{
686 if ((fBlackList.find(server + "/") != fBlackList.end()) ||
687 (fBlackList.find(server + "/" + service) != fBlackList.end()) ||
688 (fBlackList.find("/" + service) != fBlackList.end()))
689 {
690 if (fWhiteList.size()>0 &&
691 (fWhiteList.find(server + "/" + service) != fWhiteList.end()))
692 {
693 if (fDebugIsOn)
694 Debug("White list saved service " + server + "/" + service + " from blacklisting");
695 return true;
696 }
697 if (fDebugIsOn)
698 Debug("Blacklist banned service " + server + "/" + service);
699 return false;
700 }
701 return true;
702}
703// --------------------------------------------------------------------------
704//
705//! Compiles a file name
706//! @param path the base path where to put the file
707//! @param time the time at which the file is created
708//! @param service the service name, if any
709//! @param extension the extension to add, if any
710//
711string DataLogger::CompileFileName(const string& service, const string& extension, const Time& time) const
712{
713 ostringstream str;
714
715 const Time ftime(time);//removed this as already done by nightAsInt: -boost::posix_time::hours(12));
716 str << ftime.NightAsInt();
717
718 if (!service.empty())
719 str << '.' << service;
720
721 if (!extension.empty())
722 str << "." << extension;
723
724 return str.str();
725}
726
727string DataLogger::CompileFileNameWithPath(const string& path, const string& service, const string& extension)
728{
729 ostringstream str;
730
731 const Time time;
732
733 //calculate time suitable for naming files.
734 const Time ftime = time-boost::posix_time::hours(12);
735
736 //output it
737 str << path << ftime.GetAsStr("/%Y/%m/%d");
738
739 //check if target directory exist
740 if (!DoesPathExist(str.str()))
741 CreateDirectory(str.str());
742
743 str << '/' << CompileFileName(service, extension, time);
744
745 return str.str();
746
747
748}
749
750// --------------------------------------------------------------------------
751//
752//!retrieves the size on disk of a file
753//! @param fileName the full file name for which the size on disk should be retrieved
754//! @return the size of the file on disk, in bytes. 0 if the file does not exist or if an error occured
755//
756off_t DataLogger::GetFileSize(const string& fileName)
757{
758 return DimWriteStatistics::GetFileSizeOnDisk(fileName, *this);
759}
760
761// --------------------------------------------------------------------------
762//
763//! Removes the oldest run number and closes the fits files that should be closed
764//! Also creates the fits grouping file
765//
766void DataLogger::RemoveOldestRunNumber()
767{
768 if (fDebugIsOn)
769 {
770 ostringstream str;
771 str << "Removing run number " << fRunNumber.front().runNumber;
772 Debug(str);
773 }
774 //remove the entry
775 fRunNumber.pop_front();
776}
777
778// --------------------------------------------------------------------------
779//
780//! Default constructor. The name of the machine is given DATA_LOGGER
781//! and the state is set to kSM_Ready at the end of the function.
782//
783//!Setup the allows states, configs and transitions for the data logger
784//
785DataLogger::DataLogger(ostream &out) : StateMachineDim(out, "DATA_LOGGER"),
786 fFilesStats("DATA_LOGGER", *this)
787{
788 shouldBackLog = true;
789
790 servicesCounter=1;
791
792 //initialize member data
793 fFilePath = ".";
794
795 fDimList.Subscribe(*this);
796 fDimList.SetCallbackServerAdd(bind(&DataLogger::AddServer, this, placeholders::_1));
797 fDimList.SetCallbackServiceAdd(bind(&DataLogger::AddService, this, placeholders::_1));
798
799 //calculate time "centered" around noon instead of midnight
800 const Time timeNow;
801 const Time nowMinusTwelve = timeNow-boost::posix_time::hours(12);
802 fCurrentDay = nowMinusTwelve.M()*31 + nowMinusTwelve.D();//assume 31 days per month. we do not really care, only want unique number per day of the year
803 lastFlush = Time();
804
805 //Give a name to this machine's specific states
806 AddStateName(kSM_NightlyOpen, "NightlyFileOpen", "The summary files for the night are open.");
807 AddStateName(kSM_WaitingRun, "WaitForRun", "The summary files for the night are open and we wait for a run to be started.");
808 AddStateName(kSM_Logging, "Logging", "The summary files for the night and the files for a single run are open.");
809 AddStateName(kSM_BadFolder, "ErrInvalidFolder", "The folder for the files is not invalid.");
810 AddStateName(kSM_DailyWriteError, "ErrDailyWrite", "An error occured while writing to a daily (and run) file.");
811 AddStateName(kSM_RunWriteError, "ErrRunWrite", "An error occured while writing to a run file.");
812
813 // Add the possible transitions for this machine
814 AddEvent("START", kSM_Ready, kSM_BadFolder)
815 (bind(&DataLogger::Start, this))
816 ("Start the nightly logging. Nightly file location must be specified already");
817
818 AddEvent("STOP", kSM_NightlyOpen, kSM_WaitingRun, kSM_Logging, kSM_DailyWriteError, kSM_RunWriteError)
819 (bind(&DataLogger::GoToReady, this))
820 ("Stop all data logging, close all files.");
821
822 AddEvent("RESET", kSM_Error, kSM_BadFolder, kSM_DailyWriteError, kSM_RunWriteError)
823 (bind(&DataLogger::GoToReady, this))
824 ("Transition to exit error states. Closes the any open file.");
825
826 AddEvent("START_RUN_LOGGING", /*kSM_Logging,*/ kSM_NightlyOpen, kSM_Ready)
827 (bind(&DataLogger::NightlyToWaitRun, this))
828 ("Go to waiting for run number state. In this state with any received run-number a new file is opened.");
829
830 AddEvent("STOP_RUN_LOGGING", kSM_WaitingRun, kSM_Logging)
831 (bind(&DataLogger::BackToNightlyOpen, this))
832 ("Go from the wait for run to nightly open state.");
833
834 // Provide a print command
835 AddEvent("PRINT_INFO")
836 (bind(&DataLogger::PrintState, this, placeholders::_1))
837 ("Print information about the internal status of the data logger.");
838
839 OpenFileToDim fToDim;
840 fToDim.code = 0;
841 fToDim.fileName[0] = '\0';
842
843 fOpenedNightlyFiles = new DimDescribedService(GetName() + "/FILENAME_NIGHTLY", "I:1;C", fToDim,
844 "Path and base name used for the nightly files."
845 "|Type[int]:type of open files (1=log, 2=rep, 4=fits)"
846 "|Name[string]:path and base file name");
847
848 fOpenedRunFiles = new DimDescribedService(GetName() + "/FILENAME_RUN", "I:1;C", fToDim,
849 "Path and base name used for the run files."
850 "|Type[int]:type of open files (1=log, 2=rep, 4=fits)"
851 "|Name[string]:path and base file name");
852
853 fNumSubAndFitsData.numSubscriptions = 0;
854 fNumSubAndFitsData.numOpenFits = 0;
855 fNumSubAndFits = new DimDescribedService(GetName() + "/NUM_SUBS", "I:2", fNumSubAndFitsData,
856 "Num. open files + num. subscribed services"
857 "|NSubAndOpenFiles[int]:Num. of subs and open files");
858
859 //services parameters
860 fDebugIsOn = false;
861 fOpenedFilesIsOn = true;
862 fNumSubAndFitsIsOn = true;
863
864 // provide services control commands
865 AddEvent("SET_DEBUG_MODE", "B:1", kSM_NightlyOpen, kSM_Logging, kSM_WaitingRun, kSM_Ready)
866 (bind(&DataLogger::SetDebugOnOff, this, placeholders::_1))
867 ("Switch debug mode on or off. Debug mode prints information about every service written to a file."
868 "|Enable[bool]:Enable of disable debug mode (yes/no).");
869
870 AddEvent("SET_STATISTICS_UPDATE_INTERVAL", "S:1", kSM_NightlyOpen, kSM_Logging, kSM_WaitingRun, kSM_Ready)
871 (bind(&DataLogger::SetStatsPeriod, this, placeholders::_1))
872 ("Interval in which the data-logger statistics service (STATS) is updated."
873 "|Interval[ms]:Value in milliseconds (<=0: no update).");
874
875 AddEvent("ENABLE_FILENAME_SERVICES", "B:1", kSM_NightlyOpen, kSM_Logging, kSM_WaitingRun, kSM_Ready)
876 (bind(&DataLogger::SetOpenedFilesOnOff ,this, placeholders::_1))
877 ("Switch service which distributes information about the open files on or off."
878 "|Enable[bool]:Enable of disable filename services (yes/no).");
879
880 AddEvent("ENABLE_NUMSUBS_SERVICE", "B:1", kSM_NightlyOpen, kSM_Logging, kSM_WaitingRun, kSM_Ready)
881 (bind(&DataLogger::SetNumSubsAndFitsOnOff, this, placeholders::_1))
882 ("Switch the service which distributes information about the number of subscriptions and open files on or off."
883 "|Enable[bool]:Enable of disable NUM_SUBS service (yes/no).");
884
885 AddEvent("SET_RUN_TIMEOUT", "L:1", kSM_Ready, kSM_NightlyOpen, kSM_Logging, kSM_WaitingRun)
886 (bind(&DataLogger::SetRunTimeoutDelay, this, placeholders::_1))
887 ("Set the timeout delay for old run numbers."
888 "|timeout[min]:Time out in minutes after which files for expired runs are closed.");
889
890 fDestructing = false;
891
892 fPreviousOldRunNumberCheck = Time().Mjd();
893
894 fDailyFileDayChangedAlready = true;
895 fRunNumberTimeout = 60000; //default run-timeout set to 1 minute
896 fRunNumber.push_back(RunNumberType());
897 fRunNumber.back().runNumber = -1;
898 fRunNumber.back().time = Time();
899 NotifyOpenedFile("", 0, fOpenedNightlyFiles);
900 NotifyOpenedFile("", 0, fOpenedRunFiles);
901
902 fRunNumberService = 0;
903
904 fShouldAutoStart = false;
905 fAutoStarted = false;
906
907
908 if(fDebugIsOn)
909 {
910 Debug("DataLogger Init Done.");
911 }
912}
913
914// --------------------------------------------------------------------------
915//
916//! Destructor
917//
918DataLogger::~DataLogger()
919{
920 if (fDebugIsOn)
921 Debug("DataLogger destruction starts");
922
923 //this boolean should not be required anymore
924 fDestructing = true;
925
926 //now clear the services subscriptions
927 dim_lock();
928 fServiceSubscriptions.clear();
929 dim_unlock();
930
931 //clear any remaining run number (should remain only one)
932 while (fRunNumber.size() > 0)
933 {
934 RemoveOldestRunNumber();
935 }
936 //go to the ready state. i.e. close all files, run-wise first
937 GoToReady();
938
939 Info("Will soon close the daily log file");
940
941 delete fOpenedNightlyFiles;
942 delete fOpenedRunFiles;
943 delete fNumSubAndFits;
944
945 if (fNightlyLogFile.is_open())//this file is the only one that has not been closed by GoToReady
946 {
947 fNightlyLogFile << endl;
948 fNightlyLogFile.close();
949 }
950
951 for (auto it=fServerDescriptionsList.begin(); it!= fServerDescriptionsList.end(); it++)
952 delete *it;
953
954 if (fDebugIsOn)
955 Debug("DataLogger desctruction ends");
956}
957
958// --------------------------------------------------------------------------
959//
960//! checks if old run numbers should be trimmed and if so, do it
961//
962void DataLogger::TrimOldRunNumbers()
963{
964 const Time cTime = Time();
965
966 if (cTime - fPreviousOldRunNumberCheck < boost::posix_time::milliseconds(fRunNumberTimeout))
967 return;
968
969 while (fRunNumber.size() > 1 && (cTime - fRunNumber.back().time) > boost::posix_time::milliseconds(fRunNumberTimeout))
970 {
971 RemoveOldestRunNumber();
972 }
973 fPreviousOldRunNumberCheck = cTime;
974}
975// --------------------------------------------------------------------------
976//
977//! Inherited from DimInfo. Handles all the Infos to which we subscribed, and log them
978//
979int DataLogger::infoCallback(const EventImp& evt, unsigned int subIndex)
980{
981// if (fDebugIsOn)
982// {
983// ostringstream str;
984// str << "Got infoCallback called with service index= " << subIndex;
985// Debug(str.str());
986// }
987 if ((GetCurrentState() == kSM_Ready) && (!fAutoStarted) && fShouldAutoStart)
988 {
989 fAutoStarted = true;
990 SetCurrentState(Start());
991 }
992 else
993 {
994 if (GetCurrentState() > kSM_Ready)
995 fAutoStarted = true;
996 }
997
998
999 //check if the service pointer corresponds to something that we subscribed to
1000 //this is a fix for a bug that provides bad Infos when a server starts
1001 bool found = false;
1002 SubscriptionsListType::iterator x;
1003 map<string, SubscriptionType>::iterator y;
1004 for (x=fServiceSubscriptions.begin(); x != fServiceSubscriptions.end(); x++)
1005 {//find current service is subscriptions
1006 //Edit: this should be useless now... remove it sometimes ?
1007 for (y=x->second.begin(); y!=x->second.end();y++)
1008 if (y->second.index == subIndex)
1009 {
1010 found = true;
1011 break;
1012 }
1013 if (found)
1014 break;
1015 }
1016 if (!found)
1017 return GetCurrentState();
1018
1019 if (evt.GetSize() == 0)
1020 return GetCurrentState();
1021 if (evt.GetFormat() == "")
1022 return GetCurrentState();
1023
1024// cout.precision(20);
1025// cout << "Orig timestamp: " << Time(I->getTimestamp(), I->getTimestampMillisecs()*1000).Mjd() << endl;
1026 // FIXME: Here we have to check if we have received the
1027 // service with the run-number.
1028 // CheckForRunNumber(I); has been removed because we have to
1029 // subscribe to this service anyway and hence we have the pointer
1030 // (no need to check for the name)
1031 CheckForRunNumber(evt, subIndex);
1032
1033 Report(evt, y->second);
1034
1035 //remove old run numbers
1036 TrimOldRunNumbers();
1037
1038 return GetCurrentState();
1039}
1040
1041// --------------------------------------------------------------------------
1042//
1043//! Add a new active run number
1044//! @param newRun the new run number
1045//! @param time the time at which the new run number was issued
1046//
1047void DataLogger::AddNewRunNumber(int64_t newRun, Time time)
1048{
1049
1050 if (newRun > 0xffffffff)
1051 {
1052 Error("New run number too large, out of range. Ignoring.");
1053 return;
1054 }
1055 for (std::vector<int64_t>::const_iterator it=previousRunNumbers.begin(); it != previousRunNumbers.end(); it++)
1056 {
1057 if (*it == newRun)
1058 {
1059 Error("Newly provided run number has already been used (or is still in use). Going to error state");
1060 SetCurrentState(kSM_BadFolder);
1061 return;
1062 }
1063 }
1064 if (fDebugIsOn)
1065 {
1066 ostringstream str;
1067 str << "Adding new run number " << newRun << " issued at " << time;
1068 Debug(str);
1069 }
1070 //Add new run number to run number list
1071 fRunNumber.push_back(RunNumberType());
1072 fRunNumber.back().runNumber = int32_t(newRun);
1073 fRunNumber.back().time = time;
1074
1075 ostringstream str;
1076 str << "The new run number is: " << fRunNumber.back().runNumber;
1077 Message(str);
1078
1079 if (GetCurrentState() != kSM_Logging && GetCurrentState() != kSM_WaitingRun )
1080 return;
1081
1082 if (newRun > 0 && GetCurrentState() == kSM_WaitingRun)
1083 SetCurrentState(kSM_Logging);
1084 if (newRun < 0 && GetCurrentState() == kSM_Logging)
1085 SetCurrentState(kSM_WaitingRun);
1086}
1087// --------------------------------------------------------------------------
1088//
1089//! Checks whether or not the current info is a run number.
1090//! If so, then remember it. A run number is required to open the run-log file
1091//! @param I
1092//! the current DimInfo
1093//
1094void DataLogger::CheckForRunNumber(const EventImp& evt, unsigned int index)
1095{
1096 if (index != fRunNumberService)
1097 return;
1098// int64_t newRun = reinterpret_cast<const uint64_t*>(evt.GetData())[0];
1099 AddNewRunNumber(evt.GetXtra(), evt.GetTime());
1100}
1101
1102// --------------------------------------------------------------------------
1103//
1104//! write infos to log files.
1105//! @param I
1106//! The current DimInfo
1107//! @param sub
1108//! The dataLogger's subscription corresponding to this DimInfo
1109//
1110void DataLogger::Report(const EventImp& evt, SubscriptionType& sub)
1111{
1112 const string fmt(evt.GetFormat());
1113
1114 const bool isItaReport = fmt!="C";
1115
1116 if (!fNightlyLogFile.is_open())
1117 return;
1118
1119 if (fDebugIsOn && string(evt.GetName())!="DATA_LOGGER/MESSAGE")
1120 {
1121 ostringstream str;
1122 str << "Logging " << evt.GetName() << " [" << evt.GetFormat() << "] (" << evt.GetSize() << ")";
1123 Debug(str);
1124 }
1125
1126 //
1127 // Check whether we should close and reopen daily text files or not
1128 // calculate time "centered" around noon instead of midnight
1129 // if number of days has changed, then files should be closed and reopenned.
1130 const Time timeNow;
1131 const Time nowMinusTwelve = timeNow-boost::posix_time::hours(12);
1132 int newDayNumber = nowMinusTwelve.M()*31 + nowMinusTwelve.D();//assume 31 days per month. we do not really care, only want unique number per day of the year
1133
1134 //also check if we should flush the nightly files
1135 if (lastFlush < timeNow-boost::posix_time::minutes(1))
1136 {
1137 lastFlush = timeNow;
1138 SubscriptionsListType::iterator x;
1139 map<string, SubscriptionType>::iterator y;
1140 for (x=fServiceSubscriptions.begin(); x != fServiceSubscriptions.end(); x++)
1141 {//find current service is subscriptions
1142 for (y=x->second.begin(); y!=x->second.end();y++)
1143 if (y->second.nightlyFile.IsOpen())
1144 {
1145 y->second.nightlyFile.Flush();
1146 }
1147 }
1148 if (fDebugIsOn)
1149 Debug("Just flushed nightly fits files to the disk");
1150 }
1151
1152 if (newDayNumber != fCurrentDay)
1153 {
1154 fCurrentDay = newDayNumber;
1155 //crawl through the subcriptions and close any open nightly file
1156 SubscriptionsListType::iterator x;
1157 map<string, SubscriptionType>::iterator y;
1158 for (x=fServiceSubscriptions.begin(); x != fServiceSubscriptions.end(); x++)
1159 {//find current service is subscriptions
1160 for (y=x->second.begin(); y!=x->second.end();y++)
1161 if (y->second.nightlyFile.IsOpen())
1162 {
1163 y->second.nightlyFile.Close();
1164 }
1165 }
1166
1167 if (fDebugIsOn)
1168 Debug("Day have changed! Closing and reopening nightly files");
1169
1170 fNightlyLogFile << endl;
1171 fNightlyLogFile.close();
1172 fNightlyReportFile.close();
1173
1174 Info("Closed: "+fFullNightlyLogFileName);
1175 Info("Closed: "+fFullNightlyReportFileName);
1176
1177 fFullNightlyLogFileName = CompileFileNameWithPath(fFilePath, "", "log");
1178 if (!OpenTextFile(fNightlyLogFile, fFullNightlyLogFileName))
1179 {
1180 GoToReady();
1181 SetCurrentState(kSM_BadFolder);
1182 return;
1183 }
1184 fNightlyLogFile << endl;
1185
1186 fFullNightlyReportFileName = CompileFileNameWithPath(fFilePath, "", "rep");
1187 if (!OpenTextFile(fNightlyReportFile, fFullNightlyReportFileName))
1188 {
1189 GoToReady();
1190 SetCurrentState(kSM_BadFolder);
1191 return;
1192 }
1193 }
1194 //create the converter for that service
1195 if (!sub.fConv)
1196 {
1197 sub.fConv = shared_ptr<Converter>(new Converter(Out(), evt.GetFormat()));
1198 if (!sub.fConv->valid())
1199 {
1200 ostringstream str;
1201 str << "Couldn't properly parse the format... service " << evt.GetName() << " ignored.";
1202 Error(str);
1203 return;
1204 }
1205 }
1206 //construct the header
1207 ostringstream header;
1208 const Time cTime(evt.GetTime());
1209 fQuality = evt.GetQoS();
1210 //I had strange surprises with the quality from Dim before. Double check that the value is indeed valid.
1211 if (fQuality != kMessage &&
1212 fQuality != kInfo &&
1213 fQuality != kWarn &&
1214 fQuality != kError &&
1215 fQuality != kFatal &&
1216 fQuality != kComment &&
1217 fQuality != kDebug)
1218 fQuality = kError;
1219 fMjD = cTime.Mjd() ? cTime.Mjd()-40587 : 0;
1220
1221 if (isItaReport)
1222 {
1223 //write text header
1224 header << sub.server << "_" << sub.service << " " << fQuality << " ";
1225 header << evt.GetTime() << " ";
1226
1227 string text;
1228 try
1229 {
1230 text = sub.fConv->GetString(evt.GetData(), evt.GetSize());
1231 }
1232 catch (const runtime_error &e)
1233 {
1234 ostringstream str;
1235 str << "Parsing service " << evt.GetName();
1236 str << " failed: " << e.what() << " removing the subscription for now.";
1237 Error(str);
1238 //remove this subscription from the list.
1239 //because these operators use references to elements, and because they're supposed here to erase these objects on the way, I'm not too sure... so duplicate the names !
1240 RemoveService(sub.server, sub.service, false);
1241 return;
1242 }
1243
1244 if (text.empty())
1245 {
1246 ostringstream str;
1247 str << "Service " << evt.GetName() << " sent an empty string";
1248 Info(str);
1249 return;
1250 }
1251 //replace bizarre characters by white space
1252 replace(text.begin(), text.end(), '\n', '\\');
1253 replace_if(text.begin(), text.end(), ptr_fun<int, int>(&iscntrl), ' ');
1254
1255 //write entry to Nightly report
1256 if (fNightlyReportFile.is_open())
1257 {
1258 fNightlyReportFile << header.str() << text << endl;
1259 if (!CheckForOfstreamError(fNightlyReportFile, true))
1260 return;
1261 }
1262#ifdef HAVE_FITS
1263 //check if the last received event was before noon and if current one is after noon.
1264 //if so, close the file so that it gets reopened.
1265 sub.lastReceivedEvent = cTime;
1266 if (!sub.nightlyFile.IsOpen())
1267 if (GetCurrentState() != kSM_Ready)
1268 OpenFITSFiles(sub, evt);
1269 WriteToFITS(sub, evt.GetData());
1270#endif
1271 }
1272 else
1273 {//write entry to Nightly log
1274 vector<string> strings;
1275 try
1276 {
1277 strings = sub.fConv->ToStrings(evt.GetData());
1278 }
1279 catch (const runtime_error &e)
1280 {
1281 ostringstream str;
1282 str << "Parsing service " << evt.GetName();
1283 str << " failed: " << e.what() << " removing the subscription for now.";
1284 Error(str);
1285 //remove this subscription from the list.
1286 //because these operators use references to elements, and because they're supposed here to erase these objects on the way, I'm not too sure... so duplicate the names !
1287 RemoveService(sub.server, sub.service, false);
1288 return;
1289 }
1290 if (strings.size() > 1)
1291 {
1292 ostringstream err;
1293 err << "There was more than one string message in service " << evt.GetName() << " going to fatal error state";
1294 Error(err.str());
1295 }
1296 ostringstream msg;
1297 msg << sub.server << "_" << sub.service << ": " << strings[0];
1298
1299 if (fNightlyLogFile.is_open())
1300 {
1301 MessageImp(fNightlyLogFile).Write(cTime, msg.str().c_str(), fQuality);
1302 if (!CheckForOfstreamError(fNightlyLogFile, true))
1303 return;
1304 }
1305
1306 sub.lastReceivedEvent = cTime;
1307 if (!sub.nightlyFile.IsOpen())
1308 if (GetCurrentState() != kSM_Ready)
1309 OpenFITSFiles(sub, evt);
1310 WriteToFITS(sub, evt.GetData());
1311 }
1312
1313}
1314
1315// --------------------------------------------------------------------------
1316//
1317//! print the dataLogger's current state. invoked by the PRINT command
1318//! @param evt
1319//! the current event. Not used by the method
1320//! @returns
1321//! the new state. Which, in that case, is the current state
1322//!
1323int DataLogger::PrintState(const Event& )
1324{
1325 Message("------------------------------------------");
1326 Message("------- DATA LOGGER CURRENT STATE --------");
1327 Message("------------------------------------------");
1328
1329 //print the path configuration
1330#if BOOST_VERSION < 104600
1331 Message("File path: " + boost::filesystem::system_complete(boost::filesystem::path(fFilePath)).directory_string());
1332#else
1333 Message("File path: " + boost::filesystem::system_complete(boost::filesystem::path(fFilePath)).parent_path().string());
1334#endif
1335
1336 //print active run numbers
1337 ostringstream str;
1338 //timeout value
1339 str << "Timeout delay for old run numbers: " << fRunNumberTimeout << " ms";
1340 Message(str);
1341 str.str("");
1342 str << "Active Run Numbers:";
1343 for (list<RunNumberType>::const_iterator it=fRunNumber.begin(); it!=fRunNumber.end(); it++)
1344 str << " " << it->runNumber;
1345 if (fRunNumber.size()==0)
1346 str << " <none>";
1347 Message(str);
1348
1349 //print all the open files.
1350 Message("------------ OPEN FILES ----------------");
1351 if (fNightlyLogFile.is_open())
1352 Message("Nightly log-file: "+fFullNightlyLogFileName);
1353
1354 if (fNightlyReportFile.is_open())
1355 Message("Nightly report-file: "+fFullNightlyReportFileName);
1356
1357 const DimWriteStatistics::Stats statVar = fFilesStats.GetTotalSizeWritten();
1358 // /*const bool statWarning =*/ calculateTotalSizeWritten(statVar, true);
1359#ifdef HAVE_FITS
1360 str.str("");
1361 str << "Number of open FITS files: " << fNumSubAndFitsData.numOpenFits;
1362 Message(str);
1363 // FIXME: Print list of open FITS files
1364#else
1365 Message("FITS output disabled at compilation");
1366#endif
1367 Message("----------------- STATS ------------------");
1368 if (fFilesStats.GetUpdateInterval()>0)
1369 {
1370 str.str("");
1371 str << "Statistics are updated every " << fFilesStats.GetUpdateInterval() << " ms";
1372 Message(str);
1373 }
1374 else
1375 Message("Statistics updates are currently disabled.");
1376 str.str("");
1377 str << "Total Size written: " << statVar.sizeWritten/1000 << " kB";
1378 Message(str);
1379 str.str("");
1380 str << "Disk free space: " << statVar.freeSpace/1000000 << " MB";
1381 Message(str);
1382
1383 Message("------------ DIM SUBSCRIPTIONS -----------");
1384 str.str("");
1385 str << "There are " << fNumSubAndFitsData.numSubscriptions << " active DIM subscriptions.";
1386 Message(str);
1387 for (map<const string, map<string, SubscriptionType> >::const_iterator it=fServiceSubscriptions.begin(); it!= fServiceSubscriptions.end();it++)
1388 {
1389 Message("Server "+it->first);
1390 for (map<string, SubscriptionType>::const_iterator it2=it->second.begin(); it2!=it->second.end(); it2++)
1391 Message(" -> "+it2->first);
1392 }
1393 Message("--------------- BLOCK LIST ---------------");
1394 for (set<string>::const_iterator it=fBlackList.begin(); it != fBlackList.end(); it++)
1395 Message(" -> "+*it);
1396 if (fBlackList.size()==0)
1397 Message(" <empty>");
1398
1399 Message("--------------- ALLOW LIST ---------------");
1400 for (set<string>::const_iterator it=fWhiteList.begin(); it != fWhiteList.end(); it++)
1401 Message(" -> "+*it);
1402 if (fWhiteList.size()==0)
1403 Message(" <empty>");
1404
1405 Message("-------------- GROUPING LIST -------------");
1406 Message("The following servers and/or services will");
1407 Message("be grouped into a single fits file:");
1408 for (set<string>::const_iterator it=fGrouping.begin(); it != fGrouping.end(); it++)
1409 Message(" -> "+*it);
1410 if (fGrouping.size()==0)
1411 Message(" <no grouping>");
1412
1413 Message("------------------------------------------");
1414 Message("-------- END OF DATA LOGGER STATE --------");
1415 Message("------------------------------------------");
1416
1417 return GetCurrentState();
1418}
1419
1420// --------------------------------------------------------------------------
1421//
1422//! turn debug mode on and off
1423//! @param evt
1424//! the current event. contains the instruction string: On, Off, on, off, ON, OFF, 0 or 1
1425//! @returns
1426//! the new state. Which, in that case, is the current state
1427//!
1428int DataLogger::SetDebugOnOff(const Event& evt)
1429{
1430 const bool backupDebug = fDebugIsOn;
1431
1432 fDebugIsOn = evt.GetBool();
1433
1434 if (fDebugIsOn == backupDebug)
1435 Message("Debug mode was already in the requested state.");
1436
1437 ostringstream str;
1438 str << "Debug mode is now " << fDebugIsOn;
1439 Message(str);
1440
1441 fFilesStats.SetDebugMode(fDebugIsOn);
1442
1443 return GetCurrentState();
1444}
1445// --------------------------------------------------------------------------
1446//
1447//! set the statistics update period duration. 0 disables the statistics
1448//! @param evt
1449//! the current event. contains the new duration.
1450//! @returns
1451//! the new state. Which, in that case, is the current state
1452//!
1453int DataLogger::SetStatsPeriod(const Event& evt)
1454{
1455 fFilesStats.SetUpdateInterval(evt.GetShort());
1456 return GetCurrentState();
1457}
1458// --------------------------------------------------------------------------
1459//
1460//! set the opened files service on or off.
1461//! @param evt
1462//! the current event. contains the instruction string. similar to setdebugonoff
1463//! @returns
1464//! the new state. Which, in that case, is the current state
1465//!
1466int DataLogger::SetOpenedFilesOnOff(const Event& evt)
1467{
1468 const bool backupOpened = fOpenedFilesIsOn;
1469
1470 fOpenedFilesIsOn = evt.GetBool();
1471
1472 if (fOpenedFilesIsOn == backupOpened)
1473 Message("Opened files service mode was already in the requested state.");
1474
1475 ostringstream str;
1476 str << "Opened files service mode is now " << fOpenedFilesIsOn;
1477 Message(str);
1478
1479 return GetCurrentState();
1480}
1481
1482// --------------------------------------------------------------------------
1483//
1484//! set the number of subscriptions and opened fits on and off
1485//! @param evt
1486//! the current event. contains the instruction string. similar to setdebugonoff
1487//! @returns
1488//! the new state. Which, in that case, is the current state
1489//!
1490int DataLogger::SetNumSubsAndFitsOnOff(const Event& evt)
1491{
1492 const bool backupSubs = fNumSubAndFitsIsOn;
1493
1494 fNumSubAndFitsIsOn = evt.GetBool();
1495
1496 if (fNumSubAndFitsIsOn == backupSubs)
1497 Message("Number of subscriptions service mode was already in the requested state");
1498
1499 ostringstream str;
1500 str << "Number of subscriptions service mode is now " << fNumSubAndFitsIsOn;
1501 Message(str);
1502
1503 return GetCurrentState();
1504}
1505// --------------------------------------------------------------------------
1506//
1507//! set the timeout delay for old run numbers
1508//! @param evt
1509//! the current event. contains the timeout delay long value
1510//! @returns
1511//! the new state. Which, in that case, is the current state
1512//!
1513int DataLogger::SetRunTimeoutDelay(const Event& evt)
1514{
1515 if (evt.GetUInt() == 0)
1516 {
1517 Error("Timeout delays for old run numbers must be greater than 0... ignored.");
1518 return GetCurrentState();
1519 }
1520
1521 if (fRunNumberTimeout == evt.GetUInt())
1522 Message("New timeout for old run numbers is same value as previous one.");
1523
1524 fRunNumberTimeout = evt.GetUInt();
1525
1526 ostringstream str;
1527 str << "Timeout delay for old run numbers is now " << fRunNumberTimeout << " ms";
1528 Message(str);
1529
1530 return GetCurrentState();
1531}
1532
1533// --------------------------------------------------------------------------
1534//
1535//! Notifies the DIM service that a particular file was opened
1536//! @ param name the base name of the opened file, i.e. without path nor extension.
1537//! WARNING: use string instead of string& because I pass values that do not convert to string&.
1538//! this is not a problem though because file are not opened so often.
1539//! @ param type the type of the opened file. 0 = none open, 1 = log, 2 = text, 4 = fits
1540inline void DataLogger::NotifyOpenedFile(const string &name, int type, DimDescribedService* service)
1541{
1542 if (!fOpenedFilesIsOn)
1543 return;
1544
1545 if (fDebugIsOn)
1546 {
1547 ostringstream str;
1548 str << "Updating " << service->getName() << " file '" << name << "' (type=" << type << ")";
1549 Debug(str);
1550
1551 str.str("");
1552 str << "Num subscriptions: " << fNumSubAndFitsData.numSubscriptions << " Num open FITS files: " << fNumSubAndFitsData.numOpenFits;
1553 Debug(str);
1554 }
1555
1556 if (name.size()+1 > FILENAME_MAX)
1557 {
1558 Error("Provided file name '" + name + "' is longer than allowed file name length.");
1559 return;
1560 }
1561
1562 OpenFileToDim fToDim;
1563 fToDim.code = type;
1564 memcpy(fToDim.fileName, name.c_str(), name.size()+1);
1565
1566 service->setData(reinterpret_cast<void*>(&fToDim), name.size()+1+sizeof(uint32_t));
1567 service->setQuality(0);
1568 service->Update();
1569}
1570// --------------------------------------------------------------------------
1571//
1572//! Implements the Start transition.
1573//! Concatenates the given path for the Nightly file and the filename itself (based on the day),
1574//! and tries to open it.
1575//! @returns
1576//! kSM_NightlyOpen if success, kSM_BadFolder if failure
1577int DataLogger::Start()
1578{
1579 if (fDebugIsOn)
1580 {
1581 Debug("Starting...");
1582 }
1583 fFullNightlyLogFileName = CompileFileNameWithPath(fFilePath, "", "log");
1584 bool nightlyLogOpen = fNightlyLogFile.is_open();
1585 if (!OpenTextFile(fNightlyLogFile, fFullNightlyLogFileName))
1586 return kSM_BadFolder;
1587 if (!nightlyLogOpen)
1588 fNightlyLogFile << endl;
1589
1590 fFullNightlyReportFileName = CompileFileNameWithPath(fFilePath, "", "rep");
1591 if (!OpenTextFile(fNightlyReportFile, fFullNightlyReportFileName))
1592 {
1593 fNightlyLogFile.close();
1594 Info("Closed: "+fFullNightlyReportFileName);
1595 return kSM_BadFolder;
1596 }
1597
1598 fFilesStats.FileOpened(fFullNightlyLogFileName);
1599 fFilesStats.FileOpened(fFullNightlyReportFileName);
1600 //notify that a new file has been opened.
1601 const string baseFileName = CompileFileNameWithPath(fFilePath, "", "");
1602 NotifyOpenedFile(baseFileName, 3, fOpenedNightlyFiles);
1603
1604 fOpenedNightlyFits.clear();
1605
1606 return kSM_NightlyOpen;
1607}
1608
1609#ifdef HAVE_FITS
1610// --------------------------------------------------------------------------
1611//
1612//! open if required a the FITS files corresponding to a given subscription
1613//! @param sub
1614//! the current DimInfo subscription being examined
1615void DataLogger::OpenFITSFiles(SubscriptionType& sub, const EventImp& evt)
1616{
1617 string serviceName(sub.server + "_" + sub.service);//evt.GetName());
1618
1619 for (unsigned int i=0;i<serviceName.size(); i++)
1620 {
1621 if (serviceName[i] == '/')
1622 {
1623 serviceName[i] = '_';
1624 break;
1625 }
1626 }
1627 //we open the NightlyFile anyway, otherwise this function shouldn't have been called.
1628 if (!sub.nightlyFile.IsOpen())
1629 {
1630 const string partialName = CompileFileNameWithPath(fFilePath, serviceName, "fits");
1631
1632 const string fileNameOnly = partialName.substr(partialName.find_last_of('/')+1, partialName.size());
1633 if (!sub.fitsBufferAllocated)
1634 AllocateFITSBuffers(sub, evt);
1635 //get the size of the file we're about to open
1636 if (fFilesStats.FileOpened(partialName))
1637 fOpenedNightlyFits[fileNameOnly].push_back(serviceName);
1638
1639 if (!sub.nightlyFile.Open(partialName, serviceName, &fNumSubAndFitsData.numOpenFits, this, 0))
1640 {
1641 GoToRunWriteErrorState();
1642 return;
1643 }
1644
1645 ostringstream str;
1646 str << "Opened: " << partialName << " (Nfits=" << fNumSubAndFitsData.numOpenFits << ")";
1647 Info(str);
1648
1649 //notify the opening
1650 const string baseFileName = CompileFileNameWithPath(fFilePath, "", "");
1651 NotifyOpenedFile(baseFileName, 7, fOpenedNightlyFiles);
1652 if (fNumSubAndFitsIsOn)
1653 fNumSubAndFits->Update();
1654 }
1655
1656}
1657// --------------------------------------------------------------------------
1658//
1659//! Allocates the required memory for a given pair of fits files (nightly and run)
1660//! @param sub the subscription of interest.
1661//
1662void DataLogger::AllocateFITSBuffers(SubscriptionType& sub, const EventImp& evt)
1663{
1664 //Init the time columns of the file
1665 Description dateDesc(string("Time"), string("Modified Julian Date"), string("MJD"));
1666 sub.nightlyFile.AddStandardColumn(dateDesc, "1D", &fMjD, sizeof(double));
1667
1668 Description QoSDesc("QoS", "Quality of service", "");
1669 sub.nightlyFile.AddStandardColumn(QoSDesc, "1J", &fQuality, sizeof(int));
1670
1671 // Compilation failed
1672 if (!sub.fConv->valid())
1673 {
1674 Error("Compilation of format string failed.");
1675 return;
1676 }
1677
1678 //we've got a nice structure describing the format of this service's messages.
1679 //Let's create the appropriate FITS columns
1680 const vector<string> dataFormatsLocal = sub.fConv->GetFitsFormat();
1681
1682 ostringstream str;
1683 str << "Initializing data columns for service " << sub.server << "/" << sub.service;
1684 Info(str);
1685 sub.nightlyFile.InitDataColumns(GetDescription(sub.server, sub.service), dataFormatsLocal, this);
1686
1687 sub.fitsBufferAllocated = true;
1688}
1689// --------------------------------------------------------------------------
1690//
1691//! write a dimInfo data to its corresponding FITS files
1692//
1693//FIXME: DO I REALLY NEED THE EVENT IMP HERE ???
1694void DataLogger::WriteToFITS(SubscriptionType& sub, const void* data)
1695{
1696 //nightly File status (open or not) already checked
1697 if (sub.nightlyFile.IsOpen())
1698 {
1699 if (!sub.nightlyFile.Write(*sub.fConv.get(), data))
1700 {
1701 RemoveService(sub.server, sub.service, false);
1702 GoToNightlyWriteErrorState();
1703 return;
1704 }
1705 }
1706}
1707#endif //if has_fits
1708// --------------------------------------------------------------------------
1709//
1710//! Go to Run Write Error State
1711// A write error has occurred. Checks what is the current state and take appropriate action
1712void DataLogger::GoToRunWriteErrorState()
1713{
1714 if ((GetCurrentState() != kSM_RunWriteError) &&
1715 (GetCurrentState() != kSM_DailyWriteError))
1716 SetCurrentState(kSM_RunWriteError);
1717}
1718// --------------------------------------------------------------------------
1719//
1720//! Go to Nightly Write Error State
1721// A write error has occurred. Checks what is the current state and take appropriate action
1722void DataLogger::GoToNightlyWriteErrorState()
1723{
1724 if (GetCurrentState() != kSM_DailyWriteError)
1725 SetCurrentState(kSM_DailyWriteError);
1726}
1727
1728
1729#ifdef HAVE_FITS
1730// --------------------------------------------------------------------------
1731//
1732//! Create a fits group file with all the run-fits that were written (either daily or run)
1733//! @param filesToGroup a map of filenames mapping to table names to be grouped (i.e. a
1734//! single file can contain several tables to group
1735//! @param runNumber the run number that should be used for grouping. 0 means nightly group
1736//
1737void DataLogger::CreateFitsGrouping(map<string, vector<string> > & filesToGroup)
1738{
1739 if (fDebugIsOn)
1740 {
1741 ostringstream str;
1742 str << "Creating fits group for nightly files";
1743 Debug(str);
1744 }
1745 //create the FITS group corresponding to the ending run.
1746 CCfits::FITS* groupFile;
1747 unsigned int numFilesToGroup = 0;
1748 unsigned int maxCharLength = 0;
1749 for (map<string, vector<string> >::const_iterator it=filesToGroup.begin(); it != filesToGroup.end(); it++)
1750 {
1751 //add the number of tables in this file to the total number to group
1752 numFilesToGroup += it->second.size();
1753 //check the length of all the strings to be written, to determine the max string length to write
1754 if (it->first.size() > maxCharLength)
1755 maxCharLength = it->first.size();
1756 for (vector<string>::const_iterator jt=it->second.begin(); jt != it->second.end(); jt++)
1757 if (jt->size() > maxCharLength)
1758 maxCharLength = jt->size();
1759 }
1760
1761 if (fDebugIsOn)
1762 {
1763 ostringstream str;
1764 str << "There are " << numFilesToGroup << " tables to group";
1765 Debug(str);
1766 }
1767 if (numFilesToGroup <= 1)
1768 {
1769 filesToGroup.clear();
1770 return;
1771 }
1772 const string groupName = CompileFileNameWithPath(fFilePath, "", "fits");
1773
1774 Info("Creating FITS group in: "+groupName);
1775
1776 CCfits::Table* groupTable;
1777
1778 try
1779 {
1780 groupFile = new CCfits::FITS(groupName, CCfits::RWmode::Write);
1781 //setup the column names
1782 ostringstream pathTypeName;
1783 pathTypeName << maxCharLength << "A";
1784 vector<string> names;
1785 vector<string> dataTypes;
1786 names.push_back("MEMBER_XTENSION");
1787 dataTypes.push_back("8A");
1788 names.push_back("MEMBER_URI_TYPE");
1789 dataTypes.push_back("3A");
1790 names.push_back("MEMBER_LOCATION");
1791 dataTypes.push_back(pathTypeName.str());
1792 names.push_back("MEMBER_NAME");
1793 dataTypes.push_back(pathTypeName.str());
1794 names.push_back("MEMBER_VERSION");
1795 dataTypes.push_back("1J");
1796 names.push_back("MEMBER_POSITION");
1797 dataTypes.push_back("1J");
1798
1799 groupTable = groupFile->addTable("GROUPING", numFilesToGroup, names, dataTypes);
1800//TODO handle the case when the logger was stopped and restarted during the same day, i.e. the grouping file must be updated
1801 }
1802 catch (CCfits::FitsException e)
1803 {
1804 ostringstream str;
1805 str << "Creating FITS table GROUPING in " << groupName << ": " << e.message();
1806 Error(str);
1807 return;
1808 }
1809 try
1810 {
1811 groupTable->addKey("GRPNAME", "FACT_RAW_DATA", "Data from the FACT telescope");
1812 }
1813 catch (CCfits::FitsException e)
1814 {
1815 Error("CCfits::Table::addKey failed for 'GRPNAME' in '"+groupName+"-GROUPING': "+e.message());
1816 return;
1817 }
1818 //CCfits seems to be buggy somehow: can't use the column's function "write": it create a compilation error: maybe strings were not thought about.
1819 //use cfitsio routines instead
1820 groupTable->makeThisCurrent();
1821 //create appropriate buffer.
1822 const unsigned int n = 8 + 3 + 2*maxCharLength + 1 + 8; //+1 for trailling character
1823
1824 vector<char> realBuffer(n);
1825
1826 char *startOfExtension = realBuffer.data();
1827 char *startOfURI = realBuffer.data()+8;
1828 char *startOfLocation = realBuffer.data()+8+3;
1829 char *startOfName = realBuffer.data()+8+3+maxCharLength;
1830
1831 strcpy(startOfExtension, "BINTABLE");
1832 strcpy(startOfURI, "URL");
1833
1834 realBuffer[8+3+2*maxCharLength+3] = 1;
1835 realBuffer[8+3+2*maxCharLength+7] = 1;
1836
1837 int i=1;
1838 for (map<string, vector<string> >::const_iterator it=filesToGroup.begin(); it!=filesToGroup.end(); it++)
1839 for (vector<string>::const_iterator jt=it->second.begin(); jt != it->second.end(); jt++, i++)
1840 {
1841 memset(startOfLocation, 0, 2*maxCharLength+1+8);
1842
1843 strcpy(startOfLocation, it->first.c_str());
1844 strcpy(startOfName, jt->c_str());
1845
1846 if (fDebugIsOn)
1847 {
1848 ostringstream str;
1849 str << "Grouping " << it->first << " " << *jt;
1850 Debug(str);
1851 }
1852
1853 int status = 0;
1854 fits_write_tblbytes(groupFile->fitsPointer(), i, 1, 8+3+2*maxCharLength +8,
1855 reinterpret_cast<unsigned char*>(realBuffer.data()), &status);
1856 if (status)
1857 {
1858 char text[30];//max length of cfitsio error strings (from doc)
1859 fits_get_errstatus(status, text);
1860 ostringstream str;
1861 str << "Writing FITS row " << i << " in " << groupName << ": " << text << " (file_write_tblbytes, rc=" << status << ")";
1862 Error(str);
1863 GoToRunWriteErrorState();
1864 delete groupFile;
1865 return;
1866 }
1867 }
1868
1869 filesToGroup.clear();
1870 delete groupFile;
1871}
1872#endif //HAVE_FITS
1873
1874// --------------------------------------------------------------------------
1875//
1876//! Implements the StopRun transition.
1877//! Attempts to close the run file.
1878//! @returns
1879//! kSM_WaitingRun if success, kSM_FatalError otherwise
1880int DataLogger::StopRunLogging()
1881{
1882
1883 if (fDebugIsOn)
1884 {
1885 Debug("Stopping Run Logging...");
1886 }
1887
1888 if (fNumSubAndFitsIsOn)
1889 fNumSubAndFits->Update();
1890
1891 while (fRunNumber.size() > 0)
1892 {
1893 RemoveOldestRunNumber();
1894 }
1895 return kSM_WaitingRun;
1896}
1897// --------------------------------------------------------------------------
1898//
1899//! Implements the Stop and Reset transitions.
1900//! Attempts to close any openned file.
1901//! @returns
1902//! kSM_Ready
1903int DataLogger::GoToReady()
1904{
1905 if (fDebugIsOn)
1906 {
1907 Debug("Going to the Ready state...");
1908 }
1909 if (GetCurrentState() == kSM_Logging || GetCurrentState() == kSM_WaitingRun)
1910 StopRunLogging();
1911
1912 //it may be that dim tries to write a dimInfo while we're closing files. Prevent that
1913 const string baseFileName = CompileFileNameWithPath(fFilePath, "", "");
1914
1915 if (fNightlyReportFile.is_open())
1916 {
1917 fNightlyReportFile.close();
1918 Info("Closed: "+baseFileName+".rep");
1919 }
1920#ifdef HAVE_FITS
1921 for (SubscriptionsListType::iterator i = fServiceSubscriptions.begin(); i != fServiceSubscriptions.end(); i++)
1922 for (map<string, SubscriptionType>::iterator j = i->second.begin(); j != i->second.end(); j++)
1923 {
1924 if (j->second.nightlyFile.IsOpen())
1925 j->second.nightlyFile.Close();
1926 }
1927#endif
1928 if (GetCurrentState() == kSM_Logging ||
1929 GetCurrentState() == kSM_WaitingRun ||
1930 GetCurrentState() == kSM_NightlyOpen)
1931 {
1932 NotifyOpenedFile("", 0, fOpenedNightlyFiles);
1933 if (fNumSubAndFitsIsOn)
1934 fNumSubAndFits->Update();
1935 }
1936#ifdef HAVE_FITS
1937 CreateFitsGrouping(fOpenedNightlyFits);
1938#endif
1939 return kSM_Ready;
1940}
1941
1942// --------------------------------------------------------------------------
1943//
1944//! Implements the transition towards kSM_WaitingRun
1945//! If current state is kSM_Ready, then tries to go to nightlyOpen state first.
1946//! @returns
1947//! kSM_WaitingRun or kSM_BadFolder
1948int DataLogger::NightlyToWaitRun()
1949{
1950 int cState = GetCurrentState();
1951
1952 if (cState == kSM_Ready)
1953 cState = Start();
1954
1955 if (cState != kSM_NightlyOpen)
1956 return GetCurrentState();
1957
1958 if (fDebugIsOn)
1959 {
1960 Debug("Going to Wait Run Number state...");
1961 }
1962 return kSM_WaitingRun;
1963}
1964// --------------------------------------------------------------------------
1965//
1966//! Implements the transition from wait for run number to nightly open
1967//! Does nothing really.
1968//! @returns
1969//! kSM_WaitingRun
1970int DataLogger::BackToNightlyOpen()
1971{
1972 if (GetCurrentState()==kSM_Logging)
1973 StopRunLogging();
1974
1975 if (fDebugIsOn)
1976 {
1977 Debug("Going to NightlyOpen state...");
1978 }
1979 return kSM_NightlyOpen;
1980}
1981// --------------------------------------------------------------------------
1982//
1983//! Setup Logger's configuration from a Configuration object
1984//! @param conf the configuration object that should be used
1985//!
1986int DataLogger::EvalOptions(Configuration& conf)
1987{
1988 fDebugIsOn = conf.Get<bool>("debug");
1989 fFilesStats.SetDebugMode(fDebugIsOn);
1990
1991 //Set the block or allow list
1992 fBlackList.clear();
1993 fWhiteList.clear();
1994
1995 //Adding entries that should ALWAYS be ignored
1996 fBlackList.insert("DATA_LOGGER/MESSAGE");
1997 fBlackList.insert("/SERVICE_LIST");
1998 fBlackList.insert("DIS_DNS/");
1999
2000 //set the black list, white list and the goruping
2001 const vector<string> vec1 = conf.Vec<string>("block");
2002 const vector<string> vec2 = conf.Vec<string>("allow");
2003 const vector<string> vec3 = conf.Vec<string>("group");
2004
2005 fBlackList.insert(vec1.begin(), vec1.end());
2006 fWhiteList.insert(vec2.begin(), vec2.end());
2007 fGrouping.insert( vec3.begin(), vec3.end());
2008
2009 //set the old run numbers timeout delay
2010 if (conf.Has("run-timeout"))
2011 {
2012 const uint32_t timeout = conf.Get<uint32_t>("run-timeout");
2013 if (timeout == 0)
2014 {
2015 Error("Time out delay for old run numbers must not be 0.");
2016 return 1;
2017 }
2018 fRunNumberTimeout = timeout;
2019 }
2020
2021 //configure the run files directory
2022 if (conf.Has("destination-folder"))
2023 {
2024 const string folder = conf.Get<string>("destination-folder");
2025 if (!fFilesStats.SetCurrentFolder(folder))
2026 return 2;
2027
2028 fFilePath = folder;
2029 fFullNightlyLogFileName = CompileFileNameWithPath(fFilePath, "", "log");
2030 if (!OpenTextFile(fNightlyLogFile, fFullNightlyLogFileName))
2031 return 3;
2032
2033 fNightlyLogFile << endl;
2034 NotifyOpenedFile(fFullNightlyLogFileName, 1, fOpenedNightlyFiles);
2035 for (vector<string>::iterator it=backLogBuffer.begin();it!=backLogBuffer.end();it++)
2036 fNightlyLogFile << *it;
2037 }
2038
2039 shouldBackLog = false;
2040 backLogBuffer.clear();
2041
2042 //configure the interval between statistics updates
2043 if (conf.Has("stats-interval"))
2044 fFilesStats.SetUpdateInterval(conf.Get<int16_t>("stats-interval"));
2045
2046 //configure if the filenames service is on or off
2047 fOpenedFilesIsOn = !conf.Get<bool>("no-filename-service");
2048
2049 //configure if the number of subscriptions and fits files is on or off.
2050 fNumSubAndFitsIsOn = !conf.Get<bool>("no-numsubs-service");
2051 //should we open the daily files at startup ?
2052 if (conf.Has("start-daily-files"))
2053 if (conf.Get<bool>("start-daily-files"))
2054 {
2055 fShouldAutoStart = true;
2056 }
2057 return -1;
2058}
2059
2060
2061#include "Main.h"
2062
2063// --------------------------------------------------------------------------
2064template<class T>
2065int RunShell(Configuration &conf)
2066{
2067 return Main::execute<T, DataLogger>(conf);//, true);
2068}
2069
2070/*
2071 Extract usage clause(s) [if any] for SYNOPSIS.
2072 Translators: "Usage" and "or" here are patterns (regular expressions) which
2073 are used to match the usage synopsis in program output. An example from cp
2074 (GNU coreutils) which contains both strings:
2075 Usage: cp [OPTION]... [-T] SOURCE DEST
2076 or: cp [OPTION]... SOURCE... DIRECTORY
2077 or: cp [OPTION]... -t DIRECTORY SOURCE...
2078 */
2079void PrintUsage()
2080{
2081 cout << "\n"
2082 "The data logger connects to all available Dim services and "
2083 "writes them to ascii and fits files.\n"
2084 "\n"
2085 "The default is that the program is started without user interaction. "
2086 "All actions are supposed to arrive as DimCommands. Using the -c "
2087 "option, a local shell can be initialized. With h or help a short "
2088 "help message about the usage can be brought to the screen.\n"
2089 "\n"
2090 "Usage: datalogger [-c type] [OPTIONS]\n"
2091 " or: datalogger [OPTIONS]\n";
2092 cout << endl;
2093
2094}
2095// --------------------------------------------------------------------------
2096void PrintHelp()
2097{
2098 /* Additional help text which is printed after the configuration
2099 options goes here */
2100 cout <<
2101 "\n"
2102 "If the allow list has any element, only the servers and/or services "
2103 "specified in the list will be used for subscription. The black list "
2104 "will disable service subscription and has higher priority than the "
2105 "allow list. If the allow list is not present by default all services "
2106 "will be subscribed."
2107 "\n"
2108 "For example, block=DIS_DNS/ will skip all the services offered by "
2109 "the DIS_DNS server, while block=/SERVICE_LIST will skip all the "
2110 "SERVICE_LIST services offered by any server and DIS_DNS/SERVICE_LIST "
2111 "will skip DIS_DNS/SERVICE_LIST.\n"
2112 << endl;
2113
2114 Main::PrintHelp<DataLogger>();
2115}
2116
2117// --------------------------------------------------------------------------
2118void SetupConfiguration(Configuration &conf)
2119{
2120 po::options_description configs("DataLogger options");
2121 configs.add_options()
2122 ("block,b", vars<string>(), "Black-list to block services")
2123 ("allow,a", vars<string>(), "White-list to only allowe certain services")
2124 ("debug,d", po_bool(), "Debug mode. Print clear text of received service reports.")
2125 ("group,g", vars<string>(), "Grouping of services into a single run-Fits")
2126 ("run-timeout", var<uint32_t>(), "Time out delay for old run numbers in milliseconds.")
2127 ("destination-folder", var<string>(), "Base path for the nightly and run files")
2128 ("stats-interval", var<int16_t>(), "Interval in milliseconds for write statistics update")
2129 ("no-filename-service", po_bool(), "Disable update of filename service")
2130 ("no-numsubs-service", po_bool(), "Disable update of number-of-subscriptions service")
2131 ("start-daily-files", po_bool(), "Starts the logger in DailyFileOpen instead of Ready")
2132 ;
2133
2134 conf.AddOptions(configs);
2135}
2136// --------------------------------------------------------------------------
2137int main(int argc, const char* argv[])
2138{
2139 Configuration conf(argv[0]);
2140 conf.SetPrintUsage(PrintUsage);
2141 Main::SetupConfiguration(conf);
2142 SetupConfiguration(conf);
2143
2144 if (!conf.DoParse(argc, argv, PrintHelp))
2145 return 127;
2146
2147 {
2148 // No console access at all
2149 if (!conf.Has("console"))
2150 return RunShell<LocalStream>(conf);
2151
2152 // Console access w/ and w/o Dim
2153 if (conf.Get<int>("console")==0)
2154 return RunShell<LocalShell>(conf);
2155 else
2156 return RunShell<LocalConsole>(conf);
2157 }
2158
2159
2160 return 0;
2161}
Note: See TracBrowser for help on using the repository browser.