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

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