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

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