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