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

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