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

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