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

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