Skip to content

Commit cc500a7

Browse files
committed
Fix port lambda capture bug and handle port binding issues.
1 parent 7bec904 commit cc500a7

File tree

8 files changed

+70
-30
lines changed

8 files changed

+70
-30
lines changed

debian/postinst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ chmod 644 /opt/cosmos/lib/systemd/system/${SRV_NAME}.service
1818
chmod 644 /opt/cosmos/etc/dbus-1/system.d/com.syriusrobotics.${SRV_NAME}.conf
1919
chmod 750 /opt/cosmos/bin/${SRV_NAME}
2020

21+
mkdir -p /var/log/dbus2http
22+
chown ${USER_NAME}:${USER_NAME} /var/log/dbus2http
23+
2124
systemctl enable --now /opt/cosmos/lib/systemd/system/${SRV_NAME}.service
2225

2326
sync

include/dbus2http/Dbus2Http.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ class Dbus2Http {
2626
public:
2727
Dbus2Http(const std::vector<std::string>& service_prefixes, bool system_bus);
2828

29-
void start(int port, int ws_port);
29+
void start(int port, int ws_port,
30+
const std::function<void()>& on_failed = nullptr);
3031

3132
void stop();
3233

include/dbus2http/FileLineFormatter.h

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,26 +8,30 @@
88

99
namespace dbus2http {
1010

11+
template<bool date_time, bool tid>
1112
class FileLineFormatter {
1213
public:
1314
static plog::util::nstring header() { return plog::util::nstring(); }
1415
static plog::util::nstring format(const plog::Record& record) {
1516
tm t;
1617
plog::util::localtime_s(&t, &record.getTime().time);
1718
plog::util::nostringstream ss;
18-
ss << t.tm_year + 1900 << "-" << std::setfill(PLOG_NSTR('0'))
19-
<< std::setw(2) << t.tm_mon + 1 << PLOG_NSTR("-")
20-
<< std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_mday
21-
<< PLOG_NSTR(" ");
22-
ss << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_hour
23-
<< PLOG_NSTR(":") << std::setfill(PLOG_NSTR('0')) << std::setw(2)
24-
<< t.tm_min << PLOG_NSTR(":") << std::setfill(PLOG_NSTR('0'))
25-
<< std::setw(2) << t.tm_sec << PLOG_NSTR(".")
26-
<< std::setfill(PLOG_NSTR('0')) << std::setw(3)
27-
<< static_cast<int>(record.getTime().millitm) << PLOG_NSTR(" ");
19+
if (date_time) {
20+
ss << t.tm_year + 1900 << "-" << std::setfill(PLOG_NSTR('0'))
21+
<< std::setw(2) << t.tm_mon + 1 << PLOG_NSTR("-")
22+
<< std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_mday
23+
<< PLOG_NSTR(" ");
24+
ss << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_hour
25+
<< PLOG_NSTR(":") << std::setfill(PLOG_NSTR('0')) << std::setw(2)
26+
<< t.tm_min << PLOG_NSTR(":") << std::setfill(PLOG_NSTR('0'))
27+
<< std::setw(2) << t.tm_sec << PLOG_NSTR(".")
28+
<< std::setfill(PLOG_NSTR('0')) << std::setw(3)
29+
<< static_cast<int>(record.getTime().millitm) << PLOG_NSTR(" ");
30+
}
2831
ss << std::setfill(PLOG_NSTR(' ')) << std::setw(5) << std::left
2932
<< severityToString(record.getSeverity()) << PLOG_NSTR(" ");
30-
ss << PLOG_NSTR("[") << record.getTid() << PLOG_NSTR("] ");
33+
if (tid)
34+
ss << PLOG_NSTR("[") << record.getTid() << PLOG_NSTR("] ");
3135
// ss << PLOG_NSTR("[") << record.getFunc() << PLOG_NSTR("@") <<
3236
// record.getLine() << PLOG_NSTR("] ");
3337
ss << PLOG_NSTR("[") << basename(std::string(record.getFile()))

include/dbus2http/WebService.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ class WebService {
2222

2323
bool run(int port, int ws_port) {
2424
ws_port_ = ws_port;
25+
PLOGI << "listen port " << port;
2526
return server_.listen("0.0.0.0", port);
2627
}
2728

src/Dbus2Http.cpp

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,18 +12,24 @@ Dbus2Http::Dbus2Http(const std::vector<std::string>& service_prefixes,
1212
conn_ = DbusUtils::createConnection(system_bus_);
1313
}
1414

15-
void Dbus2Http::start(int port, int ws_port) {
15+
void Dbus2Http::start(int port, int ws_port,
16+
const std::function<void()>& on_failed) {
1617
dbus_caller_ = std::make_unique<DbusCaller>(context_, system_bus_);
1718
service_ = std::make_unique<WebService>(*dbus_caller_);
18-
service_thread_ = std::thread([&] { service_->run(port, ws_port); });
19+
service_thread_ = std::thread([this, port, ws_port, on_failed] {
20+
bool ret = service_->run(port, ws_port);
21+
if (not stop_ and not ret) {
22+
PLOGE << "start http service failed";
23+
if (on_failed) on_failed();
24+
}
25+
});
1926
update_thread_ = std::thread([&] {
2027
while (not stop_) {
2128
update();
22-
for (int i = 0; i < 60 and not stop_; ++i)
29+
for (int i = 0; i < 30 and not stop_; ++i)
2330
std::this_thread::sleep_for(std::chrono::seconds(1));
2431
}
2532
});
26-
PLOGI << "dbus2http started on port " << port << "...";
2733
}
2834

2935
void Dbus2Http::stop() {

src/WebService.cpp

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ bool WebService::parse_dbus_request_path(const std::string& path,
1818
std::string& object_path,
1919
std::string& interface_name,
2020
std::string& method) {
21-
std::string rem = path;
21+
const std::string& rem = path;
2222
const auto first_slash = rem.find('/');
2323
if (first_slash == std::string::npos) {
2424
return false; // missing components
@@ -44,7 +44,7 @@ bool WebService::parse_dbus_request_path(const std::string& path,
4444
return true;
4545
}
4646

47-
WebService::WebService(DbusCaller& caller) : caller_(caller) {
47+
WebService::WebService(DbusCaller& caller) : caller_(caller), ws_port_(10058) {
4848
std::string header = R"(
4949
<!DOCTYPE html>
5050
<html>
@@ -247,6 +247,14 @@ WebService::WebService(DbusCaller& caller) : caller_(caller) {
247247
res.status = 200;
248248
res.set_content(match_rule_html, "text/html");
249249
});
250+
server_.set_pre_routing_handler(
251+
[](const httplib::Request& req, httplib::Response& res) {
252+
auto now = std::chrono::system_clock::now();
253+
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
254+
PLOGD << "[" << std::ctime(&now_c) << "] "
255+
<< "New request: " << req.method << " " << req.path << std::endl;
256+
return httplib::Server::HandlerResponse::Unhandled;
257+
});
250258
server_.set_logger([](const auto& req, const auto& res) {
251259
// Timestamp
252260
auto now = std::chrono::system_clock::now();

src/main.cpp

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include <plog/Appenders/ConsoleAppender.h>
2+
#include <plog/Appenders/RollingFileAppender.h>
23
#include <plog/Formatters/TxtFormatter.h>
34
#include <plog/Initializers/ConsoleInitializer.h>
45
#include <plog/Log.h>
@@ -52,15 +53,6 @@ int main(int argc, char* argv[]) {
5253
std::signal(SIGINT, handle_sigint);
5354
std::signal(SIGTERM, handle_sigint);
5455

55-
// initialize logging
56-
static plog::ColorConsoleAppender<dbus2http::FileLineFormatter>
57-
consoleAppender;
58-
#ifdef NDEBUG
59-
plog::init(plog::info, &consoleAppender);
60-
#else
61-
plog::init(plog::debug, &consoleAppender);
62-
#endif
63-
6456
// parse arguments
6557
argparse::ArgumentParser program("dbus2http", VERSION_BUILD_NUMBER);
6658
program.add_description("A D-Bus to HTTP proxy server.");
@@ -81,8 +73,25 @@ int main(int argc, char* argv[]) {
8173
program.add_argument("--service_prefix")
8274
.nargs(argparse::nargs_pattern::at_least_one)
8375
.help("Only expose services with the given prefix");
76+
program.add_argument("-v", "--verbose")
77+
.help("print debug log")
78+
.default_value(false)
79+
.implicit_value(true);
80+
81+
static plog::ColorConsoleAppender<dbus2http::FileLineFormatter<false, false>>
82+
consoleAppender;
83+
static plog::RollingFileAppender<dbus2http::FileLineFormatter<true, true>> fileAppender("/var/log/dbus2http/dbus2http.log", 10000000, 5);
84+
8485
try {
8586
program.parse_args(argc, argv);
87+
#ifdef NDEBUG
88+
if (program.get<bool>("--verbose"))
89+
plog::init(plog::debug, &consoleAppender).addAppender(&fileAppender);
90+
else
91+
plog::init(plog::info, &consoleAppender).addAppender(&fileAppender);
92+
#else
93+
plog::init(plog::debug, &consoleAppender);
94+
#endif
8695
} catch (const std::exception& e) {
8796
PLOGE << "argument parsing error: " << e.what() << std::endl << program;
8897
return 1;
@@ -118,15 +127,23 @@ int main(int argc, char* argv[]) {
118127
// launch dbus2http proxy
119128
PLOGI << "Starting dbus2http...";
120129
dbus2http::Dbus2Http dbus2http(service_prefix, program.get<bool>("--system"));
121-
dbus2http.start(program.get<int>("--port"), program.get<int>("--websocket_port"));
130+
dbus2http.start(program.get<int>("--port"),
131+
program.get<int>("--websocket_port"),
132+
[] { g_running.store(false); });
122133

123134
dbus2http::SignalSocket signal_socket(dbus2http.getContext(),
124135
program.get<bool>("--system"),
125136
program.get<int>("--websocket_port"));
126137
signal_socket.start();
127138

139+
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
140+
PLOGI << "dbus2http started on port " << program.get<int>("--port") << "...";
141+
142+
int i = 0;
128143
while (g_running.load()) {
129-
std::this_thread::sleep_for(std::chrono::milliseconds(200));
144+
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
145+
if (i++ % 10 == 0)
146+
PLOGD << "dbus2http keep running...";
130147
}
131148

132149
PLOGI << "Stopping signal socket...";

tests/test_methods.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ void run_one_case(httplib::Client& client, const std::string& request,
5757
REQUIRE(res->body == req_j.dump());
5858
}
5959

60-
static plog::ConsoleAppender<FileLineFormatter> consoleAppender;
60+
static plog::ConsoleAppender<FileLineFormatter<false, false>> consoleAppender;
6161
std::unique_ptr<sdbus::IConnection> conn;
6262
std::thread dbus_thread;
6363
std::unique_ptr<Dbus2Http> dbus2http;

0 commit comments

Comments
 (0)