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

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