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

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