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

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