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

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