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

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