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

Last change on this file since 12705 was 12705, checked in by lyard, 13 years ago
added more columns in grouping files
File size: 86.6 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
1415}
1416
1417// --------------------------------------------------------------------------
1418//
1419//! print the dataLogger's current state. invoked by the PRINT command
1420//! @param evt
1421//! the current event. Not used by the method
1422//! @returns
1423//! the new state. Which, in that case, is the current state
1424//!
1425int DataLogger::PrintStatePlease(const Event& )
1426{
1427 Message("------------------------------------------");
1428 Message("------- DATA LOGGER CURRENT STATE --------");
1429 Message("------------------------------------------");
1430
1431 //print the path configuration
1432 Message("File path: " + boost::filesystem::system_complete(boost::filesystem::path(fFilePath)).directory_string());
1433
1434 //print active run numbers
1435 ostringstream str;
1436 //timeout value
1437 str << "Timeout delay for old run numbers: " << fRunNumberTimeout << " ms";
1438 Message(str);
1439 str.str("");
1440 str << "Active Run Numbers:";
1441 for (list<RunNumberType>::const_iterator it=fRunNumber.begin(); it!=fRunNumber.end(); it++)
1442 str << " " << it->runNumber;
1443 if (fRunNumber.size()==0)
1444 str << " <none>";
1445 Message(str);
1446
1447 //print all the open files.
1448 Message("------------ OPEN FILES ----------------");
1449 if (fNightlyLogFile.is_open())
1450 Message("Nightly log-file: "+fFullNightlyLogFileName);
1451
1452 if (fNightlyReportFile.is_open())
1453 Message("Nightly report-file: "+fFullNightlyReportFileName);
1454
1455 for (list<RunNumberType>::const_iterator it=fRunNumber.begin(); it!=fRunNumber.end(); it++)
1456 {
1457#ifdef RUN_LOGS
1458 if (it->logFile->is_open())
1459 Message("Run log-file: " + it->logName);
1460#endif
1461 if (it->reportFile->is_open())
1462 Message("Run report-file: " + it->reportName);
1463 }
1464
1465 const DimWriteStatistics::Stats statVar = fFilesStats.GetTotalSizeWritten();
1466 // /*const bool statWarning =*/ calculateTotalSizeWritten(statVar, true);
1467#ifdef HAVE_FITS
1468 str.str("");
1469 str << "Number of open FITS files: " << fNumSubAndFitsData.numOpenFits;
1470 Message(str);
1471 // FIXME: Print list of open FITS files
1472#else
1473 Message("FITS output disabled at compilation");
1474#endif
1475 Message("----------------- STATS ------------------");
1476 if (fFilesStats.GetUpdateInterval()>0)
1477 {
1478 str.str("");
1479 str << "Statistics are updated every " << fFilesStats.GetUpdateInterval() << " ms";
1480 Message(str);
1481 }
1482 else
1483 Message("Statistics updates are currently disabled.");
1484 str.str("");
1485 str << "Total Size written: " << statVar.sizeWritten/1000 << " kB";
1486 Message(str);
1487 str.str("");
1488 str << "Disk free space: " << statVar.freeSpace/1000000 << " MB";
1489 Message(str);
1490
1491 Message("------------ DIM SUBSCRIPTIONS -----------");
1492 str.str("");
1493 str << "There are " << fNumSubAndFitsData.numSubscriptions << " active DIM subscriptions.";
1494 Message(str);
1495 for (map<const string, map<string, SubscriptionType> >::const_iterator it=fServiceSubscriptions.begin(); it!= fServiceSubscriptions.end();it++)
1496 {
1497 Message("Server "+it->first);
1498 for (map<string, SubscriptionType>::const_iterator it2=it->second.begin(); it2!=it->second.end(); it2++)
1499 Message(" -> "+it2->first);
1500 }
1501 Message("--------------- BLOCK LIST ---------------");
1502 for (set<string>::const_iterator it=fBlackList.begin(); it != fBlackList.end(); it++)
1503 Message(" -> "+*it);
1504 if (fBlackList.size()==0)
1505 Message(" <empty>");
1506
1507 Message("--------------- ALLOW LIST ---------------");
1508 for (set<string>::const_iterator it=fWhiteList.begin(); it != fWhiteList.end(); it++)
1509 Message(" -> "+*it);
1510 if (fWhiteList.size()==0)
1511 Message(" <empty>");
1512
1513 Message("-------------- GROUPING LIST -------------");
1514 Message("The following servers and/or services will");
1515 Message("be grouped into a single fits file:");
1516 for (set<string>::const_iterator it=fGrouping.begin(); it != fGrouping.end(); it++)
1517 Message(" -> "+*it);
1518 if (fGrouping.size()==0)
1519 Message(" <no grouping>");
1520
1521 Message("------------------------------------------");
1522 Message("-------- END OF DATA LOGGER STATE --------");
1523 Message("------------------------------------------");
1524
1525 return GetCurrentState();
1526}
1527
1528// --------------------------------------------------------------------------
1529//
1530//! turn debug mode on and off
1531//! @param evt
1532//! the current event. contains the instruction string: On, Off, on, off, ON, OFF, 0 or 1
1533//! @returns
1534//! the new state. Which, in that case, is the current state
1535//!
1536int DataLogger::SetDebugOnOff(const Event& evt)
1537{
1538 const bool backupDebug = fDebugIsOn;
1539
1540 fDebugIsOn = evt.GetBool();
1541
1542 if (fDebugIsOn == backupDebug)
1543 Message("Debug mode was already in the requested state.");
1544
1545 ostringstream str;
1546 str << "Debug mode is now " << fDebugIsOn;
1547 Message(str);
1548
1549 fFilesStats.SetDebugMode(fDebugIsOn);
1550
1551 return GetCurrentState();
1552}
1553// --------------------------------------------------------------------------
1554//
1555//! set the statistics update period duration. 0 disables the statistics
1556//! @param evt
1557//! the current event. contains the new duration.
1558//! @returns
1559//! the new state. Which, in that case, is the current state
1560//!
1561int DataLogger::SetStatsPeriod(const Event& evt)
1562{
1563 fFilesStats.SetUpdateInterval(evt.GetShort());
1564 return GetCurrentState();
1565}
1566// --------------------------------------------------------------------------
1567//
1568//! set the opened files service on or off.
1569//! @param evt
1570//! the current event. contains the instruction string. similar to setdebugonoff
1571//! @returns
1572//! the new state. Which, in that case, is the current state
1573//!
1574int DataLogger::SetOpenedFilesOnOff(const Event& evt)
1575{
1576 const bool backupOpened = fOpenedFilesIsOn;
1577
1578 fOpenedFilesIsOn = evt.GetBool();
1579
1580 if (fOpenedFilesIsOn == backupOpened)
1581 Message("Opened files service mode was already in the requested state.");
1582
1583 ostringstream str;
1584 str << "Opened files service mode is now " << fOpenedFilesIsOn;
1585 Message(str);
1586
1587 return GetCurrentState();
1588}
1589
1590// --------------------------------------------------------------------------
1591//
1592//! set the number of subscriptions and opened fits on and off
1593//! @param evt
1594//! the current event. contains the instruction string. similar to setdebugonoff
1595//! @returns
1596//! the new state. Which, in that case, is the current state
1597//!
1598int DataLogger::SetNumSubsAndFitsOnOff(const Event& evt)
1599{
1600 const bool backupSubs = fNumSubAndFitsIsOn;
1601
1602 fNumSubAndFitsIsOn = evt.GetBool();
1603
1604 if (fNumSubAndFitsIsOn == backupSubs)
1605 Message("Number of subscriptions service mode was already in the requested state");
1606
1607 ostringstream str;
1608 str << "Number of subscriptions service mode is now " << fNumSubAndFitsIsOn;
1609 Message(str);
1610
1611 return GetCurrentState();
1612}
1613// --------------------------------------------------------------------------
1614//
1615//! set the timeout delay for old run numbers
1616//! @param evt
1617//! the current event. contains the timeout delay long value
1618//! @returns
1619//! the new state. Which, in that case, is the current state
1620//!
1621int DataLogger::SetRunTimeoutDelay(const Event& evt)
1622{
1623 if (evt.GetUInt() == 0)
1624 {
1625 Error("Timeout delays for old run numbers must be greater than 0... ignored.");
1626 return GetCurrentState();
1627 }
1628
1629 if (fRunNumberTimeout == evt.GetUInt())
1630 Message("New timeout for old run numbers is same value as previous one.");
1631
1632 fRunNumberTimeout = evt.GetUInt();
1633
1634 ostringstream str;
1635 str << "Timeout delay for old run numbers is now " << fRunNumberTimeout << " ms";
1636 Message(str);
1637
1638 return GetCurrentState();
1639}
1640
1641// --------------------------------------------------------------------------
1642//
1643//! Sets the path to use for the Nightly log file.
1644//! @param evt
1645//! the event transporting the path
1646//! @returns
1647//! currently only the current state.
1648/*
1649int DataLogger::ConfigureFilePath(const Event& evt)
1650{
1651 if (!evt.GetText())
1652 {
1653 Error("Empty folder given. Please specify a valid path.");
1654 return GetCurrentState();
1655 }
1656
1657 const string givenPath = evt.GetText();
1658 if (!DoesPathExist(givenPath))
1659 {
1660 Error("Provided path '"+givenPath+"' is not a valid folder... ignored.");
1661 return GetCurrentState();
1662 }
1663
1664 Message("New folder: "+givenPath);
1665
1666 fFilePath = givenPath;
1667
1668 fFilesStats.SetCurrentFolder(givenPath);
1669
1670 return GetCurrentState();
1671}
1672*/
1673
1674// --------------------------------------------------------------------------
1675//
1676//! Notifies the DIM service that a particular file was opened
1677//! @ param name the base name of the opened file, i.e. without path nor extension.
1678//! WARNING: use string instead of string& because I pass values that do not convert to string&.
1679//! this is not a problem though because file are not opened so often.
1680//! @ param type the type of the opened file. 0 = none open, 1 = log, 2 = text, 4 = fits
1681inline void DataLogger::NotifyOpenedFile(const string &name, int type, DimDescribedService* service)
1682{
1683 if (!fOpenedFilesIsOn)
1684 return;
1685
1686 if (fDebugIsOn)
1687 {
1688 ostringstream str;
1689 str << "Updating " << service->getName() << " file '" << name << "' (type=" << type << ")";
1690 Debug(str);
1691
1692 str.str("");
1693 str << "Num subscriptions: " << fNumSubAndFitsData.numSubscriptions << " Num open FITS files: " << fNumSubAndFitsData.numOpenFits;
1694 Debug(str);
1695 }
1696
1697 if (name.size()+1 > FILENAME_MAX)
1698 {
1699 Error("Provided file name '" + name + "' is longer than allowed file name length.");
1700 return;
1701 }
1702
1703 OpenFileToDim fToDim;
1704 fToDim.code = type;
1705 memcpy(fToDim.fileName, name.c_str(), name.size()+1);
1706
1707 service->setData(reinterpret_cast<void*>(&fToDim), name.size()+1+sizeof(uint32_t));
1708 service->setQuality(0);
1709 service->Update();
1710}
1711// --------------------------------------------------------------------------
1712//
1713//! Implements the Start transition.
1714//! Concatenates the given path for the Nightly file and the filename itself (based on the day),
1715//! and tries to open it.
1716//! @returns
1717//! kSM_NightlyOpen if success, kSM_BadFolder if failure
1718int DataLogger::StartPlease()
1719{
1720 if (fDebugIsOn)
1721 {
1722 Debug("Starting...");
1723 }
1724 fFullNightlyLogFileName = CompileFileNameWithPath(fFilePath, "", "log");
1725 bool nightlyLogOpen = fNightlyLogFile.is_open();
1726 if (!OpenTextFilePlease(fNightlyLogFile, fFullNightlyLogFileName))
1727 return kSM_BadFolder;
1728 if (!nightlyLogOpen)
1729 fNightlyLogFile << endl;
1730
1731 fFullNightlyReportFileName = CompileFileNameWithPath(fFilePath, "", "rep");
1732 if (!OpenTextFilePlease(fNightlyReportFile, fFullNightlyReportFileName))
1733 {
1734 fNightlyLogFile.close();
1735 Info("Closed: "+fFullNightlyReportFileName);
1736 return kSM_BadFolder;
1737 }
1738
1739 fFilesStats.FileOpened(fFullNightlyLogFileName);
1740 fFilesStats.FileOpened(fFullNightlyReportFileName);
1741 //notify that a new file has been opened.
1742 const string baseFileName = CompileFileNameWithPath(fFilePath, "", "");
1743 NotifyOpenedFile(baseFileName, 3, fOpenedNightlyFiles);
1744
1745 fOpenedNightlyFits.clear();
1746
1747 return kSM_NightlyOpen;
1748}
1749
1750#ifdef HAVE_FITS
1751// --------------------------------------------------------------------------
1752//
1753//! open if required a the FITS files corresponding to a given subscription
1754//! @param sub
1755//! the current DimInfo subscription being examined
1756void DataLogger::OpenFITSFilesPlease(SubscriptionType& sub, RunNumberType* cRunNumber)
1757{
1758 string serviceName(sub.dimInfo->getName());
1759
1760 //if run number has changed, reopen a new fits file with the correct run number.
1761 if (sub.runFile.IsOpen() && sub.runFile.fRunNumber != sub.runNumber)
1762 {
1763 sub.runFile.Close();
1764 Info("Closed: "+sub.runFile.GetName()+" (new run number)");
1765 }
1766
1767 //we must check if we should group this service subscription to a single fits file before we replace the / by _
1768 bool hasGrouping = false;
1769 if (!sub.runFile.IsOpen() && ((GetCurrentState() == kSM_Logging) || (GetCurrentState() == kSM_WaitingRun)))
1770 {//will we find this service in the grouping list ?
1771 for (set<string>::const_iterator it=fGrouping.begin(); it!=fGrouping.end(); it++)
1772 {
1773 if (serviceName.find(*it) != string::npos)
1774 {
1775 hasGrouping = true;
1776 break;
1777 }
1778 }
1779 }
1780 for (unsigned int i=0;i<serviceName.size(); i++)
1781 {
1782 if (serviceName[i] == '/')
1783 {
1784 serviceName[i] = '_';
1785 break;
1786 }
1787 }
1788 //we open the NightlyFile anyway, otherwise this function shouldn't have been called.
1789 if (!sub.nightlyFile.IsOpen())
1790 {
1791 const string partialName = CompileFileNameWithPath(fFilePath, serviceName, "fits");
1792
1793 const string fileNameOnly = partialName.substr(partialName.find_last_of('/')+1, partialName.size());
1794 if (!sub.fitsBufferAllocated)
1795 AllocateFITSBuffers(sub);
1796 //get the size of the file we're about to open
1797 if (fFilesStats.FileOpened(partialName))
1798 fOpenedNightlyFits[fileNameOnly].push_back(serviceName);
1799
1800 if (!sub.nightlyFile.Open(partialName, serviceName, &fNumSubAndFitsData.numOpenFits, this, 0))
1801 {
1802 GoToRunWriteErrorState();
1803 return;
1804 }
1805
1806 ostringstream str;
1807 str << "Opened: " << partialName << " (Nfits=" << fNumSubAndFitsData.numOpenFits << ")";
1808 Info(str);
1809
1810 //notify the opening
1811 const string baseFileName = CompileFileNameWithPath(fFilePath, "", "");
1812 NotifyOpenedFile(baseFileName, 7, fOpenedNightlyFiles);
1813 if (fNumSubAndFitsIsOn)
1814 fNumSubAndFits->Update();
1815 }
1816 //do the actual file open
1817 if (!sub.runFile.IsOpen() && (GetCurrentState() == kSM_WaitingRun || GetCurrentState() == kSM_Logging) && sub.runNumber > 0)
1818 {//buffer for the run file have already been allocated when doing the Nightly file
1819
1820 const string partialName =
1821 CompileFileNameWithPath(fFilePath, hasGrouping ? "" : serviceName, "fits", sub.runNumber);
1822
1823 const string fileNameOnly =
1824 partialName.substr(partialName.find_last_of('/')+1, partialName.size());
1825
1826 //get the size of the file we're about to open
1827 if (fFilesStats.FileOpened(partialName))
1828 cRunNumber->openedFits[fileNameOnly].push_back(serviceName);
1829 else
1830 if (hasGrouping)
1831 {
1832 cRunNumber->addServiceToOpenedFits(fileNameOnly, serviceName);
1833 }
1834
1835 if (hasGrouping && (!cRunNumber->runFitsFile.get()))
1836 try
1837 {
1838 cRunNumber->runFitsFile = shared_ptr<CCfits::FITS>(new CCfits::FITS(partialName, CCfits::RWmode::Write));
1839 (fNumSubAndFitsData.numOpenFits)++;
1840 }
1841 catch (CCfits::FitsException e)
1842 {
1843 ostringstream str;
1844 str << "Open FITS file " << partialName << ": " << e.message();
1845 Error(str);
1846 cRunNumber->runFitsFile = shared_ptr<CCfits::FITS>();
1847 GoToRunWriteErrorState();
1848 return;
1849 }
1850
1851 const string baseFileName = CompileFileNameWithPath(fFilePath, "", "", sub.runNumber);
1852 NotifyOpenedFile(baseFileName, 7, fOpenedRunFiles);
1853
1854 if (hasGrouping)
1855 {
1856 if (!sub.runFile.Open(partialName, serviceName, &fNumSubAndFitsData.numOpenFits, this, sub.runNumber, cRunNumber->runFitsFile.get()))
1857 {
1858 GoToRunWriteErrorState();
1859 return;
1860 }
1861 }
1862 else
1863 {
1864 if (!sub.runFile.Open(partialName, serviceName, &fNumSubAndFitsData.numOpenFits, this, sub.runNumber))
1865 {
1866 GoToRunWriteErrorState();
1867 return;
1868 }
1869 }
1870
1871 ostringstream str;
1872 str << "Opened: " << partialName << " (Nfits=" << fNumSubAndFitsData.numOpenFits << ")";
1873 Info(str);
1874
1875 if (fNumSubAndFitsIsOn)
1876 fNumSubAndFits->Update();
1877 }
1878}
1879// --------------------------------------------------------------------------
1880//
1881//! Allocates the required memory for a given pair of fits files (nightly and run)
1882//! @param sub the subscription of interest.
1883//
1884void DataLogger::AllocateFITSBuffers(SubscriptionType& sub)
1885{
1886 //Init the time columns of the file
1887 Description dateDesc(string("Time"), string("Modified Julian Date"), string("MJD"));
1888 sub.nightlyFile.AddStandardColumn(dateDesc, "1D", &fMjD, sizeof(double));
1889 sub.runFile.AddStandardColumn(dateDesc, "1D", &fMjD, sizeof(double));
1890
1891 Description QoSDesc("QoS", "Quality of service", "");
1892 sub.nightlyFile.AddStandardColumn(QoSDesc, "1J", &fQuality, sizeof(int));
1893 sub.runFile.AddStandardColumn(QoSDesc, "1J", &fQuality, sizeof(int));
1894
1895 // Compilation failed
1896 if (!sub.fConv->valid())
1897 {
1898 Error("Compilation of format string failed.");
1899 return;
1900 }
1901
1902 //we've got a nice structure describing the format of this service's messages.
1903 //Let's create the appropriate FITS columns
1904 const vector<string> dataFormatsLocal = sub.fConv->GetFitsFormat();
1905
1906 sub.nightlyFile.InitDataColumns(GetDescription(sub.server, sub.service), dataFormatsLocal, sub.dimInfo->getData(), this);
1907 sub.runFile.InitDataColumns(GetDescription(sub.server, sub.service), dataFormatsLocal, sub.dimInfo->getData(), this);
1908 sub.fitsBufferAllocated = true;
1909}
1910// --------------------------------------------------------------------------
1911//
1912//! write a dimInfo data to its corresponding FITS files
1913//
1914void DataLogger::WriteToFITS(SubscriptionType& sub)
1915{
1916 //nightly File status (open or not) already checked
1917 if (sub.nightlyFile.IsOpen())
1918 {
1919 if (!sub.nightlyFile.Write(*sub.fConv.get()))
1920 {
1921 //sub.nightlyFile.Close();
1922 RemoveService(sub.server, sub.service, false);
1923 GoToNightlyWriteErrorState();
1924 return;
1925 }
1926 // sub.nightlyFile.Flush();
1927 }
1928
1929 if (sub.runFile.IsOpen())
1930 {
1931 if (!sub.runFile.Write(*sub.fConv.get()))
1932 {
1933 sub.runFile.Close();
1934 RemoveService(sub.server, sub.service, false);
1935 GoToRunWriteErrorState();
1936 return;
1937 }
1938 }
1939}
1940#endif //if has_fits
1941// --------------------------------------------------------------------------
1942//
1943//! Go to Run Write Error State
1944// A write error has occurred. Checks what is the current state and take appropriate action
1945void DataLogger::GoToRunWriteErrorState()
1946{
1947 if ((GetCurrentState() != kSM_RunWriteError) &&
1948 (GetCurrentState() != kSM_DailyWriteError))
1949 SetCurrentState(kSM_RunWriteError);
1950}
1951// --------------------------------------------------------------------------
1952//
1953//! Go to Nightly Write Error State
1954// A write error has occurred. Checks what is the current state and take appropriate action
1955void DataLogger::GoToNightlyWriteErrorState()
1956{
1957 if (GetCurrentState() != kSM_DailyWriteError)
1958 SetCurrentState(kSM_DailyWriteError);
1959}
1960
1961/*
1962// --------------------------------------------------------------------------
1963//
1964//! Implements the StartRun transition.
1965//! Concatenates the given path for the run file and the filename itself (based on the run number),
1966//! and tries to open it.
1967//! @returns
1968//! kSM_Logging if success, kSM_BadRunConfig if failure.
1969int DataLogger::StartRunPlease()
1970{
1971 if (fDebugIsOn)
1972 {
1973 Debug("Starting Run Logging...");
1974 }
1975 //open all the relevant run-files. i.e. all the files associated with run numbers.
1976 for (list<RunNumberType>::iterator it=fRunNumber.begin(); it != fRunNumber.end(); it++)
1977 if (OpenRunFile(*it) != 0)
1978 {
1979 StopRunPlease();
1980 return kSM_BadRunConfig;
1981 }
1982
1983 return kSM_Logging;
1984}
1985*/
1986#ifdef HAVE_FITS
1987// --------------------------------------------------------------------------
1988//
1989//! Create a fits group file with all the run-fits that were written (either daily or run)
1990//! @param filesToGroup a map of filenames mapping to table names to be grouped (i.e. a
1991//! single file can contain several tables to group
1992//! @param runNumber the run number that should be used for grouping. 0 means nightly group
1993//
1994void DataLogger::CreateFitsGrouping(map<string, vector<string> > & filesToGroup, int runNumber)
1995{
1996 if (fDebugIsOn)
1997 {
1998 ostringstream str;
1999 str << "Creating fits group for ";
2000 if (runNumber != 0)
2001 str << "run files";
2002 else
2003 str << "nightly files";
2004 Debug(str);
2005 }
2006 //create the FITS group corresponding to the ending run.
2007 CCfits::FITS* groupFile;
2008 unsigned int numFilesToGroup = 0;
2009 unsigned int maxCharLength = 0;
2010 for (map<string, vector<string> >::const_iterator it=filesToGroup.begin(); it != filesToGroup.end(); it++)
2011 {
2012 //add the number of tables in this file to the total number to group
2013 numFilesToGroup += it->second.size();
2014 //check the length of all the strings to be written, to determine the max string length to write
2015 if (it->first.size() > maxCharLength)
2016 maxCharLength = it->first.size();
2017 for (vector<string>::const_iterator jt=it->second.begin(); jt != it->second.end(); jt++)
2018 if (jt->size() > maxCharLength)
2019 maxCharLength = jt->size();
2020 }
2021
2022 if (fDebugIsOn)
2023 {
2024 ostringstream str;
2025 str << "There are " << numFilesToGroup << " tables to group";
2026 Debug(str);
2027 }
2028 if (numFilesToGroup <= 1)
2029 {
2030 filesToGroup.clear();
2031 return;
2032 }
2033 const string groupName = CompileFileNameWithPath(fFilePath, "", "fits", runNumber);
2034
2035 Info("Creating FITS group in: "+groupName);
2036
2037 CCfits::Table* groupTable;
2038// const int maxCharLength = FILENAME_MAX;
2039 try
2040 {
2041 groupFile = new CCfits::FITS(groupName, CCfits::RWmode::Write);
2042 //setup the column names
2043 ostringstream pathTypeName;
2044 pathTypeName << maxCharLength << "A";
2045 vector<string> names;
2046 vector<string> dataTypes;
2047 names.push_back("MEMBER_XTENSION");
2048 dataTypes.push_back("8A");
2049 names.push_back("MEMBER_URI_TYPE");
2050 dataTypes.push_back("3A");
2051 names.push_back("MEMBER_LOCATION");
2052 dataTypes.push_back(pathTypeName.str());
2053 names.push_back("MEMBER_NAME");
2054 dataTypes.push_back(pathTypeName.str());
2055 names.push_back("MEMBER_VERSION");
2056 dataTypes.push_back("1J");
2057 names.push_back("MEMBER_POSITION");
2058 dataTypes.push_back("1J");
2059
2060 groupTable = groupFile->addTable("GROUPING", numFilesToGroup, names, dataTypes);
2061//TODO handle the case when the logger was stopped and restarted during the same day, i.e. the grouping file must be updated
2062 }
2063 catch (CCfits::FitsException e)
2064 {
2065 ostringstream str;
2066 str << "Creating FITS table GROUPING in " << groupName << ": " << e.message();
2067 Error(str);
2068 return;
2069 }
2070 try
2071 {
2072 groupTable->addKey("GRPNAME", "FACT_RAW_DATA", "Data from the FACT telescope");
2073 }
2074 catch (CCfits::FitsException e)
2075 {
2076 Error("CCfits::Table::addKey failed for 'GRPNAME' in '"+groupName+"-GROUPING': "+e.message());
2077 return;
2078 }
2079 //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.
2080 //use cfitsio routines instead
2081 groupTable->makeThisCurrent();
2082 //create appropriate buffer.
2083 const unsigned int n = 8 + 3 + 2*maxCharLength + 1 + 8; //+1 for trailling character
2084
2085 vector<unsigned char> realBuffer;
2086 realBuffer.resize(n);
2087 unsigned char* fitsBuffer = &realBuffer[0];
2088 memset(fitsBuffer, 0, n);
2089
2090 char* startOfExtension = reinterpret_cast<char*>(fitsBuffer);
2091 char* startOfURI = reinterpret_cast<char*>(&fitsBuffer[8]);
2092 char* startOfLocation = reinterpret_cast<char*>(&fitsBuffer[8 + 3]);
2093 char* startOfName = reinterpret_cast<char*>(&fitsBuffer[8+3+maxCharLength]);
2094 // char* startOfMemVer = reinterpret_cast<char*>(&fitsBuffer[8+3+2*maxCharLength]);
2095 // char* startOfMemPos = reinterpret_cast<char*>(&fitsBuffer[8+3+2*maxCharLength+1]);
2096
2097 strcpy(startOfExtension, "BINTABLE");
2098 strcpy(startOfURI, "URL");
2099 fitsBuffer[8+3+2*maxCharLength+3] = 1;
2100 fitsBuffer[8+3+2*maxCharLength+7] = 1;
2101
2102 int i=1;
2103 for (map<string, vector<string> >::const_iterator it=filesToGroup.begin(); it!=filesToGroup.end(); it++)
2104 for (vector<string>::const_iterator jt=it->second.begin(); jt != it->second.end(); jt++, i++)
2105 {
2106 strcpy(startOfLocation, it->first.c_str());
2107 strcpy(startOfName, jt->c_str());
2108
2109 if (fDebugIsOn)
2110 {
2111 ostringstream str;
2112 str << "Grouping " << it->first << " " << *jt;
2113 Debug(str);
2114 }
2115
2116 int status = 0;
2117 fits_write_tblbytes(groupFile->fitsPointer(), i, 1, 8+3+2*maxCharLength +8, fitsBuffer, &status);
2118 if (status)
2119 {
2120 char text[30];//max length of cfitsio error strings (from doc)
2121 fits_get_errstatus(status, text);
2122 ostringstream str;
2123 str << "Writing FITS row " << i << " in " << groupName << ": " << text << " (file_write_tblbytes, rc=" << status << ")";
2124 Error(str);
2125 GoToRunWriteErrorState();
2126 delete groupFile;
2127 return;
2128 }
2129 }
2130
2131 filesToGroup.clear();
2132 delete groupFile;
2133}
2134#endif //HAVE_FITS
2135
2136// --------------------------------------------------------------------------
2137//
2138//! Implements the StopRun transition.
2139//! Attempts to close the run file.
2140//! @returns
2141//! kSM_WaitingRun if success, kSM_FatalError otherwise
2142int DataLogger::StopRunLogging()
2143{
2144
2145 if (fDebugIsOn)
2146 {
2147 Debug("Stopping Run Logging...");
2148 }
2149 //it may be that dim tries to write a dimInfo at the same time as we're closing files. Prevent this
2150
2151// dim_lock();
2152 for (list<RunNumberType>::const_iterator it=fRunNumber.begin(); it != fRunNumber.end(); it++)
2153 {
2154#ifdef RUN_LOGS
2155 if (!it->logFile->is_open() || !it->reportFile->is_open())
2156#else
2157 if (!it->reportFile->is_open())
2158#endif
2159 return kSM_FatalError;
2160#ifdef RUN_LOGS
2161 it->logFile->close();
2162 Info("Closed: "+it->logName);
2163
2164#endif
2165 it->reportFile->close();
2166 Info("Closed: "+it->reportName);
2167 }
2168
2169#ifdef HAVE_FITS
2170 for (SubscriptionsListType::iterator i = fServiceSubscriptions.begin(); i != fServiceSubscriptions.end(); i++)
2171 for (map<string, SubscriptionType>::iterator j = i->second.begin(); j != i->second.end(); j++)
2172 {
2173 if (j->second.runFile.IsOpen())
2174 j->second.runFile.Close();
2175 }
2176#endif
2177 NotifyOpenedFile("", 0, fOpenedRunFiles);
2178 if (fNumSubAndFitsIsOn)
2179 fNumSubAndFits->Update();
2180
2181 while (fRunNumber.size() > 0)
2182 {
2183 RemoveOldestRunNumber();
2184 }
2185// dim_unlock();
2186 return kSM_WaitingRun;
2187}
2188// --------------------------------------------------------------------------
2189//
2190//! Implements the Stop and Reset transitions.
2191//! Attempts to close any openned file.
2192//! @returns
2193//! kSM_Ready
2194int DataLogger::GoToReadyPlease()
2195{
2196 if (fDebugIsOn)
2197 {
2198 Debug("Going to the Ready state...");
2199 }
2200 if (GetCurrentState() == kSM_Logging || GetCurrentState() == kSM_WaitingRun)
2201 StopRunLogging();
2202
2203 //it may be that dim tries to write a dimInfo while we're closing files. Prevent that
2204 const string baseFileName = CompileFileNameWithPath(fFilePath, "", "");
2205
2206 if (fNightlyReportFile.is_open())
2207 {
2208 fNightlyReportFile.close();
2209 Info("Closed: "+baseFileName+".rep");
2210 }
2211#ifdef HAVE_FITS
2212 for (SubscriptionsListType::iterator i = fServiceSubscriptions.begin(); i != fServiceSubscriptions.end(); i++)
2213 for (map<string, SubscriptionType>::iterator j = i->second.begin(); j != i->second.end(); j++)
2214 {
2215 if (j->second.nightlyFile.IsOpen())
2216 j->second.nightlyFile.Close();
2217 }
2218#endif
2219 if (GetCurrentState() == kSM_Logging ||
2220 GetCurrentState() == kSM_WaitingRun ||
2221 GetCurrentState() == kSM_NightlyOpen)
2222 {
2223 NotifyOpenedFile("", 0, fOpenedNightlyFiles);
2224 if (fNumSubAndFitsIsOn)
2225 fNumSubAndFits->Update();
2226 }
2227#ifdef HAVE_FITS
2228 CreateFitsGrouping(fOpenedNightlyFits, 0);
2229#endif
2230 return kSM_Ready;
2231}
2232
2233// --------------------------------------------------------------------------
2234//
2235//! Implements the transition towards kSM_WaitingRun
2236//! If current state is kSM_Ready, then tries to go to nightlyOpen state first.
2237//! @returns
2238//! kSM_WaitingRun or kSM_BadFolder
2239int DataLogger::NightlyToWaitRunPlease()
2240{
2241 int cState = GetCurrentState();
2242
2243// if (cState == kSM_Logging)
2244// cState = kSM_NightlyOpen;
2245
2246 if (cState == kSM_Ready)
2247 cState = StartPlease();
2248
2249 if (cState != kSM_NightlyOpen)
2250 return GetCurrentState();
2251
2252 if (fDebugIsOn)
2253 {
2254 Debug("Going to Wait Run Number state...");
2255 }
2256 return kSM_WaitingRun;
2257}
2258// --------------------------------------------------------------------------
2259//
2260//! Implements the transition from wait for run number to nightly open
2261//! Does nothing really.
2262//! @returns
2263//! kSM_WaitingRun
2264int DataLogger::BackToNightlyOpenPlease()
2265{
2266 if (GetCurrentState()==kSM_Logging)
2267 StopRunLogging();
2268
2269 if (fDebugIsOn)
2270 {
2271 Debug("Going to NightlyOpen state...");
2272 }
2273 return kSM_NightlyOpen;
2274}
2275// --------------------------------------------------------------------------
2276//
2277//! Setup Logger's configuration from a Configuration object
2278//! @param conf the configuration object that should be used
2279//!
2280int DataLogger::EvalOptions(Configuration& conf)
2281{
2282 fDebugIsOn = conf.Get<bool>("debug");
2283 fFilesStats.SetDebugMode(fDebugIsOn);
2284
2285 //Set the block or allow list
2286 fBlackList.clear();
2287 fWhiteList.clear();
2288
2289 //Adding entries that should ALWAYS be ignored
2290 fBlackList.insert("DATA_LOGGER/MESSAGE");
2291 fBlackList.insert("/SERVICE_LIST");
2292 fBlackList.insert("DIS_DNS/");
2293
2294 //set the black list, white list and the goruping
2295 const vector<string> vec1 = conf.Vec<string>("block");
2296 const vector<string> vec2 = conf.Vec<string>("allow");
2297 const vector<string> vec3 = conf.Vec<string>("group");
2298
2299 fBlackList.insert(vec1.begin(), vec1.end());
2300 fWhiteList.insert(vec2.begin(), vec2.end());
2301 fGrouping.insert( vec3.begin(), vec3.end());
2302
2303 //set the old run numbers timeout delay
2304 if (conf.Has("run-timeout"))
2305 {
2306 const uint32_t timeout = conf.Get<uint32_t>("run-timeout");
2307 if (timeout == 0)
2308 {
2309 Error("Time out delay for old run numbers must not be 0.");
2310 return 1;
2311 }
2312 fRunNumberTimeout = timeout;
2313 }
2314
2315 //configure the run files directory
2316 if (conf.Has("destination-folder"))
2317 {
2318 const string folder = conf.Get<string>("destination-folder");
2319 if (!fFilesStats.SetCurrentFolder(folder))
2320 return 2;
2321
2322 fFilePath = folder;
2323 fFullNightlyLogFileName = CompileFileNameWithPath(fFilePath, "", "log");
2324 if (!OpenTextFilePlease(fNightlyLogFile, fFullNightlyLogFileName))
2325 return 3;
2326
2327 fNightlyLogFile << endl;
2328 NotifyOpenedFile(fFullNightlyLogFileName, 1, fOpenedNightlyFiles);
2329 for (vector<string>::iterator it=backLogBuffer.begin();it!=backLogBuffer.end();it++)
2330 fNightlyLogFile << *it;
2331 }
2332
2333 shouldBackLog = false;
2334 backLogBuffer.clear();
2335
2336 //configure the interval between statistics updates
2337 if (conf.Has("stats-interval"))
2338 fFilesStats.SetUpdateInterval(conf.Get<int16_t>("stats-interval"));
2339
2340 //configure if the filenames service is on or off
2341 fOpenedFilesIsOn = !conf.Get<bool>("no-filename-service");
2342
2343 //configure if the number of subscriptions and fits files is on or off.
2344 fNumSubAndFitsIsOn = !conf.Get<bool>("no-numsubs-service");
2345 //should we open the daily files at startup ?
2346 if (conf.Has("start-daily-files"))
2347 if (conf.Get<bool>("start-daily-files"))
2348 {
2349 fShouldAutoStart = true;
2350 }
2351 return -1;
2352}
2353
2354
2355#include "Main.h"
2356
2357// --------------------------------------------------------------------------
2358template<class T>
2359int RunShell(Configuration &conf)
2360{
2361 return Main::execute<T, DataLogger>(conf, true);
2362}
2363
2364/*
2365 Extract usage clause(s) [if any] for SYNOPSIS.
2366 Translators: "Usage" and "or" here are patterns (regular expressions) which
2367 are used to match the usage synopsis in program output. An example from cp
2368 (GNU coreutils) which contains both strings:
2369 Usage: cp [OPTION]... [-T] SOURCE DEST
2370 or: cp [OPTION]... SOURCE... DIRECTORY
2371 or: cp [OPTION]... -t DIRECTORY SOURCE...
2372 */
2373void PrintUsage()
2374{
2375 cout << "\n"
2376 "The data logger connects to all available Dim services and "
2377 "writes them to ascii and fits files.\n"
2378 "\n"
2379 "The default is that the program is started without user interaction. "
2380 "All actions are supposed to arrive as DimCommands. Using the -c "
2381 "option, a local shell can be initialized. With h or help a short "
2382 "help message about the usage can be brought to the screen.\n"
2383 "\n"
2384 "Usage: datalogger [-c type] [OPTIONS]\n"
2385 " or: datalogger [OPTIONS]\n";
2386 cout << endl;
2387
2388}
2389// --------------------------------------------------------------------------
2390void PrintHelp()
2391{
2392 /* Additional help text which is printed after the configuration
2393 options goes here */
2394 cout <<
2395 "\n"
2396 "If the allow list has any element, only the servers and/or services "
2397 "specified in the list will be used for subscription. The black list "
2398 "will disable service subscription and has higher priority than the "
2399 "allow list. If the allow list is not present by default all services "
2400 "will be subscribed."
2401 "\n"
2402 "For example, block=DIS_DNS/ will skip all the services offered by "
2403 "the DIS_DNS server, while block=/SERVICE_LIST will skip all the "
2404 "SERVICE_LIST services offered by any server and DIS_DNS/SERVICE_LIST "
2405 "will skip DIS_DNS/SERVICE_LIST.\n"
2406 << endl;
2407
2408 Main::PrintHelp<DataLogger>();
2409}
2410
2411// --------------------------------------------------------------------------
2412void SetupConfiguration(Configuration &conf)
2413{
2414 po::options_description configs("DataLogger options");
2415 configs.add_options()
2416 ("block,b", vars<string>(), "Black-list to block services")
2417 ("allow,a", vars<string>(), "White-list to only allowe certain services")
2418 ("debug,d", po_bool(), "Debug mode. Print clear text of received service reports.")
2419 ("group,g", vars<string>(), "Grouping of services into a single run-Fits")
2420 ("run-timeout", var<uint32_t>(), "Time out delay for old run numbers in milliseconds.")
2421 ("destination-folder", var<string>(), "Base path for the nightly and run files")
2422 ("stats-interval", var<int16_t>(), "Interval in milliseconds for write statistics update")
2423 ("no-filename-service", po_bool(), "Disable update of filename service")
2424 ("no-numsubs-service", po_bool(), "Disable update of number-of-subscriptions service")
2425 ("start-daily-files", po_bool(), "Starts the logger in DailyFileOpen instead of Ready")
2426 ;
2427
2428 conf.AddOptions(configs);
2429}
2430// --------------------------------------------------------------------------
2431int main(int argc, const char* argv[])
2432{
2433 Configuration conf(argv[0]);
2434 conf.SetPrintUsage(PrintUsage);
2435 Main::SetupConfiguration(conf);
2436 SetupConfiguration(conf);
2437
2438 if (!conf.DoParse(argc, argv, PrintHelp))
2439 return -1;
2440
2441// try
2442 {
2443 // No console access at all
2444 if (!conf.Has("console"))
2445 return RunShell<LocalStream>(conf);
2446
2447 // Console access w/ and w/o Dim
2448 if (conf.Get<int>("console")==0)
2449 return RunShell<LocalShell>(conf);
2450 else
2451 return RunShell<LocalConsole>(conf);
2452 }
2453/* catch (exception& e)
2454 {
2455 cerr << "Exception: " << e.what() << endl;
2456 return -1;
2457 }*/
2458
2459 return 0;
2460}
Note: See TracBrowser for help on using the repository browser.