From db68d733335dcaf4be3facfd74001c7b8df4bfac Mon Sep 17 00:00:00 2001 From: Gijs Koning Date: Wed, 20 Apr 2022 06:03:23 -0700 Subject: [PATCH] swaglog: delay creating zmq socket to first use - fix modeld crash in sim (#24271) * Initialize zmq socket later with initialize method * empty lines * Add lock and move initialize function * Check for initialized old-commit-hash: 6ab7b2f32562fdb155a14e64c5c2b963f9345b33 --- selfdrive/common/statlog.cc | 3 +++ selfdrive/common/swaglog.cc | 6 ++---- selfdrive/common/util.h | 22 ++++++++++++++++------ 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/selfdrive/common/statlog.cc b/selfdrive/common/statlog.cc index 27dfc2ca9d..54463e9816 100644 --- a/selfdrive/common/statlog.cc +++ b/selfdrive/common/statlog.cc @@ -17,6 +17,9 @@ class StatlogState : public LogState { static StatlogState s = {}; static void log(const char* metric_type, const char* metric, const char* fmt, ...) { + std::lock_guard lk(s.lock); + if (!s.initialized) s.initialize(); + char* value_buf = nullptr; va_list args; va_start(args, fmt); diff --git a/selfdrive/common/swaglog.cc b/selfdrive/common/swaglog.cc index 30e087dc29..21115da10f 100644 --- a/selfdrive/common/swaglog.cc +++ b/selfdrive/common/swaglog.cc @@ -21,7 +21,6 @@ class SwaglogState : public LogState { public: SwaglogState() : LogState("ipc:///tmp/logmessage") {} - bool initialized = false; json11::Json::object ctx_j; inline void initialize() { @@ -56,8 +55,7 @@ class SwaglogState : public LogState { } else { ctx_j["device"] = "pc"; } - - initialized = true; + LogState::initialize(); } }; @@ -113,7 +111,7 @@ void cloudlog_t_common(int levelnum, const char* filename, int lineno, const cha char* msg_buf = nullptr; int ret = vasprintf(&msg_buf, fmt, args); if (ret <= 0 || !msg_buf) return; - json11::Json::object tspt_j = json11::Json::object{ + json11::Json::object tspt_j = json11::Json::object{ {"event", msg_buf}, {"time", std::to_string(nanos_since_boot())} }; diff --git a/selfdrive/common/util.h b/selfdrive/common/util.h index bf0df3bcaa..f3a24723b4 100644 --- a/selfdrive/common/util.h +++ b/selfdrive/common/util.h @@ -168,12 +168,18 @@ void update_max_atomic(std::atomic& max, T const& value) { class LogState { public: + bool initialized = false; std::mutex lock; - void *zctx; - void *sock; + void *zctx = nullptr; + void *sock = nullptr; int print_level; + const char* endpoint; - LogState(const char* endpoint) { + LogState(const char* _endpoint) { + endpoint = _endpoint; + } + + inline void initialize() { zctx = zmq_ctx_new(); sock = zmq_socket(zctx, ZMQ_PUSH); @@ -182,9 +188,13 @@ class LogState { zmq_setsockopt(sock, ZMQ_LINGER, &timeout, sizeof(timeout)); zmq_connect(sock, endpoint); - }; + initialized = true; + } + ~LogState() { - zmq_close(sock); - zmq_ctx_destroy(zctx); + if (initialized) { + zmq_close(sock); + zmq_ctx_destroy(zctx); + } } };