source: trunk/FACT++/src/dataLogger.cc@ 10290

Last change on this file since 10290 was 10289, checked in by tbretz, 13 years ago
The Converter functions now throw exceptions. The previous way of reporting a conversion error was not convenient.
File size: 36.9 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 digraph datalogger {
13 node [shape=record, fontname=Helvetica, fontsize=10];
14 e [label="Error" color="red"];
15 r [label="Ready"]
16 d [label="DailyOpen"]
17 w [label="WaitingRun"]
18 l [label="Logging"]
19 b [label="BadDailyconfig" color="red"]
20 c [label="BadRunConfig" color="red"]
21
22 e -> r
23 r -> e
24 r -> d
25 r -> b
26 d -> w
27 d -> r
28 w -> r
29 l -> r
30 l -> w
31 b -> d
32 w -> c
33 w -> l
34 b -> r
35 c -> r
36 c -> l
37 }
38 \enddot
39
40 @todo
41 - Retrieve also the messages, not only the infos
42 */
43 //****************************************************************
44#include "Event.h"
45#include "Time.h"
46#include "StateMachineDim.h"
47#include "WindowLog.h"
48#include "Configuration.h"
49#include "ServiceList.h"
50#include "Converter.h"
51#include "MessageImp.h"
52#include "LocalControl.h"
53
54//#define HAS_FITS
55
56#include <fstream>
57
58#include <boost/bind.hpp>
59
60#ifdef HAS_FITS
61#include <astroroot.h>
62#endif
63
64class DataLogger : public StateMachineDim, DimInfoHandler
65{
66public:
67 /// The list of existing states specific to the DataLogger
68 enum
69 {
70 kSM_DailyOpen = 20, ///< Daily file openned and writing
71 kSM_WaitingRun = 30, ///< waiting for the run number to open the run file
72 kSM_Logging = 40, ///< both files openned and writing
73 kSM_BadDailyConfig = 0x101, ///< the folder specified for daily logging does not exist or has bad permissions
74 kSM_BadRunConfig = 0x102, ///< the folder specified for the run logging does not exist or has wrong permissions or no run number
75 } localstates_t;
76
77 DataLogger(std::ostream &out);
78 ~DataLogger();
79
80private:
81 //Define all the data structure specific to the DataLogger here
82 /// ofstream for the dailyLogfile
83 std::ofstream fDailyLogFile;
84 /// ofstream for the run-specific Log file
85 std::ofstream fRunLogFile;
86
87 /// ofstream for the daily report file
88 std::ofstream fDailyReportFile;
89 /// ofstream for the run-specific report file
90 std::ofstream fRunReportFile;
91 /// base path of the dailyfile
92 std::string fDailyFileName;
93 ///base path of the run file
94 std::string fRunFileName;
95 ///run number (-1 means no run number specified)
96 int fRunNumber;
97 ///Current year
98 short fYear;
99 ///Current Month
100 short fMonth;
101 ///Current Day
102 short fDay;
103 ///Current Hour
104 short fHour;
105 ///Current Minute
106 short fMin;
107 ///Current Second
108 short fSec;
109 ///Current Milliseconds
110 int fMs;
111 ///Current Service Quality
112 int fQuality;
113 ///Modified Julian Date
114 double fMjD;
115
116 ///Define all the static names
117 static const char* fConfigDay;
118 static const char* fConfigRun;
119 static const char* fConfigRunNumber;
120 static const char* fConfigLog;
121 static const char* fTransStart;
122 static const char* fTransStop;
123 static const char* fTransStartRun;
124 static const char* fTransStopRun;
125 static const char* fTransReset;
126 static const char* fTransWait;
127 static const char* fRunNumberInfo; ///< This is the name of the dimInfo received to specify the run number. It must be updated once the final name will be defined
128 ///Inherited from state machine impl
129 int Execute();
130
131 ///Inherited from state machine impl
132 int Transition(const Event& evt);
133
134 ///Inherited from state machine impl
135 int Configure(const Event& evt);
136
137 //overloading of DIM's infoHandler function
138 void infoHandler();
139
140 ///for obtaining the name of the existing services
141 ServiceList fServiceList;
142
143
144 ///A std pair to store both the DimInfo name and the actual DimInfo pointer
145// typedef std::pair<std::string, DimStampedInfo*> subscriptionType;
146 ///All the services to which we've subscribed to. Sorted by server name
147// std::map<const std::string, std::vector<subscriptionType > > fServiceSubscriptions;
148
149 ///A std pair to store both the DimInfo pointer and the corresponding outputted fits file
150 struct SubscriptionType
151 {
152#ifdef HAS_FITS
153 ///daily FITS output file
154 AstroRootIo dailyFile;
155 ///run-specific FITS output file
156 AstroRootIo runFile;
157#endif
158 ///the actual dimInfo pointer
159 DimStampedInfo* dimInfo;
160 ///the number of existing handlers to this structure.
161 ///This is required otherwise I MUST handle the deleting of dimInfo outside from the destructor
162 int* numCopies;
163 void operator = (const SubscriptionType& other)
164 {
165#ifdef HAS_FITS
166 dailyFile = other.dailyFile;
167 runFile = other.runFile;
168#endif
169 dimInfo = other.dimInfo;
170 numCopies = other.numCopies;
171 (*numCopies)++;
172 }
173 SubscriptionType(const SubscriptionType& other)
174 {
175#ifdef HAS_FITS
176 dailyFile = other.dailyFile;
177 runFile = other.runFile;
178#endif
179 dimInfo = other.dimInfo;
180 numCopies = other.numCopies;
181 (*numCopies)++;
182 }
183 SubscriptionType(DimStampedInfo* info)
184 {
185 dimInfo = info;
186 numCopies = new int(1);
187 }
188 SubscriptionType()
189 {
190 dimInfo = NULL;
191 numCopies = new int(1);
192 }
193 ~SubscriptionType()
194 {
195 if (numCopies)
196 (*numCopies)--;
197 if (numCopies)
198 if (*numCopies < 1)
199 {
200#ifdef HAS_FITS
201 if (dailyFile.IsOpen())
202 dailyFile.Close();
203 if (runFile.IsOpen())
204 runFile.Close();
205#endif
206 if (dimInfo)
207 delete dimInfo;
208 if (numCopies)
209 delete numCopies;
210 dimInfo = NULL;
211 numCopies = NULL;
212 }
213 }
214 };
215 typedef std::map<const std::string, std::map<std::string, SubscriptionType>> SubscriptionsListType;
216 ///All the services to which we have subscribed to, sorted by server name.
217 SubscriptionsListType fServiceSubscriptions;
218
219
220 ///Reporting method for the services info received
221 void ReportPlease(DimInfo* I, SubscriptionType& sub);
222
223 ///Configuration of the daily file path
224 int ConfigureDailyFileName(const Event& evt);
225 ///Configuration fo the file name
226 int ConfigureRunFileName(const Event& evt);
227 ///DEPREC - configuration of the run number
228 int ConfigureRunNumber(const Event& evt);
229 ///logging method for the messages
230 int LogMessagePlease(const Event& evt);
231 ///checks whether or not the current info being treated is a run number
232 void CheckForRunNumber(DimInfo* I);
233
234 /// start transition
235 int StartPlease();
236 ///from waiting to logging transition
237 int StartRunPlease();
238 /// from logging to waiting transition
239 int StopRunPlease();
240 ///stop and reset transition
241 int GoToReadyPlease();
242 ///from dailyOpen to waiting transition
243 int DailyToWaitRunPlease();
244#ifdef HAS_FITS
245 ///Open fits files
246 void OpenFITSFilesPlease(SubscriptionType& sub);
247 ///Write data to FITS files
248 void WriteToFITS(SubscriptionType& sub);
249 ///Allocate the buffers required for fits
250 void AllocateFITSBuffers(SubscriptionType& sub);
251#endif
252public:
253 ///checks with fServiceList whether or not the services got updated
254 void CheckForServicesUpdate();
255
256}; //DataLogger
257
258//static members initialization
259//since I do not check the transition/config names any longer, indeed maybe these could be hard-coded... but who knows what will happen in the future ?
260const char* DataLogger::fConfigDay = "CONFIG_DAY";
261const char* DataLogger::fConfigRun = "CONFIG_RUN";
262const char* DataLogger::fConfigRunNumber = "CONFIG_RUN_NUMBER";
263const char* DataLogger::fConfigLog = "LOG";
264const char* DataLogger::fTransStart = "START";
265const char* DataLogger::fTransStop = "STOP";
266const char* DataLogger::fTransStartRun = "START_RUN";
267const char* DataLogger::fTransStopRun = "STOP_RUN";
268const char* DataLogger::fTransReset = "RESET";
269const char* DataLogger::fTransWait = "WAIT_RUN_NUMBER";
270const char* DataLogger::fRunNumberInfo = "RUN_NUMBER";
271
272// --------------------------------------------------------------------------
273//
274//! Default constructor. The name of the machine is given DATA_LOGGER
275//! and the state is set to kSM_Ready at the end of the function.
276//
277//!Setup the allows states, configs and transitions for the data logger
278//
279DataLogger::DataLogger(std::ostream &out) : StateMachineDim(out, "DATA_LOGGER")
280{
281 //initialize member data
282 fDailyFileName = "/home/lyard/log";
283 fRunFileName = "/home/lyard/log";
284 fRunNumber = 12345;
285 //Give a name to this machine's specific states
286 AddStateName(kSM_DailyOpen, "DailyFileOpen");
287 AddStateName(kSM_WaitingRun, "WaitForRun");
288 AddStateName(kSM_Logging, "Logging");
289 AddStateName(kSM_BadDailyConfig, "ErrDailyFolder");
290 AddStateName(kSM_BadRunConfig, "ErrRunFolder");
291
292 /*Add the possible transitions for this machine*/
293 AddTransition(kSM_DailyOpen, fTransStart, kSM_Ready, kSM_BadDailyConfig) //start the daily logging. daily file location must be specified already
294 ->AssignFunction(boost::bind(&DataLogger::StartPlease, this));
295 AddTransition(kSM_Ready, fTransStop, kSM_DailyOpen, kSM_WaitingRun, kSM_Logging) //stop the data logging
296 ->AssignFunction(boost::bind(&DataLogger::GoToReadyPlease, this));
297 AddTransition(kSM_Logging, fTransStartRun, kSM_WaitingRun, kSM_BadRunConfig) //start the run logging. run file location must be specified already.
298 ->AssignFunction(boost::bind(&DataLogger::StartRunPlease, this));
299 AddTransition(kSM_WaitingRun, fTransStopRun, kSM_Logging)
300 ->AssignFunction(boost::bind(&DataLogger::StopRunPlease, this));
301 AddTransition(kSM_Ready, fTransReset, kSM_Error, kSM_BadDailyConfig, kSM_BadRunConfig, kSM_Error) //transition to exit error states. dunno if required or not, would close the daily file if already openned.
302 ->AssignFunction(boost::bind(&DataLogger::GoToReadyPlease, this));
303 AddTransition(kSM_WaitingRun, fTransWait, kSM_DailyOpen)
304 ->AssignFunction(boost::bind(&DataLogger::DailyToWaitRunPlease, this));
305 /*Add the possible configurations for this machine*/
306 AddConfiguration(fConfigDay, "C", kSM_Ready, kSM_BadDailyConfig) //configure the daily file location. cannot be done before the file is actually opened
307 ->AssignFunction(boost::bind(&DataLogger::ConfigureDailyFileName, this, _1));
308 AddConfiguration(fConfigRun, "C", kSM_Ready, kSM_BadDailyConfig, kSM_DailyOpen, kSM_WaitingRun, kSM_BadRunConfig) //configure the run file location. cannot be done before the file is actually opened, and not in a dailly related error.
309 ->AssignFunction(boost::bind(&DataLogger::ConfigureRunFileName, this, _1));
310
311 //Provide a logging command
312 //I get the feeling that I should be going through the EventImp
313 //instead of DimCommand directly, mainly because the commandHandler
314 //is already done in StateMachineImp.cc
315 //Thus I'll simply add a configuration, which I will treat as the logging command
316 AddConfiguration(fConfigLog, "C", kSM_DailyOpen, kSM_Logging, kSM_WaitingRun, kSM_BadRunConfig)
317 ->AssignFunction(boost::bind(&DataLogger::LogMessagePlease, this, _1));
318
319 fServiceList.SetHandler(this);
320 CheckForServicesUpdate();
321}
322// --------------------------------------------------------------------------
323//
324//! Checks for changes in the existing services.
325//! Any new service will be added to the service list, while the ones which disappeared are removed.
326//! @todo
327//! add the configuration (using the conf class ?)
328//
329void DataLogger::CheckForServicesUpdate()
330{
331
332 //get the current server list
333 const std::vector<std::string> serverList = fServiceList.GetServerList();
334 //first let's remove the servers that may have disapeared
335 //can't treat the erase on maps the same way as for vectors. Do it the safe way instead
336 std::vector<std::string> toBeDeleted;
337 for (SubscriptionsListType::iterator cListe = fServiceSubscriptions.begin(); cListe != fServiceSubscriptions.end(); cListe++)
338 {
339 std::vector<std::string>::const_iterator givenServers;
340 for (givenServers=serverList.begin(); givenServers!= serverList.end(); givenServers++)
341 if (cListe->first == *givenServers)
342 break;
343 if (givenServers == serverList.end())//server vanished. Remove it
344 toBeDeleted.push_back(cListe->first);
345 }
346 for (std::vector<std::string>::const_iterator it = toBeDeleted.begin(); it != toBeDeleted.end(); it++)
347 fServiceSubscriptions.erase(*it);
348
349 //now crawl through the list of servers, and see if there was some updates
350 for (std::vector<std::string>::const_iterator i=serverList.begin(); i!=serverList.end();i++)
351 {
352 //skip the two obvious excluded services
353 if ((i->find("DIS_DNS") != std::string::npos) ||
354 (i->find("DATA_LOGGER") != std::string::npos))
355 continue;
356 //find the current server in our subscription list
357 SubscriptionsListType::iterator cSubs = fServiceSubscriptions.find(*i);
358 //get the service list of the current server
359 std::vector<std::string> cServicesList = fServiceList.GetServiceList(*i);
360 if (cSubs != fServiceSubscriptions.end())//if the current server already is in our subscriptions
361 { //then check and update our list of subscriptions
362 //first, remove the services that may have dissapeared.
363 std::map<std::string, SubscriptionType>::iterator serverSubs;
364 std::vector<std::string>::const_iterator givenSubs;
365 toBeDeleted.clear();
366 for (serverSubs=cSubs->second.begin(); serverSubs != cSubs->second.end(); serverSubs++)
367 {
368 for (givenSubs = cServicesList.begin(); givenSubs != cServicesList.end(); givenSubs++)
369 if (serverSubs->first == *givenSubs)
370 break;
371 if (givenSubs == cServicesList.end())
372 {
373 toBeDeleted.push_back(serverSubs->first);
374 }
375 }
376 for (std::vector<std::string>::const_iterator it = toBeDeleted.begin(); it != toBeDeleted.end(); it++)
377 cSubs->second.erase(*it);
378 //now check for new services
379 for (givenSubs = cServicesList.begin(); givenSubs != cServicesList.end(); givenSubs++)
380 {
381 if (*givenSubs == "SERVICE_LIST")
382 continue;
383 if (cSubs->second.find(*givenSubs) == cSubs->second.end())
384 {//service not found. Add it
385 cSubs->second[*givenSubs].dimInfo = new DimStampedInfo(((*i) + "/" + *givenSubs).c_str(), const_cast<char*>(""), this);
386 }
387 }
388 }
389 else //server not found in our list. Create its entry
390 {
391 fServiceSubscriptions[*i] = std::map<std::string, SubscriptionType>();
392 std::map<std::string, SubscriptionType>& liste = fServiceSubscriptions[*i];
393 for (std::vector<std::string>::const_iterator j = cServicesList.begin(); j!= cServicesList.end(); j++)
394 {
395 if (*j == "SERVICE_LIST")
396 continue;
397 liste[*j].dimInfo = new DimStampedInfo(((*i) + "/" + (*j)).c_str(), const_cast<char*>(""), this);
398 }
399 }
400 }
401}
402// --------------------------------------------------------------------------
403//
404//! Destructor
405//
406DataLogger::~DataLogger()
407{
408 //close the files
409 if (fDailyLogFile.is_open())
410 fDailyLogFile.close();
411 if (fDailyReportFile.is_open())
412 fDailyReportFile.close();
413 if (fRunLogFile.is_open())
414 fRunLogFile.close();
415 if (fRunReportFile.is_open())
416 fRunReportFile.close();
417 //release the services subscriptions
418 fServiceSubscriptions.clear();
419}
420// --------------------------------------------------------------------------
421//
422//! Execute
423//! Shouldn't be run as we use callbacks instead
424//
425int DataLogger::Execute()
426{
427 //due to the callback mecanism, this function should never be called
428 return kSM_FatalError;
429
430 switch (GetCurrentState())
431 {
432 case kSM_Error:
433 case kSM_Ready:
434 case kSM_DailyOpen:
435 case kSM_WaitingRun:
436 case kSM_Logging:
437 case kSM_BadDailyConfig:
438 case kSM_BadRunConfig:
439 return GetCurrentState();
440 }
441 //this line below should never be hit. It here mainly to remove warnings at compilation
442 return kSM_FatalError;
443}
444// --------------------------------------------------------------------------
445//
446//! Shouldn't be run as we use callbacks instead
447//
448 int DataLogger::Transition(const Event& evt)
449{
450 //due to the callback mecanism, this function should never be called
451 return kSM_FatalError;
452
453 switch (evt.GetTargetState())
454 {
455 case kSM_Ready:
456 /*here we must figure out whether the STOP or RESET command was sent*/
457 /*close opened files and go back to ready state*/
458 switch (GetCurrentState())
459 {
460 case kSM_BadDailyConfig:
461 case kSM_BadRunConfig:
462 case kSM_Error:
463 return GoToReadyPlease();
464
465 case kSM_Logging:
466 case kSM_WaitingRun:
467 case kSM_DailyOpen:
468 return GoToReadyPlease();
469 }
470 break;
471
472 case kSM_DailyOpen:
473 /*Attempt to open the daily file */
474 switch (GetCurrentState())
475 {
476 case kSM_Ready:
477 case kSM_BadDailyConfig:
478 return StartPlease();
479 }
480 break;
481
482 case kSM_WaitingRun:
483 /*either close the run file, or just go to the waitingrun state (if coming from daily open*/
484 switch (GetCurrentState())
485 {
486 case kSM_DailyOpen:
487 return kSM_WaitingRun;
488
489 case kSM_Logging:
490 return StopRunPlease();
491 }
492 break;
493
494 case kSM_Logging:
495 /*Attempt to open run file */
496 switch (GetCurrentState())
497 {
498 case kSM_WaitingRun:
499 case kSM_BadRunConfig:
500 return StartRunPlease();
501 }
502 break;
503 }
504 //Getting here means that an invalid transition has been asked.
505 //TODO Log an error message
506 //and return the fatal error state
507 return kSM_FatalError;
508}
509// --------------------------------------------------------------------------
510//
511//! Shouldn't be run as we use callbacks instead
512//
513 int DataLogger::Configure(const Event& evt)
514{
515 //due to the callback mecanism, this function should never be called
516 return kSM_FatalError;
517
518 switch (evt.GetTargetState())
519 {
520 case kSM_Ready:
521 case kSM_BadDailyConfig:
522 return ConfigureDailyFileName(evt);
523 break;
524
525 case kSM_WaitingRun:
526 case kSM_BadRunConfig:
527 return ConfigureRunFileName(evt);
528 break;
529
530 case kSM_Logging:
531 case kSM_DailyOpen:
532//TODO check that this is indeed correct
533 return 0;//LogMessagePlease(evt);
534 break;
535
536 }
537 //Getting here means that an invalid configuration has been asked.
538 //TODO Log an error message
539 //and return the fatal error state
540 return kSM_FatalError;
541}
542// --------------------------------------------------------------------------
543//
544//! Inherited from DimInfo. Handles all the Infos to which we subscribed, and log them
545//
546void DataLogger::infoHandler()
547{
548 DimInfo* I = getInfo();
549 if (I==NULL)
550 {
551 CheckForServicesUpdate();
552 return;
553 }
554 //check if the service pointer corresponds to something that we subscribed to
555 //this is a fix for a bug that provides bad Infos when a server starts
556 bool found = false;
557 SubscriptionsListType::iterator x;
558 std::map<std::string, SubscriptionType>::iterator y;
559 for (x=fServiceSubscriptions.begin(); x != fServiceSubscriptions.end(); x++)
560 {//instead of extracting the server and service names, I crawl through my records. dunno what's faster, but both should work
561 for (y=x->second.begin(); y!=x->second.end();y++)
562 if (y->second.dimInfo == I)
563 {
564 found = true;
565 break;
566 }
567 if (found)
568 break;
569 }
570 if (!found)
571 return;
572 if (I->getSize() <= 0)
573 return;
574 //check that the message has been updated by something, i.e. must be different from its initial value
575 if (I->getTimestamp() == 0)
576 return;
577
578 CheckForRunNumber(I);
579 ReportPlease(I, y->second);
580}
581
582// --------------------------------------------------------------------------
583//
584//! Checks whether or not the current info is a run number.
585//! If so, then remember it. A run number is required to open the run-log file
586//! @param I
587//! the current DimInfo
588//
589void DataLogger::CheckForRunNumber(DimInfo* I)
590{
591 return;
592 if (strstr(I->getName(), fRunNumberInfo) != NULL)
593 {//assumes that the run number is an integer
594 //TODO check the format here
595 fRunNumber = I->getInt();
596 }
597}
598
599// --------------------------------------------------------------------------
600//
601//! write infos to log files.
602//! @param I
603//! The current DimInfo
604//
605void DataLogger::ReportPlease(DimInfo* I, SubscriptionType& sub)
606{
607 //should we log or report this info ? (i.e. is it a message ?)
608 bool isItaReport = ((strstr(I->getName(), "Message") == NULL) && (strstr(I->getName(), "MESSAGE") == NULL));
609
610// std::ofstream & dailyFile = fDailyReportFile;//isItaReport? fDailyReportFile : fDailyLogFile;
611// std::ofstream & runFile = fRunReportFile;//isItaReport? fRunReportFile : fRunLogFile;
612
613 //TODO add service exclusion
614 if (!fDailyReportFile.is_open())
615 return;
616
617 //construct the header
618 std::stringstream header;
619
620 Time cTime((time_t)(I->getTimestamp()), I->getTimestampMillisecs());
621
622 //Buffer them for FITS write
623 //TODO this has been replaced by MjD. So I guess that these member variables can go.
624 fYear = cTime.Y(); fMonth = cTime.M(); fDay = cTime.D();
625 fHour = cTime.h(); fMin = cTime.m(); fSec = cTime.s();
626 fMs = cTime.ms(); fQuality = I->getQuality();
627
628 fMjD = cTime.Mjd();
629
630 if (isItaReport)
631 {
632 //write text header
633 header << I->getName() << " " << fQuality << " ";
634 header << fYear << " " << fMonth << " " << fDay << " ";
635 header << fHour << " " << fMin << " " << fSec << " ";
636 header << fMs << " " << I->getTimestamp() << " ";
637
638 const Converter conv(Out(), I->getFormat());
639 if (!conv)
640 {
641 Error("Couldn't properly parse the format... ignored.");
642 return;
643 }
644
645 std::string text;
646 try
647 {
648 text = conv.GetString(I->getData(), I->getSize());
649 }
650 catch (const std::runtime_error &e)
651 {
652 Out() << kRed << e.what() << endl;
653 Error("Couldn't properly parse the data... ignored.");
654 return;
655 }
656
657 if (text.empty())
658 return;
659
660 //replace bizarre characters by white space
661 replace(text.begin(), text.end(), '\n', '\\');
662 replace_if(text.begin(), text.end(), std::ptr_fun<int, int>(&std::iscntrl), ' ');
663
664 if (fDailyReportFile.is_open())
665 fDailyReportFile << header.str();
666 if (fRunReportFile.is_open())
667 fRunReportFile << header.str();
668
669 if (fDailyReportFile.is_open())
670 fDailyReportFile << text << std::endl;
671 if (fRunReportFile.is_open())
672 fRunReportFile << text << std::endl;
673 }
674 else
675 {
676 std::string n = I->getName();
677 std::stringstream msg;
678 msg << n.substr(0, n.find_first_of('/')) << ": " << I->getString();
679 MessageImp dailyMess(fDailyLogFile);
680 dailyMess.Write(cTime, msg.str().c_str(), fQuality);
681 if (fRunLogFile.is_open())
682 {
683 MessageImp runMess(fRunLogFile);
684 runMess.Write(cTime, msg.str().c_str(), fQuality);
685 }
686 }
687
688#ifdef HAS_FITS
689 if (!sub.dailyFile.IsOpen() || !sub.runFile.IsOpen())
690 OpenFITSFilesPlease(sub);
691 WriteToFITS(sub);
692#endif
693
694}
695// --------------------------------------------------------------------------
696//
697//! write messages to logs.
698//! @param evt
699//! the current event to log
700//! @returns
701//! the new state. Currently, always the current state
702//!
703//! @deprecated
704//! I guess that this function should not be any longer
705//
706int DataLogger::LogMessagePlease(const Event& evt)
707{
708 if (!fDailyLogFile.is_open())
709 return GetCurrentState();
710
711 std::stringstream header;
712 const Time& cTime = evt.GetTime();
713 header << evt.GetName() << " " << cTime.Y() << " " << cTime.M() << " " << cTime.D() << " ";
714 header << cTime.h() << " " << cTime.m() << " " << cTime.s() << " ";
715 header << cTime.ms() << " ";
716
717// std::string text = ToString(evt.GetFormat().c_str(), evt.GetData(), evt.GetSize());
718
719 const Converter conv(Out(), evt.GetFormat());
720 if (!conv)
721 {
722 Error("Couldn't properly parse the format... ignored.");
723 return GetCurrentState();
724 }
725
726 std::string text;
727 try
728 {
729 text = conv.GetString(evt.GetData(), evt.GetSize());
730 }
731 catch (const std::runtime_error &e)
732 {
733 Out() << kRed << e.what() << endl;
734 Error("Couldn't properly parse the data... ignored.");
735 return GetCurrentState();
736 }
737
738
739 if (text.empty())
740 return GetCurrentState();
741
742 //replace bizarre characters by white space
743 replace(text.begin(), text.end(), '\n', '\\');
744 replace_if(text.begin(), text.end(), std::ptr_fun<int, int>(&std::iscntrl), ' ');
745
746 if (fDailyLogFile.is_open())
747 fDailyLogFile << header;
748 if (fRunLogFile.is_open())
749 fRunLogFile << header;
750
751 if (fDailyLogFile.is_open())
752 fDailyLogFile << text;
753 if (fRunLogFile.is_open())
754 fRunLogFile << text;
755
756 return GetCurrentState();
757}
758// --------------------------------------------------------------------------
759//
760//! Sets the path to use for the daily log file.
761//! @param evt
762//! the event transporting the path
763//! @returns
764//! currently only the current state.
765//
766int DataLogger::ConfigureDailyFileName(const Event& evt)
767{
768 if (evt.GetText() != NULL)
769 fDailyFileName = std::string(evt.GetText());
770 else
771 Error("Empty daily folder");
772
773 return GetCurrentState();
774}
775// --------------------------------------------------------------------------
776//
777//! Sets the path to use for the run log file.
778//! @param evt
779//! the event transporting the path
780//! @returns
781//! currently only the current state
782int DataLogger::ConfigureRunFileName(const Event& evt)
783{
784 if (evt.GetText() != NULL)
785 fRunFileName = std::string(evt.GetText());
786 else
787 Error("Empty daily folder");
788
789 return GetCurrentState();
790}
791// --------------------------------------------------------------------------
792//
793//! Sets the run number.
794//! @param evt
795//! the event transporting the run number
796//! @returns
797//! currently only the current state
798int DataLogger::ConfigureRunNumber(const Event& evt)
799{
800 fRunNumber = evt.GetInt();
801
802 return GetCurrentState();
803}
804// --------------------------------------------------------------------------
805//
806//! Implements the Start transition.
807//! Concatenates the given path for the daily file and the filename itself (based on the day),
808//! and tries to open it.
809//! @returns
810//! kSM_DailyOpen if success, kSM_BadDailyConfig if failure
811int DataLogger::StartPlease()
812{
813 //TODO concatenate the dailyFileName and the formatted date and extension to obtain the full file name
814 Time time;//(Time::utc);
815 std::stringstream sTime;
816 sTime << time.Y() << "_" << time.M() << "_" << time.D();
817 std::string fullName = fDailyFileName + '/' + sTime.str() + ".log";
818
819 fDailyLogFile.open(fullName.c_str(), std::ios_base::out | std::ios_base::app); //maybe should be "app" instead of "ate" ??
820 fullName = fDailyFileName + '/' + sTime.str() + ".rep";
821 fDailyReportFile.open(fullName.c_str(), std::ios_base::out | std::ios_base::app);
822 if (!fDailyLogFile.is_open() || !fDailyReportFile.is_open())
823 {
824 //TODO send an error message
825 return kSM_BadDailyConfig;
826 }
827 return kSM_DailyOpen;
828}
829
830#ifdef HAS_FITS
831// --------------------------------------------------------------------------
832//
833//! open if required a the FITS files corresponding to a given subscription
834//! @param sub
835//! the current DimInfo subscription being examined
836void DataLogger::OpenFITSFilesPlease(SubscriptionType& sub)
837{
838 std::string serviceName(sub.dimInfo->getName());
839 for (unsigned int i=0;i<serviceName.size(); i++)
840 {
841 if (serviceName[i] == '/')
842 {
843 serviceName[i] = '_';
844 break;
845 }
846 }
847 Time time;
848 std::stringstream sTime;
849 sTime << time.Y() << "_" << time.M() << "_" << time.D();
850 //we open the dailyFile anyway, otherwise this function shouldn't have been called.
851 if (!sub.dailyFile.IsOpen())
852 {
853 std::string partialName = fDailyFileName + '/' + sTime.str() + '_' + serviceName + ".fits";
854 std::string fullName = fDailyFileName + '/' + sTime.str() + '_' + serviceName + ".fits[" + serviceName + "]";
855
856 AllocateFITSBuffers(sub);
857 //currently, the FITS are written in the same directory as the text files.
858 //thus the write permissions have already been checked by the text files.
859 //if the target folder changes, then I should check the write permissions here
860 //now we only check whether the target file exists or not
861 std::ifstream readTest(partialName.c_str());
862 if (readTest.is_open())
863 {
864 readTest.close();
865 sub.dailyFile.Open(fullName.c_str(), "UPDATE");
866 }
867 else {
868 sub.dailyFile.Open(fullName.c_str(), "CREATE");
869 }
870
871//TODO Write the header's attributes
872 }
873 if (!sub.runFile.IsOpen() && (GetCurrentState() == kSM_Logging))
874 {//buffer for the run file have already been allocated when doing the daily file
875 std::stringstream sRun;
876 sRun << fRunNumber;
877 std::string partialName = fRunFileName + '/' + sRun.str() + '_' + serviceName + ".fits";
878 std::string fullName = fRunFileName + '/' + sRun.str() + '_' + serviceName + ".fits[" + serviceName + "]";
879
880 std::ifstream readTest(partialName.c_str());
881 if (readTest.is_open())
882 {
883 readTest.close();
884 sub.runFile.Open(fullName.c_str(), "UPDATE");
885 }
886 else
887 sub.runFile.Open(fullName.c_str(), "CREATE");
888//TODO Write the header's attributes
889 }
890}
891// --------------------------------------------------------------------------
892//
893void DataLogger::AllocateFITSBuffers(SubscriptionType& sub)
894{
895 const char* format = sub.dimInfo->getFormat();
896 const int size = sub.dimInfo->getSize();
897
898 //Init the time columns of the file
899 sub.dailyFile.InitCol("Date", "double", &fMjD);
900 sub.runFile.InitCol("Date", "double", &fMjD);
901
902// sub.dailyFile.InitCol("Year", "short", &fYear);
903// sub.dailyFile.InitCol("Month", "short", &fMonth);
904// sub.dailyFile.InitCol("Day", "short", &fDay);
905// sub.dailyFile.InitCol("Hour", "short", &fHour);
906// sub.dailyFile.InitCol("Minute", "short", &fMin);
907// sub.dailyFile.InitCol("Second", "short", &fSec);
908// sub.dailyFile.InitCol("MilliSec", "int", &fMs);
909 sub.dailyFile.InitCol("QoS", "int", &fQuality);
910
911// sub.runFile.InitCol("Year", "short", &fYear);
912// sub.runFile.InitCol("Month", "short", &fMonth);
913// sub.runFile.InitCol("Day", "short", &fDay);
914// sub.runFile.InitCol("Hour", "short", &fHour);
915// sub.runFile.InitCol("Minute", "short", &fMin);
916// sub.runFile.InitCol("Second", "short", &fSec);
917// sub.runFile.InitCol("MilliSec", "int", &fMs);
918 sub.runFile.InitCol("QoS", "int", &fQuality);
919
920 const Converter::FormatList flist = Converter::Compile(Out(), format);
921
922 // Compilation failed
923 if (fList.empty() || fList.back().first.second!=0)
924 {
925 Error("Compilation of format string failed.");
926 return;
927 }
928
929 //we've got a nice structure describing the format of this service's messages.
930 //Let's create the appropriate FITS columns
931 for (unsigned int i=0;i<flist.size();i++)
932 {
933 std::stringstream colName;
934 std::stringstream dataQualifier;
935 void * dataPointer = static_cast<char*>(sub.dimInfo->getData()) + flist[i].second.second;
936 colName << "Data" << i;
937 dataQualifier << flist[i].second.first;
938 switch (flist[i].first.first)
939 {
940 case 'c':
941 dataQualifier << "S";
942 break;
943 case 's':
944 dataQualifier << "I";
945 break;
946 case 'i':
947 dataQualifier << "J";
948 break;
949 case 'l':
950 dataQualifier << "J";
951 //TODO triple check that in FITS, long = int
952 break;
953 case 'f':
954 dataQualifier << "E";
955 break;
956 case 'd':
957 dataQualifier << "D";
958 break;
959 case 'x':
960 dataQualifier << "K";
961 break;
962 case 'S':
963 //for strings, the number of elements I get is wrong. Correct it
964 dataQualifier.str(""); //clear
965 dataQualifier << size-1 << "A";
966 break;
967
968 default:
969 Error("THIS SHOULD NEVER BE REACHED. dataLogger.cc ln 962.");
970 };
971 sub.dailyFile.InitCol(colName.str().c_str(), dataQualifier.str().c_str(), dataPointer);
972 sub.runFile.InitCol(colName.str().c_str(), dataQualifier.str().c_str(), dataPointer);
973 }
974
975//TODO init the attributes
976}
977// --------------------------------------------------------------------------
978//
979//! write a dimInfo data to its corresponding FITS files
980//
981void DataLogger::WriteToFITS(SubscriptionType& sub)
982{
983 //dailyFile status (open or not) already checked
984 if (sub.dailyFile.IsOpen())
985 sub.dailyFile.Write();
986 if (sub.runFile.IsOpen())
987 sub.runFile.Write();
988}
989#endif //if has_fits
990// --------------------------------------------------------------------------
991//
992//! Implements the StartRun transition.
993//! Concatenates the given path for the run file and the filename itself (based on the run number),
994//! and tries to open it.
995//! @returns
996//! kSM_Logging if success, kSM_BadRunConfig if failure.
997int DataLogger::StartRunPlease()
998{
999 //attempt to open run file with current parameters
1000 if (fRunNumber == -1)
1001 return kSM_BadRunConfig;
1002 std::stringstream sRun;
1003 sRun << fRunNumber;
1004 std::string fullName = fRunFileName + '/' + sRun.str() + ".log";
1005 fRunLogFile.open(fullName.c_str(), std::ios_base::out | std::ios_base::app); //maybe should be app instead of ate
1006
1007 fullName = fRunFileName + '/' + sRun.str() + ".rep";
1008 fRunReportFile.open(fullName.c_str(), std::ios_base::out | std::ios_base::app);
1009
1010 if (!fRunLogFile.is_open() || !fRunReportFile.is_open())
1011 {
1012 //TODO send an error message
1013 return kSM_BadRunConfig;
1014 }
1015
1016 return kSM_Logging;
1017}
1018// --------------------------------------------------------------------------
1019//
1020//! Implements the StopRun transition.
1021//! Attempts to close the run file.
1022//! @returns
1023//! kSM_WaitingRun if success, kSM_FatalError otherwise
1024int DataLogger::StopRunPlease()
1025{
1026 if (!fRunLogFile.is_open() || !fRunReportFile.is_open())
1027 return kSM_FatalError;
1028
1029 fRunLogFile.close();
1030 fRunReportFile.close();
1031#ifdef HAS_FITS
1032 for (SubscriptionsListType::iterator i = fServiceSubscriptions.begin(); i != fServiceSubscriptions.end(); i++)
1033 for (std::map<std::string, SubscriptionType>::iterator j = i->second.begin(); j != i->second.end(); j++)
1034 {
1035 if (j->second.runFile.IsOpen())
1036 j->second.runFile.Close();
1037 }
1038#endif
1039 return kSM_WaitingRun;
1040
1041}
1042// --------------------------------------------------------------------------
1043//
1044//! Implements the Stop and Reset transitions.
1045//! Attempts to close any openned file.
1046//! @returns
1047//! kSM_Ready
1048int DataLogger::GoToReadyPlease()
1049{
1050 if (fDailyLogFile.is_open())
1051 fDailyLogFile.close();
1052 if (fDailyReportFile.is_open())
1053 fDailyReportFile.close();
1054
1055 if (fRunLogFile.is_open())
1056 fRunLogFile.close();
1057 if (fRunReportFile.is_open())
1058 fRunReportFile.close();
1059
1060#ifdef HAS_FITS
1061 for (SubscriptionsListType::iterator i = fServiceSubscriptions.begin(); i != fServiceSubscriptions.end(); i++)
1062 for (std::map<std::string, SubscriptionType>::iterator j = i->second.begin(); j != i->second.end(); j++)
1063 {
1064 if (j->second.dailyFile.IsOpen())
1065 j->second.dailyFile.Close();
1066 if (j->second.runFile.IsOpen())
1067 j->second.runFile.Close();
1068 }
1069#endif
1070 return kSM_Ready;
1071}
1072// --------------------------------------------------------------------------
1073//
1074//! Implements the transition towards kSM_WaitingRun
1075//! Does nothing really.
1076//! @returns
1077//! kSM_WaitingRun
1078int DataLogger::DailyToWaitRunPlease()
1079{
1080 return kSM_WaitingRun;
1081}
1082
1083// --------------------------------------------------------------------------
1084
1085int RunDim(Configuration &conf)
1086{
1087 WindowLog wout;
1088
1089 //log.SetWindow(stdscr);
1090 if (conf.Has("log"))
1091 if (!wout.OpenLogFile(conf.Get<std::string>("log")))
1092 wout << kRed << "ERROR - Couldn't open log-file " << conf.Get<std::string>("log") << ": " << strerror(errno) << std::endl;
1093
1094 // Start io_service.Run to use the StateMachineImp::Run() loop
1095 // Start io_service.run to only use the commandHandler command detaching
1096 DataLogger logger(wout);
1097 logger.Run(true);
1098
1099 return 0;
1100}
1101
1102template<class T>
1103int RunShell(Configuration &conf)
1104{
1105 static T shell(conf.GetName().c_str(), conf.Get<int>("console")!=1);
1106
1107 WindowLog &win = shell.GetStreamIn();
1108 WindowLog &wout = shell.GetStreamOut();
1109
1110 if (conf.Has("log"))
1111 if (!wout.OpenLogFile(conf.Get<std::string>("log")))
1112 win << kRed << "ERROR - Couldn't open log-file " << conf.Get<std::string>("log") << ": " << strerror(errno) << std::endl;
1113
1114 DataLogger logger(wout);
1115
1116 shell.SetReceiver(logger);
1117
1118 logger.SetReady();
1119 shell.Run(); // Run the shell
1120 logger.SetNotReady();
1121
1122 return 0;
1123}
1124
1125void SetupConfiguration(Configuration &conf)
1126{
1127 const std::string n = conf.GetName()+".log";
1128
1129 po::options_description config("Program options");
1130 config.add_options()
1131 ("dns", var<std::string>("localhost"), "Dim nameserver host name (Overwites DIM_DNS_NODE environment variable)")
1132 ("log,l", var<std::string>(n), "Write log-file")
1133 ("console,c", var<int>(), "Use console (0=shell, 1=simple buffered, X=simple unbuffered)")
1134 ;
1135
1136 conf.AddEnv("dns", "DIM_DNS_NODE");
1137
1138 conf.AddOptions(config);
1139}
1140
1141int main(int argc, char* argv[])
1142{
1143 Configuration conf(argv[0]);
1144 SetupConfiguration(conf);
1145
1146 po::variables_map vm;
1147 try
1148 {
1149 vm = conf.Parse(argc, argv);
1150 }
1151#if BOOST_VERSION > 104000
1152 catch (po::multiple_occurrences &e)
1153 {
1154 std::cout << "Error: " << e.what() << " of '" << e.get_option_name() << "' option." << std::endl;
1155 std::cout << std::endl;
1156 return -1;
1157 }
1158#endif
1159 catch (std::exception &e)
1160 {
1161 std::cout << "Error: " << e.what() << std::endl;
1162 std::cout << std::endl;
1163
1164 return -1;
1165 }
1166
1167 if (conf.HasHelp() || conf.HasPrint())
1168 return -1;
1169
1170 // To allow overwriting of DIM_DNS_NODE set 0 to 1
1171 setenv("DIM_DNS_NODE", conf.Get<std::string>("dns").c_str(), 1);
1172
1173 try
1174 {
1175 // No console access at all
1176 if (!conf.Has("console"))
1177 return RunDim(conf);
1178
1179 // Cosole access w/ and w/o Dim
1180 if (conf.Get<int>("console")==0)
1181 return RunShell<LocalShell>(conf);
1182 else
1183 return RunShell<LocalConsole>(conf);
1184 }
1185 catch (std::exception& e)
1186 {
1187 cerr << "Exception: " << e.what() << endl;
1188 return -1;
1189 }
1190
1191 return 0;
1192}
Note: See TracBrowser for help on using the repository browser.