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

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