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

Last change on this file since 19438 was 19391, checked in by tbretz, 6 years ago
For convenience print the selected PRESET_OBSERVATORY when the programs start which write the files.
File size: 84.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
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 Time& time=Time()) 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 Time& time) const
834{
835 ostringstream str;
836
837 const Time ftime(time);//removed this as already done by nightAsInt: -boost::posix_time::hours(12));
838 str << ftime.NightAsInt();
839
840 if (!service.empty())
841 str << '.' << service;
842
843 if (!extension.empty())
844 str << "." << extension;
845
846 return str.str();
847}
848
849string DataLogger::CompileFileNameWithPath(const string& path, const string& service, const string& extension)
850{
851 ostringstream str;
852
853 const Time time;
854
855 //calculate time suitable for naming files.
856 //fCurrentDay is 30 minutes after upcoming sunrise. So just use 12 hours before then
857 const Time ftime = fCurrentDay-boost::posix_time::hours(12);
858
859 //output it
860 str << path << ftime.GetAsStr("/%Y/%m/%d");
861
862 //check if target directory exist
863 if (!DoesPathExist(str.str()))
864 CreateDirectory(str.str());
865
866 str << '/' << CompileFileName(service, extension, ftime);//fCurrentDay);
867
868 return str.str();
869
870
871}
872
873// --------------------------------------------------------------------------
874//
875//!retrieves the size on disk of a file
876//! @param fileName the full file name for which the size on disk should be retrieved
877//! @return the size of the file on disk, in bytes. 0 if the file does not exist or if an error occured
878//
879off_t DataLogger::GetFileSize(const string& fileName)
880{
881 return DimWriteStatistics::GetFileSizeOnDisk(fileName, *this);
882}
883
884// --------------------------------------------------------------------------
885//
886//! Removes the oldest run number and closes the fits files that should be closed
887//! Also creates the fits grouping file
888//
889void DataLogger::RemoveOldestRunNumber()
890{
891 if (fDebugIsOn)
892 {
893 ostringstream str;
894 str << "Removing run number " << fRunNumber.front().runNumber;
895 Debug(str);
896 }
897 //remove the entry
898 fRunNumber.pop_front();
899}
900
901// --------------------------------------------------------------------------
902//
903//! Default constructor. The name of the machine is given DATA_LOGGER
904//! and the state is set to kSM_Ready at the end of the function.
905//
906//!Setup the allows states, configs and transitions for the data logger
907//
908DataLogger::DataLogger(ostream &out) : StateMachineDim(out, "DATA_LOGGER"),
909fNightlyLogImp(fNightlyLogFile), fFilesStats("DATA_LOGGER", *this)
910{
911 shouldBackLog = true;
912
913 servicesCounter=1;
914
915 //initialize member data
916 fFilePath = ".";
917
918 fDimList.Subscribe(*this);
919 fDimList.SetCallbackServerAdd(bind(&DataLogger::AddServer, this, placeholders::_1));
920 fDimList.SetCallbackServiceAdd(bind(&DataLogger::AddService, this, placeholders::_1));
921
922 //calculate time "centered" around noon instead of midnight
923 const Time timeNow;
924// const Time nowMinusTwelve = timeNow-boost::posix_time::hours(12);
925 //the "current day" is actually the next closing time of nightly files
926 //the next closing time is 30 minutes after upcoming sunrise.
927 //If we are within 30 minutes after sunrise, closing time is soon
928 fCurrentDay = timeNow.GetNextSunRise();//GetSunRise(timeNow-boost::posix_time::minutes(30))+boost::posix_time::minutes(30);
929 lastFlush = Time();
930
931 //Give a name to this machine's specific states
932 AddStateName(kSM_NightlyOpen, "NightlyFileOpen", "The summary files for the night are open.");
933 AddStateName(kSM_WaitingRun, "WaitForRun", "The summary files for the night are open and we wait for a run to be started.");
934 AddStateName(kSM_Logging, "Logging", "The summary files for the night and the files for a single run are open.");
935 AddStateName(kSM_BadFolder, "ErrInvalidFolder", "The folder for the files is not invalid.");
936 AddStateName(kSM_DailyWriteError, "ErrDailyWrite", "An error occured while writing to a daily (and run) file.");
937 AddStateName(kSM_RunWriteError, "ErrRunWrite", "An error occured while writing to a run file.");
938
939 // Add the possible transitions for this machine
940 AddEvent("START", kSM_Ready, kSM_BadFolder)
941 (bind(&DataLogger::Start, this))
942 ("Start the nightly logging. Nightly file location must be specified already");
943
944 AddEvent("STOP", kSM_NightlyOpen, kSM_WaitingRun, kSM_Logging, kSM_DailyWriteError, kSM_RunWriteError)
945 (bind(&DataLogger::GoToReady, this))
946 ("Stop all data logging, close all files.");
947
948 AddEvent("RESET", kSM_Error, kSM_BadFolder, kSM_DailyWriteError, kSM_RunWriteError)
949 (bind(&DataLogger::GoToReady, this))
950 ("Transition to exit error states. Closes the any open file.");
951
952 AddEvent("START_RUN_LOGGING", /*kSM_Logging,*/ kSM_NightlyOpen, kSM_Ready)
953 (bind(&DataLogger::NightlyToWaitRun, this))
954 ("Go to waiting for run number state. In this state with any received run-number a new file is opened.");
955
956 AddEvent("STOP_RUN_LOGGING", kSM_WaitingRun, kSM_Logging)
957 (bind(&DataLogger::BackToNightlyOpen, this))
958 ("Go from the wait for run to nightly open state.");
959
960 // Provide a print command
961 AddEvent("PRINT_INFO")
962 (bind(&DataLogger::PrintState, this, placeholders::_1))
963 ("Print information about the internal status of the data logger.");
964
965
966 OpenFileToDim fToDim;
967 fToDim.code = 0;
968 fToDim.fileName[0] = '\0';
969
970 fOpenedNightlyFiles = new DimDescribedService(GetName() + "/FILENAME_NIGHTLY", "I:1;C", fToDim,
971 "Path and base name used for the nightly files."
972 "|Type[int]:type of open files (1=log, 2=rep, 4=fits)"
973 "|Name[string]:path and base file name");
974
975 fOpenedRunFiles = new DimDescribedService(GetName() + "/FILENAME_RUN", "I:1;C", fToDim,
976 "Path and base name used for the run files."
977 "|Type[int]:type of open files (1=log, 2=rep, 4=fits)"
978 "|Name[string]:path and base file name");
979
980 fNumSubAndFitsData.numSubscriptions = 0;
981 fNumSubAndFitsData.numOpenFits = 0;
982 fNumSubAndFits = new DimDescribedService(GetName() + "/NUM_SUBS", "I:2", fNumSubAndFitsData,
983 "Num. open files + num. subscribed services"
984 "|NSubAndOpenFiles[int]:Num. of subs and open files");
985
986 //services parameters
987 fDebugIsOn = false;
988 fOpenedFilesIsOn = true;
989 fNumSubAndFitsIsOn = true;
990
991 string emptyString="";
992 //Subscription list service
993 fCurrentSubscription = new DimDescribedService(GetName() + "/SUBSCRIPTIONS", "C", emptyString.c_str(),
994 "List of all the services subscribed by datalogger, except the ones provided by itself."
995 "|Liste[string]:list of logged services and the delay in seconds since last update");
996 fCurrentSubscriptionUpdateRate = 60; //by default, 1 minute between each update
997 fLastSubscriptionUpdate = timeNow;
998
999 // provide services control commands
1000 AddEvent("SET_DEBUG_MODE", "B:1", kSM_NightlyOpen, kSM_Logging, kSM_WaitingRun, kSM_Ready)
1001 (bind(&DataLogger::SetDebugOnOff, this, placeholders::_1))
1002 ("Switch debug mode on or off. Debug mode prints information about every service written to a file."
1003 "|Enable[bool]:Enable of disable debug mode (yes/no).");
1004
1005 AddEvent("SET_STATISTICS_UPDATE_INTERVAL", "S:1", kSM_NightlyOpen, kSM_Logging, kSM_WaitingRun, kSM_Ready)
1006 (bind(&DataLogger::SetStatsPeriod, this, placeholders::_1))
1007 ("Interval in which the data-logger statistics service (STATS) is updated."
1008 "|Interval[ms]:Value in milliseconds (<=0: no update).");
1009
1010 AddEvent("ENABLE_FILENAME_SERVICES", "B:1", kSM_NightlyOpen, kSM_Logging, kSM_WaitingRun, kSM_Ready)
1011 (bind(&DataLogger::SetOpenedFilesOnOff ,this, placeholders::_1))
1012 ("Switch service which distributes information about the open files on or off."
1013 "|Enable[bool]:Enable of disable filename services (yes/no).");
1014
1015 AddEvent("ENABLE_NUMSUBS_SERVICE", "B:1", kSM_NightlyOpen, kSM_Logging, kSM_WaitingRun, kSM_Ready)
1016 (bind(&DataLogger::SetNumSubsAndFitsOnOff, this, placeholders::_1))
1017 ("Switch the service which distributes information about the number of subscriptions and open files on or off."
1018 "|Enable[bool]:Enable of disable NUM_SUBS service (yes/no).");
1019
1020 AddEvent("SET_RUN_TIMEOUT", "L:1", kSM_Ready, kSM_NightlyOpen, kSM_Logging, kSM_WaitingRun)
1021 (bind(&DataLogger::SetRunTimeoutDelay, this, placeholders::_1))
1022 ("Set the timeout delay for old run numbers."
1023 "|timeout[min]:Time out in minutes after which files for expired runs are closed.");
1024 //Provide access to the duration between two updates of the service list
1025 AddEvent("SET_SERVICE_LIST_UPDATE_INTERVAL", "I:1", kSM_Ready, kSM_NightlyOpen, kSM_Logging, kSM_WaitingRun)
1026 (bind(&DataLogger::setSubscriptionListUpdateTimeLapse, this, placeholders::_1))
1027 ("Set the min interval between two services-list updates."
1028 "|duration[sec]:The interval between two updates, in seconds.");
1029
1030 fDestructing = false;
1031
1032 fPreviousOldRunNumberCheck = Time();
1033
1034 fDailyFileDayChangedAlready = true;
1035 fRunNumberTimeout = 60000; //default run-timeout set to 1 minute
1036 fRunNumber.push_back(RunNumberType());
1037 fRunNumber.back().runNumber = -1;
1038 fRunNumber.back().time = Time();
1039 NotifyOpenedFile("", 0, fOpenedNightlyFiles);
1040 NotifyOpenedFile("", 0, fOpenedRunFiles);
1041
1042 fRunNumberService = 0;
1043
1044 fShouldAutoStart = false;
1045 fAutoStarted = false;
1046
1047
1048 if(fDebugIsOn)
1049 {
1050 Debug("DataLogger Init Done.");
1051 }
1052}
1053
1054// --------------------------------------------------------------------------
1055//
1056//! Destructor
1057//
1058DataLogger::~DataLogger()
1059{
1060 if (fDebugIsOn)
1061 Debug("DataLogger destruction starts");
1062
1063 //this boolean should not be required anymore
1064 fDestructing = true;
1065
1066 //now clear the services subscriptions
1067 dim_lock();
1068 fServiceSubscriptions.clear();
1069 dim_unlock();
1070
1071 //clear any remaining run number (should remain only one)
1072 while (fRunNumber.size() > 0)
1073 {
1074 RemoveOldestRunNumber();
1075 }
1076 //go to the ready state. i.e. close all files, run-wise first
1077 GoToReady();
1078
1079 Info("Will soon close the daily log file");
1080
1081 delete fOpenedNightlyFiles;
1082 delete fOpenedRunFiles;
1083 delete fNumSubAndFits;
1084 delete fCurrentSubscription;
1085
1086 if (fNightlyLogFile.is_open())//this file is the only one that has not been closed by GoToReady
1087 {
1088 fNightlyLogFile << endl;
1089 fNightlyLogFile.close();
1090 }
1091 if (!fNightlyLogFile.is_open())
1092 Info("Daily log file was closed indeed");
1093 else
1094 Warn("Seems like there was a problem while closing the daily log file.");
1095 for (auto it=fServerDescriptionsList.begin(); it!= fServerDescriptionsList.end(); it++)
1096 delete *it;
1097
1098 if (fDebugIsOn)
1099 Debug("DataLogger desctruction ends");
1100}
1101
1102// --------------------------------------------------------------------------
1103//
1104//! checks if old run numbers should be trimmed and if so, do it
1105//
1106void DataLogger::TrimOldRunNumbers()
1107{
1108 const Time cTime = Time();
1109
1110 if (cTime - fPreviousOldRunNumberCheck < boost::posix_time::milliseconds(fRunNumberTimeout))
1111 return;
1112
1113 while (fRunNumber.size() > 1 && (cTime - fRunNumber.back().time) > boost::posix_time::milliseconds(fRunNumberTimeout))
1114 {
1115 RemoveOldestRunNumber();
1116 }
1117 fPreviousOldRunNumberCheck = cTime;
1118}
1119// --------------------------------------------------------------------------
1120//
1121//! Inherited from DimInfo. Handles all the Infos to which we subscribed, and log them
1122//
1123int DataLogger::infoCallback(const EventImp& evt, unsigned int subIndex)
1124{
1125// if (fDebugIsOn)
1126// {
1127// ostringstream str;
1128// str << "Got infoCallback called with service index= " << subIndex;
1129// Debug(str.str());
1130// }
1131
1132 if ((GetCurrentState() == kSM_Ready) && (!fAutoStarted) && fShouldAutoStart)
1133 {
1134 fAutoStarted = true;
1135 SetCurrentState(Start(), "infoCallback");
1136// SetCurrentState(NightlyToWaitRun());
1137 }
1138 else
1139 {
1140 if (GetCurrentState() > kSM_Ready)
1141 fAutoStarted = true;
1142 }
1143
1144
1145 //check if the service pointer corresponds to something that we subscribed to
1146 //this is a fix for a bug that provides bad Infos when a server starts
1147 bool found = false;
1148 SubscriptionsListType::iterator x;
1149 map<string, SubscriptionType>::iterator y;
1150 for (x=fServiceSubscriptions.begin(); x != fServiceSubscriptions.end(); x++)
1151 {//find current service is subscriptions
1152 //Edit: this should be useless now... remove it sometimes ?
1153 for (y=x->second.begin(); y!=x->second.end();y++)
1154 if (y->second.index == subIndex)
1155 {
1156 found = true;
1157 break;
1158 }
1159 if (found)
1160 break;
1161 }
1162
1163 if (!found && fDebugIsOn)
1164 {
1165 ostringstream str;
1166 str << "Service " << evt.GetName() << " not found in subscriptions" << endl;
1167 Debug(str.str());
1168 }
1169 if (!found)
1170 return GetCurrentState();
1171
1172
1173 if (evt.GetSize() == 0 && fDebugIsOn)
1174 {
1175 ostringstream str;
1176 str << "Got 0 size for " << evt.GetName() << endl;
1177 Debug(str.str());
1178 }
1179 if (evt.GetSize() == 0)
1180 return GetCurrentState();
1181
1182 if (evt.GetFormat() == "" && fDebugIsOn)
1183 {
1184 ostringstream str;
1185 str << "Got no format for " << evt.GetName() << endl;
1186 Debug(str.str());
1187 }
1188 if (evt.GetFormat() == "")
1189 return GetCurrentState();
1190
1191// cout.precision(20);
1192// cout << "Orig timestamp: " << Time(I->getTimestamp(), I->getTimestampMillisecs()*1000).Mjd() << endl;
1193 // FIXME: Here we have to check if we have received the
1194 // service with the run-number.
1195 // CheckForRunNumber(I); has been removed because we have to
1196 // subscribe to this service anyway and hence we have the pointer
1197 // (no need to check for the name)
1198 CheckForRunNumber(evt, subIndex);
1199
1200 Report(evt, y->second);
1201
1202 //remove old run numbers
1203 TrimOldRunNumbers();
1204
1205 return GetCurrentState();
1206}
1207
1208// --------------------------------------------------------------------------
1209//
1210//! Add a new active run number
1211//! @param newRun the new run number
1212//! @param time the time at which the new run number was issued
1213//
1214void DataLogger::AddNewRunNumber(int64_t newRun, Time time)
1215{
1216
1217 if (newRun > 0xffffffff)
1218 {
1219 Error("New run number too large, out of range. Ignoring.");
1220 return;
1221 }
1222 for (std::vector<int64_t>::const_iterator it=previousRunNumbers.begin(); it != previousRunNumbers.end(); it++)
1223 {
1224 if (*it == newRun)
1225 {
1226 Error("Newly provided run number has already been used (or is still in use). Going to error state");
1227 SetCurrentState(kSM_BadFolder, "AddNewRunNumber");
1228 return;
1229 }
1230 }
1231 if (fDebugIsOn)
1232 {
1233 ostringstream str;
1234 str << "Adding new run number " << newRun << " issued at " << time;
1235 Debug(str);
1236 }
1237 //Add new run number to run number list
1238 fRunNumber.push_back(RunNumberType());
1239 fRunNumber.back().runNumber = int32_t(newRun);
1240 fRunNumber.back().time = time;
1241
1242 if (fDebugIsOn)
1243 {
1244 ostringstream str;
1245 str << "The new run number is: " << fRunNumber.back().runNumber;
1246 Debug(str);
1247 }
1248 if (GetCurrentState() != kSM_Logging && GetCurrentState() != kSM_WaitingRun )
1249 return;
1250
1251 if (newRun > 0 && GetCurrentState() == kSM_WaitingRun)
1252 SetCurrentState(kSM_Logging, "AddNewRunNumber");
1253 if (newRun < 0 && GetCurrentState() == kSM_Logging)
1254 SetCurrentState(kSM_WaitingRun, "AddNewRunNumber");
1255}
1256// --------------------------------------------------------------------------
1257//
1258//! Checks whether or not the current info is a run number.
1259//! If so, then remember it. A run number is required to open the run-log file
1260//! @param I
1261//! the current DimInfo
1262//
1263void DataLogger::CheckForRunNumber(const EventImp& evt, unsigned int index)
1264{
1265 if (index != fRunNumberService)
1266 return;
1267// int64_t newRun = reinterpret_cast<const uint64_t*>(evt.GetData())[0];
1268 AddNewRunNumber(evt.GetXtra(), evt.GetTime());
1269}
1270// --------------------------------------------------------------------------
1271//
1272//! Get SunRise. Copied from drivectrl.cc
1273//! Used to know when to close and reopen files
1274//!
1275/*
1276Time DataLogger::GetSunRise(const Time &time)
1277{
1278#ifdef HAVE_NOVA
1279 const double lon = -(17.+53./60+26.525/3600);
1280 const double lat = 28.+45./60+42.462/3600;
1281
1282 ln_lnlat_posn observer;
1283 observer.lng = lon;
1284 observer.lat = lat;
1285
1286 // This caluclates the sun-rise of the next day after 12:00 noon
1287 ln_rst_time sun_day;
1288 if (ln_get_solar_rst(time.JD(), &observer, &sun_day)==1)
1289 {
1290 Fatal("GetSunRise reported the sun to be circumpolar!");
1291 return Time(Time::none);
1292 }
1293
1294 if (Time(sun_day.rise)>=time)
1295 return Time(sun_day.rise);
1296
1297 if (ln_get_solar_rst(time.JD()+0.5, &observer, &sun_day)==1)
1298 {
1299 Fatal("GetSunRise reported the sun to be circumpolar!");
1300 return Time(Time::none);
1301 }
1302
1303 return Time(sun_day.rise);
1304#else
1305 return time;
1306#endif
1307}
1308*/
1309// --------------------------------------------------------------------------
1310//
1311//! write infos to log files.
1312//! @param I
1313//! The current DimInfo
1314//! @param sub
1315//! The dataLogger's subscription corresponding to this DimInfo
1316//
1317void DataLogger::Report(const EventImp& evt, SubscriptionType& sub)
1318{
1319 const string fmt(evt.GetFormat());
1320
1321 const bool isItaReport = fmt!="C";
1322
1323 if (!fNightlyLogFile.is_open())
1324 return;
1325
1326 if (fDebugIsOn && string(evt.GetName())!="DATA_LOGGER/MESSAGE")
1327 {
1328 ostringstream str;
1329 str << "Logging " << evt.GetName() << " [" << evt.GetFormat() << "] (" << evt.GetSize() << ")";
1330 Debug(str);
1331 }
1332
1333 //
1334 // Check whether we should close and reopen daily text files or not
1335 // calculate time "centered" around noon instead of midnight
1336 // if number of days has changed, then files should be closed and reopenned.
1337 const Time timeNow;
1338// const Time nowMinusTwelve = timeNow-boost::posix_time::hours(12);
1339// int newDayNumber = (int)(nowMinusTwelve.Mjd());
1340
1341 //also check if we should flush the nightly files
1342 if (lastFlush < timeNow-boost::posix_time::minutes(1))
1343 {
1344 lastFlush = timeNow;
1345 SubscriptionsListType::iterator x;
1346 map<string, SubscriptionType>::iterator y;
1347 for (x=fServiceSubscriptions.begin(); x != fServiceSubscriptions.end(); x++)
1348 {//find current service is subscriptions
1349 for (y=x->second.begin(); y!=x->second.end();y++)
1350 if (y->second.nightlyFile.IsOpen())
1351 {
1352 y->second.nightlyFile.Flush();
1353 }
1354 }
1355 if (fDebugIsOn)
1356 Debug("Just flushed nightly fits files to the disk");
1357 }
1358 //check if we should close and reopen the nightly files
1359 if (timeNow > fCurrentDay)//GetSunRise(fCurrentDay)+boost::posix_time::minutes(30)) //if we went past 30 minutes after sunrise
1360 {
1361 //set the next closing time. If we are here, we have passed 30 minutes after sunrise.
1362 fCurrentDay = timeNow.GetNextSunRise();//GetSunRise(timeNow-boost::posix_time::minutes(30))+boost::posix_time::minutes(30);
1363 //crawl through the subcriptions and close any open nightly file
1364 SubscriptionsListType::iterator x;
1365 map<string, SubscriptionType>::iterator y;
1366 for (x=fServiceSubscriptions.begin(); x != fServiceSubscriptions.end(); x++)
1367 {//find current service is subscriptions
1368 for (y=x->second.begin(); y!=x->second.end();y++)
1369 {
1370 if (y->second.nightlyFile.IsOpen())
1371 {
1372 y->second.nightlyFile.Close();
1373 }
1374 y->second.increment = 0;
1375 }
1376 }
1377
1378 if (fDebugIsOn)
1379 Debug("Day have changed! Closing and reopening nightly files");
1380
1381 fNightlyLogFile << endl;
1382 fNightlyLogFile.close();
1383// fNightlyReportFile.close();
1384
1385 Info("Closed: "+fFullNightlyLogFileName);
1386// Info("Closed: "+fFullNightlyReportFileName);
1387
1388 fFullNightlyLogFileName = CompileFileNameWithPath(fFilePath, "", "log");
1389 if (!OpenTextFile(fNightlyLogFile, fFullNightlyLogFileName))
1390 {
1391 GoToReady();
1392 SetCurrentState(kSM_BadFolder, "Report");
1393 return;
1394 }
1395 fNightlyLogFile << endl;
1396
1397// fFullNightlyReportFileName = CompileFileNameWithPath(fFilePath, "", "rep");
1398// if (!OpenTextFile(fNightlyReportFile, fFullNightlyReportFileName))
1399// {
1400// GoToReady();
1401// SetCurrentState(kSM_BadFolder, "Report");
1402// return;
1403// }
1404 }
1405 //create the converter for that service
1406 if (!sub.fConv)
1407 {
1408 sub.fConv = shared_ptr<Converter>(new Converter(Out(), evt.GetFormat()));
1409 if (!sub.fConv->valid())
1410 {
1411 ostringstream str;
1412 str << "Couldn't properly parse the format... service " << evt.GetName() << " ignored.";
1413 Error(str);
1414 return;
1415 }
1416 }
1417 //construct the header
1418 ostringstream header;
1419 const Time cTime(evt.GetTime());
1420 fQuality = evt.GetQoS();
1421
1422 //update subscription last received time
1423 sub.lastReceivedEvent = cTime;
1424 //update subscription list service if required
1425 updateSubscriptionList();
1426
1427 fMjD = cTime.Mjd() ? cTime.Mjd()-40587 : 0;
1428
1429 if (isItaReport)
1430 {
1431//DISABLED REPORT WRITING BY THOMAS REQUEST
1432 //write text header
1433/* string serviceName = (sub.service == "MESSAGE") ? "" : "_"+sub.service;
1434 header << sub.server << serviceName << " " << fQuality << " ";
1435 header << evt.GetTime() << " ";
1436
1437 string text;
1438 try
1439 {
1440 text = sub.fConv->GetString(evt.GetData(), evt.GetSize());
1441 }
1442 catch (const runtime_error &e)
1443 {
1444 ostringstream str;
1445 str << "Parsing service " << evt.GetName();
1446 str << " failed: " << e.what() << " removing the subscription to " << sub.server << "/" << sub.service;
1447 Warn(str);
1448 //remove this subscription from the list.
1449 //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 !
1450 RemoveService(sub.server, sub.service, false);
1451 return;
1452 }
1453
1454 if (text.empty())
1455 {
1456 ostringstream str;
1457 str << "Service " << evt.GetName() << " sent an empty string";
1458 Info(str);
1459 return;
1460 }
1461 //replace bizarre characters by white space
1462 replace(text.begin(), text.end(), '\n', '\\');
1463 replace_if(text.begin(), text.end(), ptr_fun<int, int>(&iscntrl), ' ');
1464
1465 //write entry to Nightly report
1466 if (fNightlyReportFile.is_open())
1467 {
1468 fNightlyReportFile << header.str() << text << endl;
1469 if (!CheckForOfstreamError(fNightlyReportFile, true))
1470 return;
1471 }
1472*/
1473#ifdef HAVE_FITS
1474 //check if the last received event was before noon and if current one is after noon.
1475 //if so, close the file so that it gets reopened.
1476// sub.lastReceivedEvent = cTime;
1477 if (!sub.nightlyFile.IsOpen())
1478 if (GetCurrentState() != kSM_Ready)
1479 OpenFITSFiles(sub);
1480 WriteToFITS(sub, evt.GetData());
1481#endif
1482 }
1483 else
1484 {//write entry to Nightly log
1485 vector<string> strings;
1486 try
1487 {
1488 strings = sub.fConv->ToStrings(evt.GetData());
1489 }
1490 catch (const runtime_error &e)
1491 {
1492 ostringstream str;
1493 str << "Parsing service " << evt.GetName();
1494 str << " failed: " << e.what() << " removing the subscription for now.";
1495 Error(str);
1496 //remove this subscription from the list.
1497 //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 !
1498 RemoveService(sub.server, sub.service, false);
1499 return;
1500 }
1501 if (strings.size() > 1)
1502 {
1503 ostringstream err;
1504 err << "There was more than one string message in service " << evt.GetName() << " going to fatal error state";
1505 Error(err.str());
1506 }
1507
1508 bool isMessage = (sub.service == "MESSAGE");
1509 ostringstream msg;
1510 string serviceName = isMessage ? "" : "_"+sub.service;
1511 msg << sub.server << serviceName;
1512
1513
1514 //in case of non messages message (i.e. binary data written to logs)
1515 //we override the quality before writing to .log, otherwise it will wrongly decorate the log entry
1516 //because fQuality is really the system state in some cases.
1517 //so save a backup of the original value before writing to fits
1518 int backup_quality = fQuality;
1519
1520 //fix the quality of non message "messages"
1521 if (!isMessage)
1522 {
1523 msg << "[" << fQuality << "]";
1524 fQuality = kMessage;
1525 }
1526
1527 //special case for alarm reset
1528 if (isMessage && (fQuality == kAlarm) && (strings[0] == ""))
1529 {
1530 fQuality = kInfo;
1531 strings[0] = "Alarm reset";
1532 }
1533 msg << ": " << strings[0];
1534
1535 if (fNightlyLogFile.is_open())
1536 {
1537 fNightlyLogImp.Write(cTime, msg.str().c_str(), fQuality);
1538 if (!CheckForOfstreamError(fNightlyLogFile, true))
1539 return;
1540 }
1541
1542 //in case we have overriden the fQuality before writing to log, restore the original value before writing to FITS
1543 if (!isMessage)
1544 fQuality = backup_quality;
1545
1546// sub.lastReceivedEvent = cTime;
1547 if (!sub.nightlyFile.IsOpen())
1548 if (GetCurrentState() != kSM_Ready)
1549 OpenFITSFiles(sub);
1550 WriteToFITS(sub, evt.GetData());
1551 }
1552}
1553
1554// --------------------------------------------------------------------------
1555//
1556//! print the dataLogger's current state. invoked by the PRINT command
1557//! @param evt
1558//! the current event. Not used by the method
1559//! @returns
1560//! the new state. Which, in that case, is the current state
1561//!
1562int DataLogger::PrintState(const Event& )
1563{
1564 Message("------------------------------------------");
1565 Message("------- DATA LOGGER CURRENT STATE --------");
1566 Message("------------------------------------------");
1567
1568 //print the path configuration
1569#if BOOST_VERSION < 104600
1570 Message("File path: " + boost::filesystem::system_complete(boost::filesystem::path(fFilePath)).directory_string());
1571#else
1572 Message("File path: " + boost::filesystem::system_complete(boost::filesystem::path(fFilePath)).parent_path().string());
1573#endif
1574
1575 //print active run numbers
1576 ostringstream str;
1577 //timeout value
1578 str << "Timeout delay for old run numbers: " << fRunNumberTimeout << " ms";
1579 Message(str);
1580 str.str("");
1581 str << "Active Run Numbers:";
1582 for (list<RunNumberType>::const_iterator it=fRunNumber.begin(); it!=fRunNumber.end(); it++)
1583 str << " " << it->runNumber;
1584 if (fRunNumber.empty())
1585 str << " <none>";
1586 Message(str);
1587
1588 //print all the open files.
1589 Message("------------ OPEN FILES ----------------");
1590 if (fNightlyLogFile.is_open())
1591 Message("Nightly log-file: "+fFullNightlyLogFileName);
1592
1593// if (fNightlyReportFile.is_open())
1594 // Message("Nightly report-file: "+fFullNightlyReportFileName);
1595
1596 const DimWriteStatistics::Stats statVar = fFilesStats.GetTotalSizeWritten();
1597 // /*const bool statWarning =*/ calculateTotalSizeWritten(statVar, true);
1598#ifdef HAVE_FITS
1599 str.str("");
1600 str << "Number of open FITS files: " << fNumSubAndFitsData.numOpenFits;
1601 Message(str);
1602 // FIXME: Print list of open FITS files
1603#else
1604 Message("FITS output disabled at compilation");
1605#endif
1606 Message("----------------- STATS ------------------");
1607 if (fFilesStats.GetUpdateInterval()>0)
1608 {
1609 str.str("");
1610 str << "Statistics are updated every " << fFilesStats.GetUpdateInterval() << " ms";
1611 Message(str);
1612 }
1613 else
1614 Message("Statistics updates are currently disabled.");
1615 str.str("");
1616 str << "Total Size written: " << statVar.sizeWritten/1000 << " kB";
1617 Message(str);
1618 str.str("");
1619 str << "Disk free space: " << statVar.freeSpace/1000000 << " MB";
1620 Message(str);
1621
1622 Message("------------ DIM SUBSCRIPTIONS -----------");
1623 str.str("");
1624 str << "There are " << fNumSubAndFitsData.numSubscriptions << " active DIM subscriptions.";
1625 Message(str);
1626 for (map<const string, map<string, SubscriptionType> >::const_iterator it=fServiceSubscriptions.begin(); it!= fServiceSubscriptions.end();it++)
1627 {
1628 Message("Server "+it->first);
1629 for (map<string, SubscriptionType>::const_iterator it2=it->second.begin(); it2!=it->second.end(); it2++)
1630 Message(" -> "+it2->first);
1631 }
1632 Message("--------------- BLOCK LIST ---------------");
1633 for (set<string>::const_iterator it=fBlackList.begin(); it != fBlackList.end(); it++)
1634 Message(" -> "+*it);
1635 if (fBlackList.empty())
1636 Message(" <empty>");
1637
1638 Message("--------------- ALLOW LIST ---------------");
1639 for (set<string>::const_iterator it=fWhiteList.begin(); it != fWhiteList.end(); it++)
1640 Message(" -> "+*it);
1641 if (fWhiteList.empty())
1642 Message(" <empty>");
1643
1644 Message("-------------- GROUPING LIST -------------");
1645 Message("The following servers and/or services will");
1646 Message("be grouped into a single fits file:");
1647 for (set<string>::const_iterator it=fGrouping.begin(); it != fGrouping.end(); it++)
1648 Message(" -> "+*it);
1649 if (fGrouping.empty())
1650 Message(" <no grouping>");
1651
1652 Message("------------------------------------------");
1653 Message("-------- END OF DATA LOGGER STATE --------");
1654 Message("------------------------------------------");
1655
1656 return GetCurrentState();
1657}
1658
1659// --------------------------------------------------------------------------
1660//
1661//! turn debug mode on and off
1662//! @param evt
1663//! the current event. contains the instruction string: On, Off, on, off, ON, OFF, 0 or 1
1664//! @returns
1665//! the new state. Which, in that case, is the current state
1666//!
1667int DataLogger::SetDebugOnOff(const Event& evt)
1668{
1669 const bool backupDebug = fDebugIsOn;
1670
1671 fDebugIsOn = evt.GetBool();
1672
1673 if (fDebugIsOn == backupDebug)
1674 Message("Debug mode was already in the requested state.");
1675
1676 ostringstream str;
1677 str << "Debug mode is now " << fDebugIsOn;
1678 Message(str);
1679
1680 fFilesStats.SetDebugMode(fDebugIsOn);
1681
1682 return GetCurrentState();
1683}
1684// --------------------------------------------------------------------------
1685//
1686//! set the statistics update period duration. 0 disables the statistics
1687//! @param evt
1688//! the current event. contains the new duration.
1689//! @returns
1690//! the new state. Which, in that case, is the current state
1691//!
1692int DataLogger::SetStatsPeriod(const Event& evt)
1693{
1694 fFilesStats.SetUpdateInterval(evt.GetShort());
1695 return GetCurrentState();
1696}
1697// --------------------------------------------------------------------------
1698//
1699//! set the opened files service on or off.
1700//! @param evt
1701//! the current event. contains the instruction string. similar to setdebugonoff
1702//! @returns
1703//! the new state. Which, in that case, is the current state
1704//!
1705int DataLogger::SetOpenedFilesOnOff(const Event& evt)
1706{
1707 const bool backupOpened = fOpenedFilesIsOn;
1708
1709 fOpenedFilesIsOn = evt.GetBool();
1710
1711 if (fOpenedFilesIsOn == backupOpened)
1712 Message("Opened files service mode was already in the requested state.");
1713
1714 ostringstream str;
1715 str << "Opened files service mode is now " << fOpenedFilesIsOn;
1716 Message(str);
1717
1718 return GetCurrentState();
1719}
1720
1721// --------------------------------------------------------------------------
1722//
1723//! set the number of subscriptions and opened fits on and off
1724//! @param evt
1725//! the current event. contains the instruction string. similar to setdebugonoff
1726//! @returns
1727//! the new state. Which, in that case, is the current state
1728//!
1729int DataLogger::SetNumSubsAndFitsOnOff(const Event& evt)
1730{
1731 const bool backupSubs = fNumSubAndFitsIsOn;
1732
1733 fNumSubAndFitsIsOn = evt.GetBool();
1734
1735 if (fNumSubAndFitsIsOn == backupSubs)
1736 Message("Number of subscriptions service mode was already in the requested state");
1737
1738 ostringstream str;
1739 str << "Number of subscriptions service mode is now " << fNumSubAndFitsIsOn;
1740 Message(str);
1741
1742 return GetCurrentState();
1743}
1744// --------------------------------------------------------------------------
1745//
1746//! set the timeout delay for old run numbers
1747//! @param evt
1748//! the current event. contains the timeout delay long value
1749//! @returns
1750//! the new state. Which, in that case, is the current state
1751//!
1752int DataLogger::SetRunTimeoutDelay(const Event& evt)
1753{
1754 if (evt.GetUInt() == 0)
1755 {
1756 Error("Timeout delays for old run numbers must be greater than 0... ignored.");
1757 return GetCurrentState();
1758 }
1759
1760 if (fRunNumberTimeout == evt.GetUInt())
1761 Message("New timeout for old run numbers is same value as previous one.");
1762
1763 fRunNumberTimeout = evt.GetUInt();
1764
1765 ostringstream str;
1766 str << "Timeout delay for old run numbers is now " << fRunNumberTimeout << " ms";
1767 Message(str);
1768
1769 return GetCurrentState();
1770}
1771
1772// --------------------------------------------------------------------------
1773//
1774//! Notifies the DIM service that a particular file was opened
1775//! @ param name the base name of the opened file, i.e. without path nor extension.
1776//! WARNING: use string instead of string& because I pass values that do not convert to string&.
1777//! this is not a problem though because file are not opened so often.
1778//! @ param type the type of the opened file. 0 = none open, 1 = log, 2 = text, 4 = fits
1779inline void DataLogger::NotifyOpenedFile(const string &name, int type, DimDescribedService* service)
1780{
1781 if (!fOpenedFilesIsOn)
1782 return;
1783
1784 if (fDebugIsOn)
1785 {
1786 ostringstream str;
1787 str << "Updating " << service->getName() << " file '" << name << "' (type=" << type << ")";
1788 Debug(str);
1789
1790 str.str("");
1791 str << "Num subscriptions: " << fNumSubAndFitsData.numSubscriptions << " Num open FITS files: " << fNumSubAndFitsData.numOpenFits;
1792 Debug(str);
1793 }
1794
1795 if (name.size()+1 > FILENAME_MAX)
1796 {
1797 Error("Provided file name '" + name + "' is longer than allowed file name length.");
1798 return;
1799 }
1800
1801 OpenFileToDim fToDim;
1802 fToDim.code = type;
1803 memcpy(fToDim.fileName, name.c_str(), name.size()+1);
1804
1805 service->setData(reinterpret_cast<void*>(&fToDim), name.size()+1+sizeof(uint32_t));
1806 service->setQuality(0);
1807 service->Update();
1808}
1809// --------------------------------------------------------------------------
1810//
1811//! Implements the Start transition.
1812//! Concatenates the given path for the Nightly file and the filename itself (based on the day),
1813//! and tries to open it.
1814//! @returns
1815//! kSM_NightlyOpen if success, kSM_BadFolder if failure
1816int DataLogger::Start()
1817{
1818 if (fDebugIsOn)
1819 {
1820 Debug("Starting...");
1821 }
1822 fFullNightlyLogFileName = CompileFileNameWithPath(fFilePath, "", "log");
1823 bool nightlyLogOpen = fNightlyLogFile.is_open();
1824 if (!OpenTextFile(fNightlyLogFile, fFullNightlyLogFileName))
1825 return kSM_BadFolder;
1826 if (!nightlyLogOpen)
1827 fNightlyLogFile << endl;
1828
1829// fFullNightlyReportFileName = CompileFileNameWithPath(fFilePath, "", "rep");
1830// if (!OpenTextFile(fNightlyReportFile, fFullNightlyReportFileName))
1831// {
1832// fNightlyLogFile.close();
1833// Info("Closed: "+fFullNightlyReportFileName);
1834// return kSM_BadFolder;
1835// }
1836
1837 fFilesStats.FileOpened(fFullNightlyLogFileName);
1838// fFilesStats.FileOpened(fFullNightlyReportFileName);
1839 //notify that a new file has been opened.
1840 const string baseFileName = CompileFileNameWithPath(fFilePath, "", "");
1841 NotifyOpenedFile(baseFileName, 3, fOpenedNightlyFiles);
1842
1843 fOpenedNightlyFits.clear();
1844
1845 return kSM_NightlyOpen;
1846}
1847
1848#ifdef HAVE_FITS
1849// --------------------------------------------------------------------------
1850//
1851//! open if required a the FITS files corresponding to a given subscription
1852//! @param sub
1853//! the current DimInfo subscription being examined
1854void DataLogger::OpenFITSFiles(SubscriptionType& sub)
1855{
1856 string serviceName(sub.server + "_" + sub.service);//evt.GetName());
1857
1858 for (unsigned int i=0;i<serviceName.size(); i++)
1859 {
1860 if (serviceName[i] == '/')
1861 {
1862 serviceName[i] = '_';
1863 break;
1864 }
1865 }
1866 //we open the NightlyFile anyway, otherwise this function shouldn't have been called.
1867 if (!sub.nightlyFile.IsOpen())
1868 {
1869 string incrementedServiceName = serviceName;
1870 if (sub.increment != 0)
1871 {
1872 ostringstream str;
1873 str << "." << sub.increment;
1874 incrementedServiceName += str.str();
1875 }
1876 const string partialName = CompileFileNameWithPath(fFilePath, incrementedServiceName, "fits");
1877
1878 const string fileNameOnly = partialName.substr(partialName.find_last_of('/')+1, partialName.size());
1879 if (!sub.fitsBufferAllocated)
1880 AllocateFITSBuffers(sub);
1881 //get the size of the file we're about to open
1882 if (fFilesStats.FileOpened(partialName))
1883 fOpenedNightlyFits[fileNameOnly].push_back(serviceName);
1884
1885 if (!sub.nightlyFile.Open(partialName, serviceName, &fNumSubAndFitsData.numOpenFits, this, 0))
1886 {
1887 GoToRunWriteErrorState();
1888 return;
1889 }
1890
1891 ostringstream str;
1892 str << "Opened: " << partialName << " (Nfits=" << fNumSubAndFitsData.numOpenFits << ")";
1893 Info(str);
1894
1895 //notify the opening
1896 const string baseFileName = CompileFileNameWithPath(fFilePath, "", "");
1897 NotifyOpenedFile(baseFileName, 7, fOpenedNightlyFiles);
1898 if (fNumSubAndFitsIsOn)
1899 fNumSubAndFits->Update();
1900 }
1901
1902}
1903// --------------------------------------------------------------------------
1904//
1905//! Allocates the required memory for a given pair of fits files (nightly and run)
1906//! @param sub the subscription of interest.
1907//
1908void DataLogger::AllocateFITSBuffers(SubscriptionType& sub)
1909{
1910 //Init the time columns of the file
1911 Description dateDesc(string("Time"), string("Modified Julian Date"), string("MJD"));
1912 sub.nightlyFile.AddStandardColumn(dateDesc, "1D", &fMjD, sizeof(double));
1913
1914 Description QoSDesc("QoS", "Quality of service", "");
1915 sub.nightlyFile.AddStandardColumn(QoSDesc, "1J", &fQuality, sizeof(int));
1916
1917 // Compilation failed
1918 if (!sub.fConv->valid())
1919 {
1920 Error("Compilation of format string failed.");
1921 return;
1922 }
1923
1924 //we've got a nice structure describing the format of this service's messages.
1925 //Let's create the appropriate FITS columns
1926 const vector<string> dataFormatsLocal = sub.fConv->GetFitsFormat();
1927
1928 ostringstream str;
1929 str << "Initializing data columns for service " << sub.server << "/" << sub.service;
1930 Info(str);
1931 sub.nightlyFile.InitDataColumns(GetDescription(sub.server, sub.service), dataFormatsLocal, this);
1932
1933 sub.fitsBufferAllocated = true;
1934}
1935// --------------------------------------------------------------------------
1936//
1937//! write a dimInfo data to its corresponding FITS files
1938//
1939//FIXME: DO I REALLY NEED THE EVENT IMP HERE ???
1940void DataLogger::WriteToFITS(SubscriptionType& sub, const void* data)
1941{
1942 //nightly File status (open or not) already checked
1943 if (sub.nightlyFile.IsOpen())
1944 {
1945 if (!sub.nightlyFile.Write(*sub.fConv.get(), data))
1946 {
1947 RemoveService(sub.server, sub.service, false);
1948 GoToNightlyWriteErrorState();
1949 return;
1950 }
1951 }
1952}
1953#endif //if has_fits
1954// --------------------------------------------------------------------------
1955//
1956//! Go to Run Write Error State
1957// A write error has occurred. Checks what is the current state and take appropriate action
1958void DataLogger::GoToRunWriteErrorState()
1959{
1960 if ((GetCurrentState() != kSM_RunWriteError) &&
1961 (GetCurrentState() != kSM_DailyWriteError))
1962 SetCurrentState(kSM_RunWriteError, "GoToRunWriteErrorState");
1963}
1964// --------------------------------------------------------------------------
1965//
1966//! Go to Nightly Write Error State
1967// A write error has occurred. Checks what is the current state and take appropriate action
1968void DataLogger::GoToNightlyWriteErrorState()
1969{
1970 if (GetCurrentState() != kSM_DailyWriteError)
1971 SetCurrentState(kSM_DailyWriteError, "GoToNightlyWriteErrorState");
1972}
1973
1974
1975#ifdef HAVE_FITS
1976// --------------------------------------------------------------------------
1977//
1978//! Create a fits group file with all the run-fits that were written (either daily or run)
1979//! @param filesToGroup a map of filenames mapping to table names to be grouped (i.e. a
1980//! single file can contain several tables to group
1981//! @param runNumber the run number that should be used for grouping. 0 means nightly group
1982//
1983void DataLogger::CreateFitsGrouping(map<string, vector<string> > & filesToGroup)
1984{
1985 if (fDebugIsOn)
1986 {
1987 ostringstream str;
1988 str << "Creating fits group for nightly files";
1989 Debug(str);
1990 }
1991 //create the FITS group corresponding to the ending run.
1992 CCfits::FITS* groupFile;
1993 unsigned int numFilesToGroup = 0;
1994 unsigned int maxCharLength = 0;
1995 for (map<string, vector<string> >::const_iterator it=filesToGroup.begin(); it != filesToGroup.end(); it++)
1996 {
1997 //add the number of tables in this file to the total number to group
1998 numFilesToGroup += it->second.size();
1999 //check the length of all the strings to be written, to determine the max string length to write
2000 if (it->first.size() > maxCharLength)
2001 maxCharLength = it->first.size();
2002 for (vector<string>::const_iterator jt=it->second.begin(); jt != it->second.end(); jt++)
2003 if (jt->size() > maxCharLength)
2004 maxCharLength = jt->size();
2005 }
2006
2007 if (fDebugIsOn)
2008 {
2009 ostringstream str;
2010 str << "There are " << numFilesToGroup << " tables to group";
2011 Debug(str);
2012 }
2013 if (numFilesToGroup <= 1)
2014 {
2015 filesToGroup.clear();
2016 return;
2017 }
2018 const string groupName = CompileFileNameWithPath(fFilePath, "", "fits");
2019
2020 Info("Creating FITS group in: "+groupName);
2021
2022 CCfits::Table* groupTable;
2023
2024 try
2025 {
2026 groupFile = new CCfits::FITS(groupName, CCfits::RWmode::Write);
2027 //setup the column names
2028 ostringstream pathTypeName;
2029 pathTypeName << maxCharLength << "A";
2030 vector<string> names;
2031 vector<string> dataTypes;
2032 names.emplace_back("MEMBER_XTENSION");
2033 dataTypes.emplace_back("8A");
2034 names.emplace_back("MEMBER_URI_TYPE");
2035 dataTypes.emplace_back("3A");
2036 names.emplace_back("MEMBER_LOCATION");
2037 dataTypes.push_back(pathTypeName.str());
2038 names.emplace_back("MEMBER_NAME");
2039 dataTypes.push_back(pathTypeName.str());
2040 names.emplace_back("MEMBER_VERSION");
2041 dataTypes.emplace_back("1J");
2042 names.emplace_back("MEMBER_POSITION");
2043 dataTypes.emplace_back("1J");
2044
2045 groupTable = groupFile->addTable("GROUPING", numFilesToGroup, names, dataTypes);
2046//TODO handle the case when the logger was stopped and restarted during the same day, i.e. the grouping file must be updated
2047 }
2048 catch (CCfits::FitsException e)
2049 {
2050 ostringstream str;
2051 str << "Creating FITS table GROUPING in " << groupName << ": " << e.message();
2052 Error(str);
2053 return;
2054 }
2055 try
2056 {
2057 groupTable->addKey("GRPNAME", "FACT_RAW_DATA", "Data from the FACT telescope");
2058 }
2059 catch (CCfits::FitsException e)
2060 {
2061 Error("CCfits::Table::addKey failed for 'GRPNAME' in '"+groupName+"-GROUPING': "+e.message());
2062 return;
2063 }
2064 //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.
2065 //use cfitsio routines instead
2066 groupTable->makeThisCurrent();
2067 //create appropriate buffer.
2068 const unsigned int n = 8 + 3 + 2*maxCharLength + 1 + 8; //+1 for trailling character
2069
2070 vector<char> realBuffer(n);
2071
2072 char *startOfExtension = realBuffer.data();
2073 char *startOfURI = realBuffer.data()+8;
2074 char *startOfLocation = realBuffer.data()+8+3;
2075 char *startOfName = realBuffer.data()+8+3+maxCharLength;
2076
2077 strcpy(startOfExtension, "BINTABLE");
2078 strcpy(startOfURI, "URL");
2079
2080 realBuffer[8+3+2*maxCharLength+3] = 1;
2081 realBuffer[8+3+2*maxCharLength+7] = 1;
2082
2083 int i=1;
2084 for (map<string, vector<string> >::const_iterator it=filesToGroup.begin(); it!=filesToGroup.end(); it++)
2085 for (vector<string>::const_iterator jt=it->second.begin(); jt != it->second.end(); jt++, i++)
2086 {
2087 memset(startOfLocation, 0, 2*maxCharLength+1+8);
2088
2089 strcpy(startOfLocation, it->first.c_str());
2090 strcpy(startOfName, jt->c_str());
2091
2092 if (fDebugIsOn)
2093 {
2094 ostringstream str;
2095 str << "Grouping " << it->first << " " << *jt;
2096 Debug(str);
2097 }
2098
2099 int status = 0;
2100 fits_write_tblbytes(groupFile->fitsPointer(), i, 1, 8+3+2*maxCharLength +8,
2101 reinterpret_cast<unsigned char*>(realBuffer.data()), &status);
2102 if (status)
2103 {
2104 char text[30];//max length of cfitsio error strings (from doc)
2105 fits_get_errstatus(status, text);
2106 ostringstream str;
2107 str << "Writing FITS row " << i << " in " << groupName << ": " << text << " (file_write_tblbytes, rc=" << status << ")";
2108 Error(str);
2109 GoToRunWriteErrorState();
2110 delete groupFile;
2111 return;
2112 }
2113 }
2114
2115 filesToGroup.clear();
2116 delete groupFile;
2117}
2118#endif //HAVE_FITS
2119
2120// --------------------------------------------------------------------------
2121//
2122//! Implements the StopRun transition.
2123//! Attempts to close the run file.
2124//! @returns
2125//! kSM_WaitingRun if success, kSM_FatalError otherwise
2126int DataLogger::StopRunLogging()
2127{
2128
2129 if (fDebugIsOn)
2130 {
2131 Debug("Stopping Run Logging...");
2132 }
2133
2134 if (fNumSubAndFitsIsOn)
2135 fNumSubAndFits->Update();
2136
2137 while (fRunNumber.size() > 0)
2138 {
2139 RemoveOldestRunNumber();
2140 }
2141 return kSM_WaitingRun;
2142}
2143// --------------------------------------------------------------------------
2144//
2145//! Implements the Stop and Reset transitions.
2146//! Attempts to close any openned file.
2147//! @returns
2148//! kSM_Ready
2149int DataLogger::GoToReady()
2150{
2151 if (fDebugIsOn)
2152 {
2153 Debug("Going to the Ready state...");
2154 }
2155 if (GetCurrentState() == kSM_Logging || GetCurrentState() == kSM_WaitingRun)
2156 StopRunLogging();
2157
2158 //it may be that dim tries to write a dimInfo while we're closing files. Prevent that
2159 const string baseFileName = CompileFileNameWithPath(fFilePath, "", "");
2160
2161// if (fNightlyReportFile.is_open())
2162// {
2163// fNightlyReportFile.close();
2164// Info("Closed: "+baseFileName+".rep");
2165// }
2166#ifdef HAVE_FITS
2167 for (SubscriptionsListType::iterator i = fServiceSubscriptions.begin(); i != fServiceSubscriptions.end(); i++)
2168 for (map<string, SubscriptionType>::iterator j = i->second.begin(); j != i->second.end(); j++)
2169 {
2170 if (j->second.nightlyFile.IsOpen())
2171 j->second.nightlyFile.Close();
2172 }
2173#endif
2174 if (GetCurrentState() == kSM_Logging ||
2175 GetCurrentState() == kSM_WaitingRun ||
2176 GetCurrentState() == kSM_NightlyOpen)
2177 {
2178 NotifyOpenedFile("", 0, fOpenedNightlyFiles);
2179 if (fNumSubAndFitsIsOn)
2180 fNumSubAndFits->Update();
2181 }
2182#ifdef HAVE_FITS
2183 CreateFitsGrouping(fOpenedNightlyFits);
2184#endif
2185 return kSM_Ready;
2186}
2187
2188// --------------------------------------------------------------------------
2189//
2190//! Implements the transition towards kSM_WaitingRun
2191//! If current state is kSM_Ready, then tries to go to nightlyOpen state first.
2192//! @returns
2193//! kSM_WaitingRun or kSM_BadFolder
2194int DataLogger::NightlyToWaitRun()
2195{
2196 int cState = GetCurrentState();
2197
2198 if (cState == kSM_Ready)
2199 cState = Start();
2200
2201 if (cState != kSM_NightlyOpen)
2202 return GetCurrentState();
2203
2204 if (fDebugIsOn)
2205 {
2206 Debug("Going to Wait Run Number state...");
2207 }
2208 return kSM_WaitingRun;
2209}
2210// --------------------------------------------------------------------------
2211//
2212//! Implements the transition from wait for run number to nightly open
2213//! Does nothing really.
2214//! @returns
2215//! kSM_WaitingRun
2216int DataLogger::BackToNightlyOpen()
2217{
2218 if (GetCurrentState()==kSM_Logging)
2219 StopRunLogging();
2220
2221 if (fDebugIsOn)
2222 {
2223 Debug("Going to NightlyOpen state...");
2224 }
2225 return kSM_NightlyOpen;
2226}
2227// --------------------------------------------------------------------------
2228//
2229//! Setup Logger's configuration from a Configuration object
2230//! @param conf the configuration object that should be used
2231//!
2232int DataLogger::EvalOptions(Configuration& conf)
2233{
2234 fDebugIsOn = conf.Get<bool>("debug");
2235 fFilesStats.SetDebugMode(fDebugIsOn);
2236
2237 //Set the block or allow list
2238 fBlackList.clear();
2239 fWhiteList.clear();
2240
2241 //Adding entries that should ALWAYS be ignored
2242 fBlackList.insert("DATA_LOGGER/MESSAGE");
2243 fBlackList.insert("DATA_LOGGER/SUBSCRIPTIONS");
2244 fBlackList.insert("/SERVICE_LIST");
2245 fBlackList.insert("DIS_DNS/");
2246
2247 //set the black list, white list and the goruping
2248 const vector<string> vec1 = conf.Vec<string>("block");
2249 const vector<string> vec2 = conf.Vec<string>("allow");
2250 const vector<string> vec3 = conf.Vec<string>("group");
2251
2252 fBlackList.insert(vec1.begin(), vec1.end());
2253 fWhiteList.insert(vec2.begin(), vec2.end());
2254 fGrouping.insert( vec3.begin(), vec3.end());
2255
2256 //set the old run numbers timeout delay
2257 if (conf.Has("run-timeout"))
2258 {
2259 const uint32_t timeout = conf.Get<uint32_t>("run-timeout");
2260 if (timeout == 0)
2261 {
2262 Error("Time out delay for old run numbers must not be 0.");
2263 return 1;
2264 }
2265 fRunNumberTimeout = timeout;
2266 }
2267
2268 //configure the run files directory
2269 if (conf.Has("destination-folder"))
2270 {
2271 const string folder = conf.Get<string>("destination-folder");
2272 if (!fFilesStats.SetCurrentFolder(folder))
2273 return 2;
2274
2275 fFilePath = folder;
2276 fFullNightlyLogFileName = CompileFileNameWithPath(fFilePath, "", "log");
2277 if (!OpenTextFile(fNightlyLogFile, fFullNightlyLogFileName))
2278 return 3;
2279
2280 fNightlyLogFile << endl;
2281 NotifyOpenedFile(fFullNightlyLogFileName, 1, fOpenedNightlyFiles);
2282 for (vector<string>::iterator it=backLogBuffer.begin();it!=backLogBuffer.end();it++)
2283 fNightlyLogFile << *it;
2284 }
2285
2286 shouldBackLog = false;
2287 backLogBuffer.clear();
2288
2289 //configure the interval between statistics updates
2290 if (conf.Has("stats-interval"))
2291 fFilesStats.SetUpdateInterval(conf.Get<int16_t>("stats-interval"));
2292
2293 //configure if the filenames service is on or off
2294 fOpenedFilesIsOn = !conf.Get<bool>("no-filename-service");
2295
2296 //configure if the number of subscriptions and fits files is on or off.
2297 fNumSubAndFitsIsOn = !conf.Get<bool>("no-numsubs-service");
2298 //should we open the daily files at startup ?
2299 if (conf.Has("start-daily-files"))
2300 if (conf.Get<bool>("start-daily-files"))
2301 {
2302 fShouldAutoStart = true;
2303 }
2304 if (conf.Has("service-list-interval"))
2305 fCurrentSubscriptionUpdateRate = conf.Get<int32_t>("service-list-interval");
2306
2307 Info("Preset observatory: "+Nova::LnLatPosn::preset()+" [PRESET_OBSERVATORY]");
2308
2309 return -1;
2310}
2311
2312
2313#include "Main.h"
2314
2315// --------------------------------------------------------------------------
2316template<class T>
2317int RunShell(Configuration &conf)
2318{
2319 return Main::execute<T, DataLogger>(conf);//, true);
2320}
2321
2322/*
2323 Extract usage clause(s) [if any] for SYNOPSIS.
2324 Translators: "Usage" and "or" here are patterns (regular expressions) which
2325 are used to match the usage synopsis in program output. An example from cp
2326 (GNU coreutils) which contains both strings:
2327 Usage: cp [OPTION]... [-T] SOURCE DEST
2328 or: cp [OPTION]... SOURCE... DIRECTORY
2329 or: cp [OPTION]... -t DIRECTORY SOURCE...
2330 */
2331void PrintUsage()
2332{
2333 cout << "\n"
2334 "The data logger connects to all available Dim services and "
2335 "writes them to ascii and fits files.\n"
2336 "\n"
2337 "The default is that the program is started without user interaction. "
2338 "All actions are supposed to arrive as DimCommands. Using the -c "
2339 "option, a local shell can be initialized. With h or help a short "
2340 "help message about the usage can be brought to the screen.\n"
2341 "\n"
2342 "Usage: datalogger [-c type] [OPTIONS]\n"
2343 " or: datalogger [OPTIONS]\n";
2344 cout << endl;
2345
2346}
2347// --------------------------------------------------------------------------
2348void PrintHelp()
2349{
2350 /* Additional help text which is printed after the configuration
2351 options goes here */
2352 cout <<
2353 "\n"
2354 "If the allow list has any element, only the servers and/or services "
2355 "specified in the list will be used for subscription. The black list "
2356 "will disable service subscription and has higher priority than the "
2357 "allow list. If the allow list is not present by default all services "
2358 "will be subscribed."
2359 "\n"
2360 "For example, block=DIS_DNS/ will skip all the services offered by "
2361 "the DIS_DNS server, while block=/SERVICE_LIST will skip all the "
2362 "SERVICE_LIST services offered by any server and DIS_DNS/SERVICE_LIST "
2363 "will skip DIS_DNS/SERVICE_LIST.\n"
2364 << endl;
2365
2366 Main::PrintHelp<DataLogger>();
2367}
2368
2369// --------------------------------------------------------------------------
2370void SetupConfiguration(Configuration &conf)
2371{
2372 po::options_description configs("DataLogger options");
2373 configs.add_options()
2374 ("block,b", vars<string>(), "Black-list to block services")
2375 ("allow,a", vars<string>(), "White-list to only allow certain services")
2376 ("debug,d", po_bool(), "Debug mode. Print clear text of received service reports.")
2377 ("group,g", vars<string>(), "Grouping of services into a single run-Fits")
2378 ("run-timeout", var<uint32_t>(), "Time out delay for old run numbers in milliseconds.")
2379 ("destination-folder", var<string>(), "Base path for the nightly and run files")
2380 ("stats-interval", var<int16_t>(), "Interval in milliseconds for write statistics update")
2381 ("no-filename-service", po_bool(), "Disable update of filename service")
2382 ("no-numsubs-service", po_bool(), "Disable update of number-of-subscriptions service")
2383 ("start-daily-files", po_bool(), "Starts the logger in DailyFileOpen instead of Ready")
2384 ("service-list-interval", var<int32_t>(), "Interval between two updates of the service SUBSCRIPTIONS")
2385 ;
2386
2387 conf.AddOptions(configs);
2388}
2389// --------------------------------------------------------------------------
2390int main(int argc, const char* argv[])
2391{
2392 Configuration conf(argv[0]);
2393 conf.SetPrintUsage(PrintUsage);
2394 Main::SetupConfiguration(conf);
2395 SetupConfiguration(conf);
2396
2397 if (!conf.DoParse(argc, argv, PrintHelp))
2398 return 127;
2399
2400 {
2401 // No console access at all
2402 if (!conf.Has("console"))
2403 return RunShell<LocalStream>(conf);
2404
2405 // Console access w/ and w/o Dim
2406 if (conf.Get<int>("console")==0)
2407 return RunShell<LocalShell>(conf);
2408 else
2409 return RunShell<LocalConsole>(conf);
2410 }
2411
2412
2413 return 0;
2414}
Note: See TracBrowser for help on using the repository browser.