forked from aldebaran/libqi
/
application.cpp
534 lines (462 loc) · 15 KB
/
application.cpp
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
/*
* Copyright (c) 2012, 2013 Aldebaran Robotics. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the COPYING file.
*/
#include <cstdlib>
#include <iostream>
#include <numeric>
#include <src/application_p.hpp>
#include <qi/application.hpp>
#include <qi/os.hpp>
#include <qi/atomic.hpp>
#include <qi/log.hpp>
#include <qi/path_conf.hpp>
#include <src/sdklayout.hpp>
#include <boost/program_options.hpp>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include "utils.hpp"
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
#ifdef _WIN32
#include <windows.h>
#endif
qiLogCategory("qi.Application");
namespace bfs = boost::filesystem;
static std::string _sdkPath;
static boost::program_options::options_description _options;
static void parseArguments(int argc, char* argv[])
{
namespace po = boost::program_options;
po::options_description desc("Application options");
desc.add_options()
("qi-sdk-prefix", po::value<std::string>(&_sdkPath), "The path of the SDK to use")
;
po::variables_map vm;
po::parsed_options parsed = po::command_line_parser(argc, argv).options(desc).allow_unregistered().run();
po::store(parsed, vm);
po::notify(vm);
qi::Application::setArguments(po::collect_unrecognized(parsed.options, po::include_positional));
qi::Application::options().add(desc);
}
namespace qi {
static int globalArgc = -1;
static std::vector<char*> globalArgv;
static bool globalInitialized = false;
static bool globalTerminated = false;
static std::string globalName;
static std::vector<std::string>* globalArguments;
static std::string globalPrefix;
static std::string globalProgram;
static std::string globalRealProgram;
using FunctionList = std::vector<std::function<void()>>;
using FunctionWithArgValueList = std::vector<std::pair<std::function<void(int)>, int>>;
static FunctionList* globalAtExit = nullptr;
static FunctionList* globalAtEnter = nullptr;
static FunctionWithArgValueList* globalAtSignal = nullptr;
static FunctionList* globalAtRun = nullptr;
static FunctionList* globalAtStop = nullptr;
static boost::optional<boost::asio::io_service> globalIoService;
static void readPathConf()
{
std::string prefix = ::qi::path::sdkPrefix();
std::vector<std::string> toAdd = ::qi::path::parseQiPathConf(prefix);
std::vector<std::string>::const_iterator it;
for (it = toAdd.begin(); it != toAdd.end(); ++it) {
::qi::path::detail::addOptionalSdkPrefix(it->c_str());
}
}
static void stop_handler(int signal_number)
{
qiLogVerbose() << "Signal " << signal_number << " received!";
static int count_int = 0;
static int count_term = 0;
int sigcount = 0;
if (signal_number == SIGINT) {
count_int++;
sigcount = count_int;
}
else if (signal_number == SIGTERM) {
count_term++;
sigcount = count_term;
}
switch (sigcount) {
case 1:
qiLogVerbose() << "Sending the stop command...";
//register the signal again to call exit the next time if stop did not succeed
Application::atSignal(boost::bind<void>(&stop_handler, _1), signal_number);
// Stop might immediately trigger application destruction, so it has
// to go after atSignal.
Application::stop();
return;
default:
//even for SIGTERM this is an error, so return 1.
qiLogVerbose() << "signal " << signal_number << " received a second time, calling exit(1).";
exit(1);
return;
}
}
static void signal_handler(const boost::system::error_code& error, int signal_number, std::function<void (int)> fun)
{
//when cancel is called the signal handler is raised with an error. catch it!
if (!error) {
fun(signal_number);
}
}
template<typename T> static T& lazyGet(T* & ptr)
{
if (!ptr)
ptr = new T;
return *ptr;
}
bool Application::atSignal(std::function<void (int)> func, int signal)
{
lazyGet(globalAtSignal).push_back(std::make_pair(std::move(func), signal));
return true;
}
qi::Path details::searchExecutableAbsolutePath(const qi::Path& path,
const bfs::path& currentDirectory,
std::vector<bfs::path> environmentPaths)
{
boost::system::error_code err;
const bfs::path boostPath(path);
if (boostPath.is_relative() && !boostPath.has_parent_path())
{
environmentPaths.insert(environmentPaths.begin(), currentDirectory);
return boost::process::search_path(boostPath, environmentPaths).make_preferred();
}
return bfs::absolute(boostPath, currentDirectory).make_preferred();
}
static void initApp(int& argc, char ** &argv, const std::string& path)
{
// this must be initialized first because readPathConf uses it (through
// sdklayout)
if (!path.empty())
{
globalProgram = path;
qiLogVerbose() << "Program path explicitely set to " << globalProgram;
}
else
{
globalProgram = details::searchExecutableAbsolutePath(qi::Path::fromNative(argv[0])).str();
qiLogVerbose() << "Program path guessed as " << globalProgram;
}
globalProgram = path::detail::normalize(globalProgram).str();
parseArguments(argc, argv);
readPathConf();
if (globalInitialized)
throw std::logic_error("Application was already initialized");
globalInitialized = true;
// We use only one thread (the main thread) for the application `io_service` that is used
// to process signals.
constexpr const auto ioServiceConcurrencyHint = 1;
globalIoService.emplace(ioServiceConcurrencyHint);
globalArgc = argc;
globalArgv = std::vector<char*>(argv, argv + argc);
std::vector<std::string>& args = lazyGet(globalArguments);
args.clear();
for (int i=0; i<argc; ++i)
args.push_back(argv[i]);
FunctionList& fl = lazyGet(globalAtEnter);
qiLogDebug() << "Executing " << fl.size() << " atEnter handlers";
for (FunctionList::iterator i = fl.begin(); i!= fl.end(); ++i)
{
try
{
(*i)();
}
catch (std::exception& e)
{
qiLogError() << "Application atEnter callback throw the following error: " << e.what();
}
}
fl.clear();
{
// Add the help option
namespace po = boost::program_options;
po::options_description helpDesc("Help options");
helpDesc.add_options() ("help,h", "Produces help message");
_options.add(helpDesc);
po::variables_map vm;
try
{
po::parsed_options parsed = po::command_line_parser(Application::arguments())
.options(_options)
.allow_unregistered()
.run();
po::store(parsed, vm);
po::notify(vm);
std::vector<std::string> args
= po::collect_unrecognized(parsed.options, po::include_positional);
if (vm.count("help"))
{
std::cout << _options << std::endl;
args.push_back("--help"); // Put the help argument back.
}
/* Set arguments to what was not used */
::qi::Application::setArguments(args);
argc = Application::argc();
argv = globalArgv.data();
}
catch (po::error& e)
{
qiLogError() << e.what();
}
}
}
Application::Application(int& argc, char ** &argv, const std::string& name,
const std::string& path)
{
globalName = name;
initApp(argc, argv, path);
}
Application::Application(const std::string &name, int& argc, char ** &argv)
{
globalName = name;
initApp(argc, argv, "");
}
void* Application::loadModule(const std::string& moduleName, int flags)
{
void* handle = os::dlopen(moduleName.c_str(), flags);
if (!handle)
{
throw std::runtime_error("Module \'" + moduleName + "\' not load: error was " + qi::os::dlerror());
}
else
{
qiLogDebug() << "Loadmodule " << handle;
}
// Reprocess atEnter list in case the module had AT_ENTER
FunctionList& fl = lazyGet(globalAtEnter);
qiLogDebug() << "Executing " << fl.size() << " atEnter handlers";
for (FunctionList::iterator i = fl.begin(); i!= fl.end(); ++i)
(*i)();
fl.clear();
return handle;
}
void Application::unloadModule(void* handle)
{
os::dlclose(handle);
}
Application::~Application()
{
FunctionList& fl = lazyGet(globalAtExit);
for (FunctionList::iterator i = fl.begin(); i!= fl.end(); ++i)
{
try
{
(*i)();
}
catch (std::exception& e)
{
qiLogError() << "Application atExit callback throw the following error: " << e.what();
}
}
globalIoService = boost::none;
globalTerminated = true;
}
void Application::run()
{
QI_ASSERT_TRUE(globalIoService);
// We use a list because signal_set is not moveable.
std::list<boost::asio::signal_set> signalSets;
auto atSignal = lazyGet(globalAtSignal);
// run is called, so we catch sigint/sigterm, the default
// implementation call Application::stop that
// will make this loop exit.
atSignal.emplace_back(boost::bind(stop_handler, _1), SIGTERM);
atSignal.emplace_back(boost::bind(stop_handler, _1), SIGINT);
for(const auto& func: atSignal)
signalSets.emplace(signalSets.end(), *globalIoService, func.second)->async_wait(
boost::bind(signal_handler, _1, _2, std::move(func.first)));
// Call every function registered as "atRun"
for(auto& function: lazyGet(globalAtRun))
function();
globalIoService->run();
}
void Application::stop()
{
static qi::Atomic<bool> atStopHandlerCall{false};
if (atStopHandlerCall.setIfEquals(false, true))
{
FunctionList& fl = lazyGet(globalAtStop);
qiLogDebug() << "Executing " << fl.size() << " atStop handlers";
for (FunctionList::iterator i = fl.begin(); i!= fl.end(); ++i)
{
try
{
(*i)();
}
catch (std::exception& e)
{
qiLogError() << "Application atStop callback throw the following error: " << e.what();
}
}
QI_ASSERT_TRUE(globalIoService);
globalIoService->stop();
}
}
void Application::setName(const std::string &name)
{
globalName = name;
}
std::string Application::name()
{
return globalName;
}
void Application::setArguments(const std::vector<std::string>& args)
{
globalArgc = static_cast<int>(args.size());
lazyGet(globalArguments) = args;
globalArgv.resize(args.size() + 1);
for (unsigned i=0; i<args.size(); ++i)
globalArgv[i] = qi::os::strdup(args[i].c_str());
globalArgv[args.size()] = 0;
}
void Application::setArguments(int argc, char** argv)
{
globalArgc = argc;
globalArgv = std::vector<char*>(argv, argv + argc);
std::vector<std::string>& args = lazyGet(globalArguments);
args.resize(argc);
for (int i=0; i<argc; ++i)
args[i] = argv[i];
}
bool Application::initialized()
{
return globalInitialized;
}
bool Application::terminated()
{
return globalTerminated;
}
int Application::argc()
{
return globalArgc;
}
const char** Application::argv()
{
return const_cast<const char**>(globalArgv.data());
}
bool Application::atEnter(std::function<void()> func)
{
qiLogDebug() << "atEnter";
lazyGet(globalAtEnter).push_back(func);
return true;
}
bool Application::atExit(std::function<void()> func)
{
lazyGet(globalAtExit).push_back(func);
return true;
}
bool Application::atRun(std::function<void ()> func)
{
lazyGet(globalAtRun).push_back(func);
return true;
}
bool Application::atStop(std::function<void()> func)
{
lazyGet(globalAtStop).push_back(func);
return true;
}
const std::vector<std::string>& Application::arguments()
{
return lazyGet(globalArguments);
}
const char *Application::program()
{
return globalProgram.c_str();
}
/*
http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe
Some OS-specific interfaces:
Mac OS X: _NSGetExecutablePath() (man 3 dyld)
Linux : readlink /proc/self/exe
Solaris : getexecname()
FreeBSD : sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1
BSD with procfs: readlink /proc/curproc/file
Windows : GetModuleFileName() with hModule = NULL
The portable (but less reliable) method is to use argv[0].
Although it could be set to anything by the calling program,
by convention it is set to either a path name of the executable
or a name that was found using $PATH.
Some shells, including bash and ksh, set the environment variable "_"
to the full path of the executable before it is executed. In that case
you can use getenv("_") to get it. However this is unreliable because
not all shells do this, and it could be set to anything or be left over
from a parent process which did not change it before executing your program.
*/
const char *Application::realProgram()
{
try
{
if (!globalRealProgram.empty())
return globalRealProgram.c_str();
#ifdef __APPLE__
{
char *fname = (char *)malloc(PATH_MAX);
uint32_t sz = PATH_MAX;
fname[0] = 0;
int ret;
ret = _NSGetExecutablePath(fname, &sz);
if (ret == 0)
{
globalRealProgram = fname;
globalRealProgram = path::detail::normalize(globalRealProgram).str();
}
else
{
globalRealProgram = details::searchExecutableAbsolutePath(qi::Path::fromNative(::qi::Application::argv()[0])).str();
}
free(fname);
}
#elif __linux__
boost::filesystem::path p("/proc/self/exe");
boost::filesystem::path fname = boost::filesystem::read_symlink(p);
if (!boost::filesystem::is_empty(fname))
globalRealProgram = fname.string().c_str();
else
globalRealProgram = details::searchExecutableAbsolutePath(qi::Path::fromNative(::qi::Application::argv()[0])).str();
#elif _WIN32
WCHAR fname[MAX_PATH];
int ret = GetModuleFileNameW(NULL, fname, MAX_PATH);
if (ret > 0)
{
fname[ret] = '\0';
boost::filesystem::path programPath(fname, qi::unicodeFacet());
globalRealProgram = programPath.string(qi::unicodeFacet());
}
else
{
// GetModuleFileName failed, trying to guess from argc, argv...
globalRealProgram = details::searchExecutableAbsolutePath(qi::Path::fromNative(::qi::Application::argv()[0])).str();
}
#else
globalRealProgram = details::searchExecutableAbsolutePath(qi::Path::fromNative(::qi::Application::argv()[0])).str();
#endif
return globalRealProgram.c_str();
}
catch (...)
{
return NULL;
}
}
const char* Application::_suggestedSdkPath()
{
return _sdkPath.c_str();
}
boost::program_options::options_description& Application::options()
{
return _options;
}
std::string Application::helpText()
{
std::ostringstream ss;
ss << _options;
return ss.str();
}
}