Goby3 3.6.1
2026.09.15
Loading...
Searching...
No Matches
interface.h
Go to the documentation of this file.
1// Copyright 2011-2026:
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 <cstdlib>
31#include <iostream>
32#include <sys/types.h>
33#include <unistd.h>
34
35#include <boost/format.hpp>
36
37#include "goby/exception.h"
42#include "goby/time.h"
44#include "goby/util/geodesy.h"
45
46namespace goby
47{
54template <typename App>
56
63template <typename App,
64 typename Configurator = middleware::ProtobufConfigurator<typename App::ConfigType>>
65int run(int argc, char* argv[])
66{
67 return run<App>(Configurator(argc, argv));
68}
69
70namespace middleware
71{
72
73namespace julia
74{
75template <typename App> class ApplicationWrapper;
76}
77
78namespace python
79{
80template <typename App> class ApplicationWrapper;
81}
82
84template <typename Config> class Application
85{
86 public:
88 virtual ~Application()
89 {
90 goby::glog.is_debug2() && goby::glog << "Application: destructing cleanly" << std::endl;
91 }
92
93 using ConfigType = Config;
94
95 protected:
97 virtual void pre_initialize() {};
98
100 virtual void initialize() {};
101
103 virtual void post_initialize() {};
104
106 virtual void run() = 0;
107
109 virtual void pre_finalize() {};
110
112 virtual void finalize() {};
113
115 virtual void post_finalize() {};
116
120 void quit(int return_value = 0)
121 {
122 alive_ = false;
123 return_value_ = return_value;
124 }
125
127 const Config& app_cfg() { return *app_cfg_; }
128
131 {
132 if (geodesy_)
133 return *geodesy_;
134 else
135 throw(goby::Exception("No lat_origin and lon_origin defined for requested UTMGeodesy"));
136 }
137
139 bool has_geodesy() { return geodesy_ ? true : false; }
140
141 std::string app_name() { return app3_base_configuration_->name(); }
142
143 bool app_alive() { return alive_; }
144
145 boost::units::quantity<boost::units::si::frequency>
146 choose_loop_freq(boost::units::quantity<boost::units::si::frequency> compiled_loop_freq)
147 {
148 if (app3_base_configuration_->has_loop_frequency())
149 return app3_base_configuration_->loop_frequency_with_units();
150 else
151 return compiled_loop_freq;
152 }
153
154 protected:
156
157 private:
158 template <typename App>
159 friend int ::goby::run(
161
162 template <typename App> friend class goby::middleware::julia::ApplicationWrapper;
163 template <typename App> friend class goby::middleware::python::ApplicationWrapper;
164
165 // main loop that exits on quit(); returns the desired return value
166 int __run();
167
168 void run_one() { run(); }
169
170 void configure_logger();
171 void configure_glog_file();
172 void configure_intervehicle();
173 void check_rotate_glog_file();
174
175 private:
176 // sets configuration (before Application construction)
177 static std::unique_ptr<Config> app_cfg_;
178 static std::unique_ptr<protobuf::AppConfig> app3_base_configuration_;
179
180 bool alive_;
181 int return_value_;
182
183 // static here allows fout_ to live until program exit to log glog output
184 static std::unique_ptr<std::ofstream> fout_;
185
186 goby::time::SteadyClock::time_point next_log_rotate_time_;
187
188 std::unique_ptr<goby::util::UTMGeodesy> geodesy_;
189};
190} // namespace middleware
191
192} // namespace goby
193
194template <typename Config>
195std::unique_ptr<std::ofstream> goby::middleware::Application<Config>::fout_;
196
197template <typename Config> std::unique_ptr<Config> goby::middleware::Application<Config>::app_cfg_;
198
199template <typename Config>
200std::unique_ptr<goby::middleware::protobuf::AppConfig>
202
203template <typename Config> goby::middleware::Application<Config>::Application() : alive_(true)
204{
205 using goby::glog;
206
207 configure_logger();
208 if (app3_base_configuration_->has_geodesy())
209 configure_geodesy({app3_base_configuration_->geodesy().lat_origin_with_units(),
210 app3_base_configuration_->geodesy().lon_origin_with_units()});
211
212 if (app3_base_configuration_->has_intervehicle_cfg())
213 configure_intervehicle();
214
215 if (!app3_base_configuration_->IsInitialized())
216 throw(middleware::ConfigException("Invalid base configuration"));
217
218 glog.is_debug2() && glog << "Application: constructed with PID: " << getpid() << std::endl;
219 glog.is_debug1() && glog << "App name is " << app3_base_configuration_->name() << std::endl;
220 glog.is_debug2() && glog << "Configuration is: " << app_cfg_->DebugString() << std::endl;
221}
222
223template <typename Config> void goby::middleware::Application<Config>::configure_logger()
224{
225 using goby::glog;
226
227 // set up the logger
228 glog.set_name(app3_base_configuration_->name());
230 app3_base_configuration_->glog_config().tty_verbosity()),
231 &std::cout);
232
233 if (app3_base_configuration_->glog_config().show_gui())
235
236 if (app3_base_configuration_->glog_config().has_file_log())
237 configure_glog_file();
238
239 if (app3_base_configuration_->glog_config().show_dccl_log())
241}
242
244{
246 app3_base_configuration_->intervehicle_cfg();
247
248 if (intervehicle_cfg.has_dccl_passphrase())
249 {
251 intervehicle_cfg.dccl_passphrase());
252 }
253}
254
256{
257 using goby::glog;
258 if (app3_base_configuration_->glog_config().has_file_log() &&
259 app3_base_configuration_->glog_config().file_log().has_log_rotate_sec() &&
260 goby::time::SteadyClock::now() > next_log_rotate_time_)
261 {
262 glog.remove_stream(fout_.get());
263 configure_glog_file();
264 }
265}
266
268{
269 const auto& file_log = app3_base_configuration_->glog_config().file_log();
270 std::string file_format_str;
271
272 std::string file_name_format = file_log.file_name();
273
274 if (!file_log.has_file_name() && file_log.omit().file_timestamp())
275 file_name_format = "%2%.txt";
276
277 if (file_log.has_file_dir() && !file_log.file_dir().empty())
278 {
279 auto file_dir = file_log.file_dir();
280 if (file_dir.back() != '/')
281 file_dir += "/";
282 file_format_str = file_dir + file_name_format;
283 }
284 else
285 {
286 file_format_str = file_name_format;
287 }
288
289 boost::format file_format(file_format_str);
290
291 if (!file_log.omit().file_timestamp())
292 {
293 if (file_format_str.find("%1") == std::string::npos)
294 glog.is_die() &&
295 glog << "file_name string must contain \"%1%\" which is expanded to the current "
296 "application start time (e.g. 20190201T184925), unless omit.file_timestamp "
297 "== true. Erroneous file_name is: "
298 << file_format_str << std::endl;
299 }
300
301 file_format.exceptions(boost::io::all_error_bits ^
302 (boost::io::too_many_args_bit | boost::io::too_few_args_bit));
303
304 std::string file_name =
305 (file_format % goby::time::file_str() % app3_base_configuration_->name()).str();
306 glog.is_verbose() && glog << "logging output to file: " << file_name << std::endl;
307
308 fout_.reset(new std::ofstream(file_name.c_str()));
309
310 if (!fout_->is_open())
311 glog.is_die() && glog << "cannot write glog output to requested file: " << file_name
312 << std::endl;
313
314 if (!file_log.omit().latest_symlink())
315 {
316 std::string file_symlink =
317 (file_format % "latest" % app3_base_configuration_->name()).str();
318 remove(file_symlink.c_str());
319 char* resolved = realpath(file_name.c_str(), nullptr);
320 if (resolved != nullptr)
321 {
322 int result = symlink(resolved, file_symlink.c_str());
323 free(resolved);
324 if (result != 0)
325 glog.is_warn() &&
326 glog << "Cannot create symlink to latest file. Continuing onwards anyway"
327 << std::endl;
328 }
329 }
330
331 glog.add_stream(file_log.verbosity(), fout_.get());
332
333 if (file_log.has_log_rotate_sec())
334 next_log_rotate_time_ =
335 goby::time::SteadyClock::now() + std::chrono::seconds(file_log.log_rotate_sec());
336}
337
338template <typename Config>
344
345template <typename Config> int goby::middleware::Application<Config>::__run()
346{
347 // block SIGWINCH (change window size) in all threads
348 sigset_t signal_mask;
349 sigemptyset(&signal_mask);
350 sigaddset(&signal_mask, SIGWINCH);
351 pthread_sigmask(SIG_BLOCK, &signal_mask, NULL);
352
353 this->pre_initialize();
354 this->initialize();
355 this->post_initialize();
356 // continue to run while we are alive (quit() has not been called)
357 while (alive_)
358 {
359 this->run_one();
360 this->check_rotate_glog_file();
361 }
362 this->pre_finalize();
363 this->finalize();
364 this->post_finalize();
365 return return_value_;
366}
367
368template <typename App>
370{
371 int return_value = 0;
372 try
373 {
374 try
375 {
376 cfgtor.validate();
377 }
379 {
380 cfgtor.handle_config_error(e);
381 return 1;
382 }
383
384 // simply print the configuration and exit
385 if (cfgtor.app_configuration().debug_cfg())
386 {
387 std::cout << cfgtor.str() << std::endl;
388 exit(EXIT_SUCCESS);
389 }
390
391 // set configuration
392 App::app_cfg_.reset(new typename App::ConfigType(cfgtor.cfg()));
393 App::app3_base_configuration_.reset(
395
396 // set up simulation time
397 middleware::detail::configure_simulation_time(*App::app3_base_configuration_);
398
399 // instantiate the application (with the configuration already set)
400 App app;
401 return_value = app.__run();
402 }
403 catch (std::exception& e)
404 {
405 // some other exception
406 std::cerr << "Application:: uncaught exception: " << e.what() << std::endl;
407 throw;
408 }
409
410 goby::glog.is_debug2() && goby::glog << "goby::run: exiting cleanly with code: " << return_value
411 << std::endl;
412 return return_value;
413}
414
415#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:85
const util::UTMGeodesy & geodesy()
Accesses the geodetic conversion tool if lat_origin and lon_origin were provided.
Definition interface.h:130
virtual void pre_finalize()
Called just before finalize.
Definition interface.h:109
virtual void post_initialize()
Called just after initialize.
Definition interface.h:103
virtual void initialize()
Perform any initialize tasks that couldn't be done in the constructor.
Definition interface.h:100
virtual void pre_initialize()
Called just before initialize.
Definition interface.h:97
virtual void run()=0
Runs once.
bool has_geodesy()
Returns if the geodesy tool is configured with a datum.
Definition interface.h:139
virtual void finalize()
Perform any final cleanup actions just before the destructor is called.
Definition interface.h:112
void quit(int return_value=0)
Requests a clean exit.
Definition interface.h:120
void configure_geodesy(goby::util::UTMGeodesy::LatLonPoint datum)
Definition interface.h:339
boost::units::quantity< boost::units::si::frequency > choose_loop_freq(boost::units::quantity< boost::units::si::frequency > compiled_loop_freq)
Definition interface.h:146
virtual void post_finalize()
Called just after finalize.
Definition interface.h:115
const Config & app_cfg()
Accesses configuration object passed at launch.
Definition interface.h:127
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.
The class exposed to Python; user application classes subclass this.
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.
void configure_simulation_time(const protobuf::AppConfig &app_cfg)
Applies the simulation time settings from an application configuration to goby::time::SimulatorSettin...
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:369
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.
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...