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

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