Goby3 3.3.1
2025.11.25
Loading...
Searching...
No Matches
interface.h
Go to the documentation of this file.
1// Copyright 2011-2025:
2// GobySoft, LLC (2013-)
3// Massachusetts Institute of Technology (2007-2014)
4// Community contributors (see AUTHORS file)
5// File authors:
6// Toby Schneider <toby@gobysoft.org>
7//
8//
9// This file is part of the Goby Underwater Autonomy Project Libraries
10// ("The Goby Libraries").
11//
12// The Goby Libraries are free software: you can redistribute them and/or modify
13// them under the terms of the GNU Lesser General Public License as published by
14// the Free Software Foundation, either version 2.1 of the License, or
15// (at your option) any later version.
16//
17// The Goby Libraries are distributed in the hope that they will be useful,
18// but WITHOUT ANY WARRANTY; without even the implied warranty of
19// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20// GNU Lesser General Public License for more details.
21//
22// You should have received a copy of the GNU Lesser General Public License
23// along with Goby. If not, see <http://www.gnu.org/licenses/>.
24
25#ifndef GOBY_MIDDLEWARE_APPLICATION_INTERFACE_H
26#define GOBY_MIDDLEWARE_APPLICATION_INTERFACE_H
27
28#include <chrono>
29#include <csignal>
30#include <iostream>
31#include <sys/types.h>
32#include <unistd.h>
33
34#include <boost/format.hpp>
35
36#include "goby/exception.h"
40#include "goby/time.h"
42#include "goby/util/geodesy.h"
43
44namespace goby
45{
52template <typename App>
54
61template <typename App,
62 typename Configurator = middleware::ProtobufConfigurator<typename App::ConfigType>>
63int run(int argc, char* argv[])
64{
65 return run<App>(Configurator(argc, argv));
66}
67
68namespace middleware
69{
70
71namespace julia
72{
73template <typename App> class ApplicationWrapper;
74}
75
77template <typename Config> class Application
78{
79 public:
81 virtual ~Application()
82 {
83 goby::glog.is_debug2() && goby::glog << "Application: destructing cleanly" << std::endl;
84 }
85
86 using ConfigType = Config;
87
88 protected:
90 virtual void pre_initialize() {};
91
93 virtual void initialize() {};
94
96 virtual void post_initialize() {};
97
99 virtual void run() = 0;
100
102 virtual void pre_finalize() {};
103
105 virtual void finalize() {};
106
108 virtual void post_finalize() {};
109
113 void quit(int return_value = 0)
114 {
115 alive_ = false;
116 return_value_ = return_value;
117 }
118
120 const Config& app_cfg() { return *app_cfg_; }
121
124 {
125 if (geodesy_)
126 return *geodesy_;
127 else
128 throw(goby::Exception("No lat_origin and lon_origin defined for requested UTMGeodesy"));
129 }
130
132 bool has_geodesy() { return geodesy_ ? true : false; }
133
134 std::string app_name() { return app3_base_configuration_->name(); }
135
136 bool app_alive() { return alive_; }
137
138 boost::units::quantity<boost::units::si::frequency>
139 choose_loop_freq(boost::units::quantity<boost::units::si::frequency> compiled_loop_freq)
140 {
141 if (app3_base_configuration_->has_loop_frequency())
142 return app3_base_configuration_->loop_frequency_with_units();
143 else
144 return compiled_loop_freq;
145 }
146
147 protected:
149
150 private:
151 template <typename App>
152 friend int ::goby::run(
154
155 template <typename App> friend class goby::middleware::julia::ApplicationWrapper;
156
157 // main loop that exits on quit(); returns the desired return value
158 int __run();
159
160 void run_one() { run(); }
161
162 void configure_logger();
163 void configure_glog_file();
164 void configure_intervehicle();
165 void check_rotate_glog_file();
166
167 private:
168 // sets configuration (before Application construction)
169 static std::unique_ptr<Config> app_cfg_;
170 static std::unique_ptr<protobuf::AppConfig> app3_base_configuration_;
171
172 bool alive_;
173 int return_value_;
174
175 // static here allows fout_ to live until program exit to log glog output
176 static std::unique_ptr<std::ofstream> fout_;
177
178 goby::time::SteadyClock::time_point next_log_rotate_time_;
179
180 std::unique_ptr<goby::util::UTMGeodesy> geodesy_;
181};
182} // namespace middleware
183
184} // namespace goby
185
186template <typename Config>
187std::unique_ptr<std::ofstream> goby::middleware::Application<Config>::fout_;
188
189template <typename Config> std::unique_ptr<Config> goby::middleware::Application<Config>::app_cfg_;
190
191template <typename Config>
192std::unique_ptr<goby::middleware::protobuf::AppConfig>
194
195template <typename Config> goby::middleware::Application<Config>::Application() : alive_(true)
196{
197 using goby::glog;
198
199 configure_logger();
200 if (app3_base_configuration_->has_geodesy())
201 configure_geodesy({app3_base_configuration_->geodesy().lat_origin_with_units(),
202 app3_base_configuration_->geodesy().lon_origin_with_units()});
203
204 if (app3_base_configuration_->has_intervehicle_cfg())
205 configure_intervehicle();
206
207 if (!app3_base_configuration_->IsInitialized())
208 throw(middleware::ConfigException("Invalid base configuration"));
209
210 glog.is_debug2() && glog << "Application: constructed with PID: " << getpid() << std::endl;
211 glog.is_debug1() && glog << "App name is " << app3_base_configuration_->name() << std::endl;
212 glog.is_debug2() && glog << "Configuration is: " << app_cfg_->DebugString() << std::endl;
213}
214
215template <typename Config> void goby::middleware::Application<Config>::configure_logger()
216{
217 using goby::glog;
218
219 // set up the logger
220 glog.set_name(app3_base_configuration_->name());
222 app3_base_configuration_->glog_config().tty_verbosity()),
223 &std::cout);
224
225 if (app3_base_configuration_->glog_config().show_gui())
227
228 if (app3_base_configuration_->glog_config().has_file_log())
229 configure_glog_file();
230
231 if (app3_base_configuration_->glog_config().show_dccl_log())
233}
234
236{
238 app3_base_configuration_->intervehicle_cfg();
239
240 if (intervehicle_cfg.has_dccl_passphrase())
241 {
243 intervehicle_cfg.dccl_passphrase());
244 }
245}
246
248{
249 using goby::glog;
250 if (app3_base_configuration_->glog_config().has_file_log() &&
251 app3_base_configuration_->glog_config().file_log().has_log_rotate_sec() &&
252 goby::time::SteadyClock::now() > next_log_rotate_time_)
253 {
254 glog.remove_stream(fout_.get());
255 configure_glog_file();
256 }
257}
258
260{
261 const auto& file_log = app3_base_configuration_->glog_config().file_log();
262 std::string file_format_str;
263
264 std::string file_name_format = file_log.file_name();
265
266 if (!file_log.has_file_name() && file_log.omit().file_timestamp())
267 file_name_format = "%2%.txt";
268
269 if (file_log.has_file_dir() && !file_log.file_dir().empty())
270 {
271 auto file_dir = file_log.file_dir();
272 if (file_dir.back() != '/')
273 file_dir += "/";
274 file_format_str = file_dir + file_name_format;
275 }
276 else
277 {
278 file_format_str = file_name_format;
279 }
280
281 boost::format file_format(file_format_str);
282
283 if (!file_log.omit().file_timestamp())
284 {
285 if (file_format_str.find("%1") == std::string::npos)
286 glog.is_die() &&
287 glog << "file_name string must contain \"%1%\" which is expanded to the current "
288 "application start time (e.g. 20190201T184925), unless omit.file_timestamp "
289 "== true. Erroneous file_name is: "
290 << file_format_str << std::endl;
291 }
292
293 file_format.exceptions(boost::io::all_error_bits ^
294 (boost::io::too_many_args_bit | boost::io::too_few_args_bit));
295
296 std::string file_name =
297 (file_format % goby::time::file_str() % app3_base_configuration_->name()).str();
298 glog.is_verbose() && glog << "logging output to file: " << file_name << std::endl;
299
300 fout_.reset(new std::ofstream(file_name.c_str()));
301
302 if (!fout_->is_open())
303 glog.is_die() && glog << "cannot write glog output to requested file: " << file_name
304 << std::endl;
305
306 if (!file_log.omit().latest_symlink())
307 {
308 std::string file_symlink =
309 (file_format % "latest" % app3_base_configuration_->name()).str();
310 remove(file_symlink.c_str());
311 int result = symlink(realpath(file_name.c_str(), NULL), file_symlink.c_str());
312 if (result != 0)
313 glog.is_warn() &&
314 glog << "Cannot create symlink to latest file. Continuing onwards anyway"
315 << std::endl;
316 }
317
318 glog.add_stream(file_log.verbosity(), fout_.get());
319
320 if (file_log.has_log_rotate_sec())
321 next_log_rotate_time_ =
322 goby::time::SteadyClock::now() + std::chrono::seconds(file_log.log_rotate_sec());
323}
324
325template <typename Config>
331
332template <typename Config> int goby::middleware::Application<Config>::__run()
333{
334 // block SIGWINCH (change window size) in all threads
335 sigset_t signal_mask;
336 sigemptyset(&signal_mask);
337 sigaddset(&signal_mask, SIGWINCH);
338 pthread_sigmask(SIG_BLOCK, &signal_mask, NULL);
339
340 this->pre_initialize();
341 this->initialize();
342 this->post_initialize();
343 // continue to run while we are alive (quit() has not been called)
344 while (alive_)
345 {
346 this->run_one();
347 this->check_rotate_glog_file();
348 }
349 this->pre_finalize();
350 this->finalize();
351 this->post_finalize();
352 return return_value_;
353}
354
355template <typename App>
357{
358 int return_value = 0;
359 try
360 {
361 try
362 {
363 cfgtor.validate();
364 }
366 {
367 cfgtor.handle_config_error(e);
368 return 1;
369 }
370
371 // simply print the configuration and exit
372 if (cfgtor.app_configuration().debug_cfg())
373 {
374 std::cout << cfgtor.str() << std::endl;
375 exit(EXIT_SUCCESS);
376 }
377
378 // set configuration
379 App::app_cfg_.reset(new typename App::ConfigType(cfgtor.cfg()));
380 App::app3_base_configuration_.reset(
382
383 // set up simulation time
384 if (App::app3_base_configuration_->simulation().time().use_sim_time())
385 {
388 App::app3_base_configuration_->simulation().time().warp_factor();
389 if (App::app3_base_configuration_->simulation().time().has_reference_microtime())
391 std::chrono::system_clock::time_point(std::chrono::microseconds(
392 App::app3_base_configuration_->simulation().time().reference_microtime()));
393 }
394
395 // instantiate the application (with the configuration already set)
396 App app;
397 return_value = app.__run();
398 }
399 catch (std::exception& e)
400 {
401 // some other exception
402 std::cerr << "Application:: uncaught exception: " << e.what() << std::endl;
403 throw;
404 }
405
406 goby::glog.is_debug2() && goby::glog << "goby::run: exiting cleanly with code: " << return_value
407 << std::endl;
408 return return_value;
409}
410
411#endif
simple exception class for goby applications
Definition exception.h:35
Base class for Goby applications. Generally you will want to use SingleThreadApplication or MultiThre...
Definition interface.h:78
const util::UTMGeodesy & geodesy()
Accesses the geodetic conversion tool if lat_origin and lon_origin were provided.
Definition interface.h:123
virtual void pre_finalize()
Called just before finalize.
Definition interface.h:102
virtual void post_initialize()
Called just after initialize.
Definition interface.h:96
virtual void initialize()
Perform any initialize tasks that couldn't be done in the constructor.
Definition interface.h:93
virtual void pre_initialize()
Called just before initialize.
Definition interface.h:90
virtual void run()=0
Runs once.
bool has_geodesy()
Returns if the geodesy tool is configured with a datum.
Definition interface.h:132
virtual void finalize()
Perform any final cleanup actions just before the destructor is called.
Definition interface.h:105
void quit(int return_value=0)
Requests a clean exit.
Definition interface.h:113
void configure_geodesy(goby::util::UTMGeodesy::LatLonPoint datum)
Definition interface.h:326
boost::units::quantity< boost::units::si::frequency > choose_loop_freq(boost::units::quantity< boost::units::si::frequency > compiled_loop_freq)
Definition interface.h:139
virtual void post_finalize()
Called just after finalize.
Definition interface.h:108
const Config & app_cfg()
Accesses configuration object passed at launch.
Definition interface.h:120
indicates a problem with the runtime command line or .cfg file configuration (or –help was given)
Defines the interface to a "configurator", a class that can read command line parameters (argc,...
virtual void validate() const
Override to validate the configuration.
virtual void handle_config_error(middleware::ConfigException &e) const
Override to customize how ConfigException errors are handled.
virtual const protobuf::AppConfig & app_configuration() const
Subset of the configuration used to configure the Application itself.
const Config & cfg() const
The configuration object produced from the command line parameters.
virtual std::string str() const =0
Override to output the configuration object as a string.
void remove_stream(std::ostream *os=nullptr)
void set_name(const std::string &s)
Set the name of the application that the logger is serving.
void add_stream(logger::Verbosity verbosity=logger::VERBOSE, std::ostream *os=nullptr)
Attach a stream object (e.g. std::cout, std::ofstream, ...) to the logger with desired verbosity.
std::string str(TimeType value=SystemClock::now< TimeType >())
Returns the provided time (or current time if omitted) as a human-readable string.
Definition convert.h:187
std::string file_str(TimeType value=SystemClock::now< TimeType >())
Returns the provided time (or current time if omitted) as an ISO string suitable for file names (no s...
Definition convert.h:200
The global namespace for the Goby project.
util::FlexOstream glog
Access the Goby logger through this object.
int run(const goby::middleware::ConfiguratorInterface< typename App::ConfigType > &cfgtor)
Run a Goby application using the provided Configurator.
Definition interface.h:356
static void set_crypto_passphrase(const std::string &passphrase, const std::set< dccl::int32 > &do_not_encrypt_ids=std::set< dccl::int32 >())
static void setup_dlog()
Enable dlog output to glog using same verbosity settings as glog.
static bool using_sim_time
Enables simulation time if true (if false, none of the remaining parameters are used)
Definition simulation.h:38
static std::chrono::system_clock::time_point reference_time
Reference time when calculating SystemClock::now(). If this is unset, the default is 1 January of the...
Definition simulation.h:42
static int warp_factor
Warp factor to speed up (or slow time) the time values returned by SteadyClock::now() and SystemClock...
Definition simulation.h:40
std::chrono::time_point< SteadyClock > time_point
static time_point now() noexcept
Returns the current steady time unless SimulatorSettings::using_sim_time == true in which case a simu...