-
Notifications
You must be signed in to change notification settings - Fork 20
/
application.h
695 lines (540 loc) · 22.1 KB
/
application.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
/***************************************************************************
* Copyright (C) gempa GmbH *
* All rights reserved. *
* Contact: gempa GmbH (seiscomp-dev@gempa.de) *
* *
* GNU Affero General Public License Usage *
* This file may be used under the terms of the GNU Affero *
* Public License version 3.0 as published by the Free Software Foundation *
* and appearing in the file LICENSE included in the packaging of this *
* file. Please review the following information to ensure the GNU Affero *
* Public License version 3.0 requirements will be met: *
* https://www.gnu.org/licenses/agpl-3.0.html. *
* *
* Other Usage *
* Alternatively, this file may be used in accordance with the terms and *
* conditions contained in a signed written agreement between you and *
* gempa GmbH. *
***************************************************************************/
#ifndef SEISCOMP_CLIENT_APPLICATION_H
#define SEISCOMP_CLIENT_APPLICATION_H
#include <seiscomp/system/application.h>
#include <seiscomp/core/message.h>
#include <seiscomp/client/queue.h>
#include <seiscomp/client/monitor.h>
#include <seiscomp/client/inventory.h>
#include <seiscomp/client.h>
#include <seiscomp/datamodel/databasequery.h>
#include <seiscomp/datamodel/notifier.h>
#include <seiscomp/datamodel/configmodule.h>
#include <seiscomp/math/coord.h>
#include <seiscomp/messaging/connection.h>
#include <seiscomp/utils/timer.h>
#include <seiscomp/utils/stringfirewall.h>
#include <set>
#include <thread>
#include <mutex>
#define SCCoreApp (Seiscomp::Client::Application::Instance())
namespace Seiscomp {
namespace Logging {
class Output;
}
namespace Client {
MAKEENUM(
ApplicationStatus,
EVALUES(
STARTED,
FINISHED
),
ENAMES(
"started",
"finished"
)
);
class SC_SYSTEM_CLIENT_API ApplicationStatusMessage : public Core::Message {
DECLARE_SC_CLASS(ApplicationStatusMessage);
DECLARE_SERIALIZATION;
public:
ApplicationStatusMessage();
ApplicationStatusMessage(const std::string &module,
ApplicationStatus status);
ApplicationStatusMessage(const std::string &module,
const std::string &username,
ApplicationStatus status);
public:
virtual bool empty() const;
const std::string &module() const;
const std::string &username() const;
ApplicationStatus status() const;
private:
std::string _module;
std::string _username;
ApplicationStatus _status;
};
struct SC_SYSTEM_CLIENT_API Notification {
//! Declares the application internal notification types.
//! Custom types can be used with negative values.
enum Type {
Object,
Disconnect,
Reconnect,
Close,
Timeout,
AcquisitionFinished
};
Notification() : object(nullptr), type(Object) {}
Notification(Core::BaseObject * o) : object(o), type(Object) {}
Notification(int t) : object(nullptr), type(t) {}
Notification(int t, Core::BaseObject * o) : object(o), type(t) {}
Core::BaseObject *object;
int type;
};
/**
* \brief Application class to write commandline clients easily which are
* connected to the messaging and need database access.
*
* In addition to @ref System::Application it adds the method
* @ref handleMessage which must be implemented to handle receives
* messages. An additional abstraction layer is implemented which already
* checks the message for notifier objects, extracts them and calls respective
* callbacks:
* * @ref addObject()
* * @ref removeObject()
* * @ref updateObject()
*/
class SC_SYSTEM_CLIENT_API Application : public System::Application {
// ----------------------------------------------------------------------
// Public types
// ----------------------------------------------------------------------
public:
typedef ObjectMonitor::Log ObjectLog;
//! Initialization stages used when reporting errors
enum ClientStage {
MESSAGING = System::Application::ST_QUANTITY,
DATABASE = System::Application::ST_QUANTITY + 1,
CST_QUANTITY
};
// ----------------------------------------------------------------------
// X'truction
// ----------------------------------------------------------------------
public:
Application(int argc, char **argv);
~Application();
// ----------------------------------------------------------------------
// Public functions
// ----------------------------------------------------------------------
public:
//! Returns the configured agencyID
const std::string &agencyID() const;
//! Returns the configured author
const std::string &author() const;
/**
* Returns according to the configured white- and blacklist of
* agencyID's whether the passed agencyID is allowed or not
* @param agencyID The agencyID to check
* @return The boolean result
*/
bool isAgencyIDAllowed(const std::string &agencyID) const;
/**
* Returns !isAgencyIDAllowed(agencyID)
* @param agencyID The agencyID to check
* @return !isAgencyIDAllowed(agencyID)
*/
bool isAgencyIDBlocked(const std::string &agencyID) const;
/**
* Exit the application and set the returnCode.
* @param returnCode The value returned from exec()
*/
virtual void exit(int returnCode);
//! Returns the application's messaging connection interface
Client::Connection *connection() const;
//! Returns the configured database type
const std::string &databaseType() const;
//! Returns the configured database connection parameters
const std::string &databaseParameters() const;
//! Returns the application's database interface
IO::DatabaseInterface *database() const;
//! Returns the application's database URI
const std::string &databaseURI() const;
//! Returns the application's database query interface
DataModel::DatabaseQuery *query() const;
//! Returns the configures recordstream URL to be used by
//! RecordStream::Open()
const std::string &recordStreamURL() const;
//! Returns the list of configured points of interest
const std::vector<Math::Geo::CityD> &cities() const;
//! Returns the nearest city with respect to lat/lon and
//! a given maximum distance and minimum population
const Math::Geo::CityD *nearestCity(double lat, double lon,
double maxDist, double minPopulation,
double *dist, double *azi) const;
//! Returns the config module object if available
DataModel::ConfigModule *configModule() const;
//! Returns the state of a station
bool isStationEnabled(const std::string& networkCode,
const std::string& stationCode);
//! Returns the messaging-server
const std::string &messagingURL() const;
//! Enables a timer that calls every n seconds the
//! handleTimeout() methods
//! A value of 0 seconds disables the timer
void enableTimer(unsigned int seconds);
//! Disables the timer
void disableTimer();
//! Sends a notification to the application. If used in derived
//! classes to send custom notifications use negative notification
//! types and reimplement dispatchNotification(...).
void sendNotification(const Notification &);
bool waitEvent();
// ----------------------------------------------------------------------
// Initialization configuration functions
// This functions have to be called before the init() method
// ----------------------------------------------------------------------
public:
//! Sets the primary messaging group
void setPrimaryMessagingGroup(const std::string&);
//! Returns the set primary messaging group
const std::string &primaryMessagingGroup() const;
//! Sets the username used for the messaging connection
void setMessagingUsername(const std::string&);
/**
* Adds a group to subscribe to. This is only a default group.
* If another group or groups are given via commandline or config
* file this subscription will be overriden completely.
*/
void addMessagingSubscription(const std::string&);
//! Initialize the database, default = true, true
void setDatabaseEnabled(bool enable, bool tryToFetch);
bool isDatabaseEnabled() const;
//! Returns whether the inventory should be loaded from a
//! file (false) or from the database (true)
bool isInventoryDatabaseEnabled() const;
//! Returns whether the config module should be loaded from a
//! file (false) or from the database (true)
bool isConfigDatabaseEnabled() const;
//! Initialize the messaging, default = true
void setMessagingEnabled(bool enable);
bool isMessagingEnabled() const;
/**
* @brief Toggles receiption of messaging membership messages. The
* default is false.
* @param enable Flag
*/
void setMembershipMessagesEnabled(bool enable);
bool areMembershipMessagesEnabled() const;
//! Enables/disables sending of start/stop messages.
//! If enabled, a start message (at startup) and a
//! stop message (at shutdown) will be sent to the
//! STATUS group. Default = false
void setStartStopMessagesEnabled(bool enable);
bool areStartStopMessagesEnabled() const;
//! Enables/disables auto shutdown caused by
//! the shutdown of a definable master module or
//! master username. If both values are set the
//! one coming first is used.
void setAutoShutdownEnabled(bool enable);
bool isAutoShutdownEnabled() const;
//! Enables recordstream URL option, default = true
void setRecordStreamEnabled(bool enable);
bool isRecordStreamEnabled() const;
//! Load the stations from the inventory at startup, default = false
void setLoadStationsEnabled(bool enable);
bool isLoadStationsEnabled() const;
//! Load the complete inventory at startup, default = false
void setLoadInventoryEnabled(bool enable);
bool isLoadInventoryEnabled() const;
//! Load the configmodule from the database at startup, default = false
void setLoadConfigModuleEnabled(bool enable);
bool isLoadConfigModuleEnabled() const;
//! Load the cities.xml file, default = false
void setLoadCitiesEnabled(bool enable);
bool isLoadCitiesEnabled() const;
//! Load the custom defined fep regions in ~/.seiscomp/fep or
//! ~/seiscomp/trunk/share/fep, default = false
void setLoadRegionsEnabled(bool enable);
bool isLoadRegionsEnabled() const;
//! Sets whether the received notifier are applied automatically
//! or not, default: true
/**
* Sets whether the received notifier are applied automatically
* or not, default: true
* When AutoApplyNotifier is enabled a received message will
* be handled in two passes:
* 1. pass: Apply all attached notifier
* 2. pass: Interpret all notifier
*
* So when using an object in an interprete callback it is
* garantueed that all child objects that also has been sent
* inside the message are attached to it.
*/
void setAutoApplyNotifierEnabled(bool enable);
bool isAutoApplyNotifierEnabled() const;
/**
* Sets whether the received notifier will be interpreted or not.
* Default: true
* When this option is enabled, the callback methods
* addObject(), updateObject() and removeObject() will be
* called after a notifier has been received.
*/
void setInterpretNotifierEnabled(bool enable);
bool isInterpretNotifierEnabled() const;
/** Returns whether a custom publicID pattern has been configured
or not */
bool hasCustomPublicIDPattern() const;
/**
* Sets the number of retries if a connection fails.
* The default value is 0xFFFFFFFF and should be understood
* as "keep on trying".
*/
void setConnectionRetries(unsigned int);
//! Sets the config module name to use when reading
//! the database configuration. An empty module name
//! means: read all available modules.
//! The default module is "trunk".
void setConfigModuleName(const std::string &module);
const std::string &configModuleName() const;
//! Sets the master module used when auto shutdown
//! is activated.
void setShutdownMasterModule(const std::string &module);
//! Sets the master username used when auto shutdown
//! is activated.
void setShutdownMasterUsername(const std::string &username);
/**
* Adds a logger for an input object flow.
* This method must be called after Application::init().
* The returned pointer is managed by the Application and must not
* be deleted.
*/
ObjectLog *
addInputObjectLog(const std::string &name,
const std::string &channel = "");
/**
* Adds a logger for an output object flow.
* This method must be called after Application::init().
* The returned pointer is managed by the Application and must not
* be deleted.
*/
ObjectLog *
addOutputObjectLog(const std::string &name,
const std::string &channel = "");
/**
* Logs input/output object throughput.
* @param log Pointer returned by addInputObjectLog or addOutputObjectLog
* @param timestamp The timestamp to be logged
*/
void logObject(ObjectLog *log, const Core::Time ×tamp,
size_t count = 1);
/**
* Reloads the application inventory from either an XML file or
* the database.
*/
bool reloadInventory();
/**
* Reloads the application configuration (bindings) from either an
* XML file or the database.
*/
bool reloadBindings();
/**
* @brief Injects a message from outside. The message will actually
* take the same path as when it would have been received via
* the messaging.
* @param msg The message. The ownership if left to the caller.
* @param pkt The optional network packet. The ownership is left to
* the caller.
*/
void injectMessage(Core::Message *msg, Packet *pkt = nullptr);
/**
* @brief Routes a notifier to either add/update or removeObject.
* @param notifier The notifier pointer which must not be nullptr
*/
void handleNotifier(DataModel::Notifier *notifier);
// ----------------------------------------------------------------------
// Static public members
// ----------------------------------------------------------------------
public:
//! Returns the pointer to the application's instance.
static Application *Instance();
// ----------------------------------------------------------------------
// Protected functions
// ----------------------------------------------------------------------
protected:
virtual void createBaseCommandLineDescription() override;
virtual bool validateParameters() override;
virtual bool handlePreFork() override;
virtual bool init() override;
/**
* Starts the mainloop until exit() or quit() is called.
* The default implementation waits for messages in blocking mode
* and calls handleMessage() whenever a new message arrives.
*/
virtual bool run() override;
//! This method gets called when all messages has been read or
//! the connection is invalid
virtual void idle();
//! Cleanup method called before exec() returns.
virtual void done() override;
//! Opens the configuration file and reads the state variables
virtual bool initConfiguration() override;
//! Initialized the database
virtual bool initDatabase();
//! Sets the database interface and creates a database query object
void setDatabase(IO::DatabaseInterface* db);
/**
* Reads the requested subscriptions from the configuration file
* and apply them to the messaging connection.
*/
virtual bool initSubscriptions();
const std::set<std::string> &subscribedGroups() const;
/**
* Called when the application received the AcquisitionFinished event.
* This is most likely send from the readRecords thread of the
* StreamApplication. The default implementation does nothing.
*/
virtual void handleEndAcquisition();
// ----------------------------------------------------------------------
// Messaging handlers
// ----------------------------------------------------------------------
protected:
virtual bool dispatch(Core::BaseObject*);
//! Custom dispatch method for notifications with negative (< 0)
//! types. The default implementation return false.
virtual bool dispatchNotification(int type, Core::BaseObject*);
/**
* Reads messages from the connection.
* @return true, if successfull, false if not. When returning false,
* the mainloop will stop and the program is going to
* terminate.
*/
bool readMessages();
/**
* This method gets called when a previously started timer timeout's.
* The timer has to be started by enableTimer(timeout).
*/
virtual void handleTimeout();
/**
* This method is called when close event is sent to the application.
* The default handler returns true and causes the event queue to
* shutdown and to exit the application.
* It false is returned the close event is ignored.
*/
virtual bool handleClose();
/**
* This methods gets called when an auto shutdown has been
* initiated. The default implementation just quits.
*/
virtual void handleAutoShutdown();
/**
* This methods gets called when an the log interval is reached
* and the application should prepare its logging information. This
* method can be used to sync logs.
* The default implementation does nothing.
*/
virtual void handleMonitorLog(const Core::Time ×tamp);
/**
* This method gets called after the connection got lost.
*/
virtual void handleDisconnect();
/**
* This method gets called after the connection got reestablished.
*/
virtual void handleReconnect();
/**
* Handles receiption of a network packet which is a candidate
* for message decoding. Special service messages such as ENTER or
* LEAVE will not cause a message to be created. This method is always
* called *before* a message should be handled.
*/
virtual void handleNetworkMessage(const Client::Packet *msg);
/**
* This method gets called whenever a new message arrives. Derived
* classes have to implement this method to receive messages.
* To enable autoapplying and notifier interpreting call this method
* inside the reimplemented version.
* @param msg The message. A smartpointer may be stored for
* future use. The pointer must not be deleted!
*/
virtual void handleMessage(Core::Message *msg);
//! Callback for interpret notifier
virtual void addObject(const std::string &parentID, DataModel::Object*) {}
//! Callback for interpret notifier
virtual void removeObject(const std::string &parentID, DataModel::Object*) {}
//! Callback for interpret notifier
virtual void updateObject(const std::string &parentID, DataModel::Object*) {}
// ----------------------------------------------------------------------
// Private functions
// ----------------------------------------------------------------------
private:
bool initMessaging();
bool loadConfig(const std::string &configDB);
bool loadInventory(const std::string &inventoryDB);
void startMessageThread();
void runMessageThread();
bool processEvent();
void timeout();
void monitorLog(const Core::Time ×tamp, std::ostream &os);
// ----------------------------------------------------------------------
// Implementation
// ----------------------------------------------------------------------
protected:
std::string _agencyID;
std::string _author;
Util::StringFirewall _procFirewall;
Util::StringFirewall _networkTypeFirewall;
Util::StringFirewall _stationTypeFirewall;
DataModel::DatabaseQueryPtr _query;
std::string _configModuleName;
DataModel::ConfigModulePtr _configModule;
// Initialization configuration
bool _enableMessaging;
bool _enableMembershipMessages;
bool _enableStartStopMessages;
bool _enableAutoShutdown;
bool _enableDatabase;
bool _enableRecordStream;
bool _enableFetchDatabase;
bool _enableLoadStations;
bool _enableLoadInventory;
bool _enableLoadConfigModule;
bool _enableAutoApplyNotifier;
bool _enableInterpretNotifier;
bool _enableLoadCities;
bool _enableLoadRegions;
unsigned int _retryCount;
std::vector<Math::Geo::CityD> _cities;
std::vector<std::string> _messagingSubscriptionRequests;
std::set<std::string> _messagingSubscriptions;
std::string _shutdownMasterModule;
std::string _shutdownMasterUsername;
bool _customPublicIDPattern;
int _objectLogTimeWindow;
private:
static Application *_instance;
protected:
ObjectMonitor *_inputMonitor;
ObjectMonitor *_outputMonitor;
ThreadedQueue<Notification> _queue;
std::thread *_messageThread;
ConnectionPtr _connection;
IO::DatabaseInterfacePtr _database;
// State variables
std::string _messagingUser;
std::string _messagingURL;
std::string _messagingPrimaryGroup;
std::string _messagingContentType;
unsigned int _messagingTimeout;
std::string _inventoryDB;
std::string _configDB;
std::string _cityDB;
std::string _dbType;
std::string _dbParameters;
std::string _db;
std::string _recordStream;
Util::Timer _userTimer;
std::mutex _objectLogMutex;
};
inline bool Application::waitEvent() {
return processEvent();
}
}
}
#endif