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