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

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