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

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