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