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

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