From eaadabbb8e8e229bff361bb3ef762f3f1915db30 Mon Sep 17 00:00:00 2001 From: Rene Cannao Date: Wed, 18 Feb 2026 03:12:19 +0000 Subject: [PATCH] logger: fix thread-context map race in buffered logging --- include/MySQL_Logger.hpp | 3 +++ include/PgSQL_Logger.hpp | 3 +++ lib/log_utils.cpp | 27 +++++++++++---------------- 3 files changed, 17 insertions(+), 16 deletions(-) diff --git a/include/MySQL_Logger.hpp b/include/MySQL_Logger.hpp index 6169cefba..6e46ae936 100644 --- a/include/MySQL_Logger.hpp +++ b/include/MySQL_Logger.hpp @@ -3,6 +3,9 @@ #include "proxysql.h" #include "cpp.h" #include +#include +#include +#include #ifndef PROXYJSON #define PROXYJSON diff --git a/include/PgSQL_Logger.hpp b/include/PgSQL_Logger.hpp index 05842f8b4..044ae18ef 100644 --- a/include/PgSQL_Logger.hpp +++ b/include/PgSQL_Logger.hpp @@ -3,6 +3,9 @@ #include "proxysql.h" #include "cpp.h" #include +#include +#include +#include class LogBuffer; class LogBufferThreadContext; diff --git a/lib/log_utils.cpp b/lib/log_utils.cpp index ce1d4bd97..bcfafd8cc 100644 --- a/lib/log_utils.cpp +++ b/lib/log_utils.cpp @@ -123,24 +123,19 @@ bool LogBufferThreadContext::should_log(int rate_limit) { LogBufferThreadContext* GetLogBufferThreadContext(std::unordered_map>& log_thread_contexts, std::mutex& log_thread_contexts_lock, uint64_t current_time) { pthread_t tid = pthread_self(); - { - std::lock_guard lock(log_thread_contexts_lock); - auto it = log_thread_contexts.find(tid); - if (it != log_thread_contexts.end()) { - return it->second.get(); - } + std::lock_guard lock(log_thread_contexts_lock); + auto it = log_thread_contexts.find(tid); + if (it != log_thread_contexts.end()) { + return it->second.get(); } - + // Context doesn't exist for this thread, create it with proper initialization auto new_context = std::make_unique(); - LogBufferThreadContext* ptr = new_context.get(); // init() is already called in the constructor, which initializes both events and audit buffers - ptr->events.set_last_flush_time(current_time); - ptr->audit.set_last_flush_time(current_time); - - { - std::lock_guard lock(log_thread_contexts_lock); - log_thread_contexts[tid] = std::move(new_context); - } - return ptr; + new_context->events.set_last_flush_time(current_time); + new_context->audit.set_last_flush_time(current_time); + + LogBufferThreadContext* ptr = new_context.get(); + auto [insert_it, inserted] = log_thread_contexts.emplace(tid, std::move(new_context)); + return inserted ? ptr : insert_it->second.get(); }