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

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