This is an automated email from the ASF dual-hosted git repository. fgerlits pushed a commit to branch MINIFICPP-2877_Reorganize-BackTrace in repository https://gitbox.apache.org/repos/asf/nifi-minifi-cpp.git
commit 570f870e1f4a409836de1d565767d238824444e0 Author: Ferenc Gerlits <[email protected]> AuthorDate: Wed Nov 11 10:11:51 2026 +0100 MINIFICPP-2877 Reorganize BackTrace - make sure that no heap allocations are done from the signal handler - fix the display of C functions: they used to show the file name only - simplify the interface - fix the unit test: some of it used to be always skipped --- controller/tests/ControllerTests.cpp | 23 ++- core-framework/include/core/ThreadedRepository.h | 4 +- core-framework/include/utils/BackTrace.h | 151 +-------------- core-framework/include/utils/ThreadPool.h | 6 +- core-framework/src/utils/BackTrace.cpp | 204 ++++++++++++++------- libminifi/include/FlowController.h | 2 +- libminifi/include/core/state/UpdateController.h | 2 +- libminifi/src/FlowController.cpp | 13 +- libminifi/src/c2/C2Agent.cpp | 10 +- libminifi/src/c2/ControllerSocketProtocol.cpp | 4 +- libminifi/test/unit/BackTraceTests.cpp | 57 ++++-- libminifi/test/unit/CMakeLists.txt | 7 + .../include/minifi-cpp/core/TraceableResource.h | 2 +- 13 files changed, 222 insertions(+), 263 deletions(-) diff --git a/controller/tests/ControllerTests.cpp b/controller/tests/ControllerTests.cpp index 4d815e057..5665c26f4 100644 --- a/controller/tests/ControllerTests.cpp +++ b/controller/tests/ControllerTests.cpp @@ -36,6 +36,7 @@ #include "core/state/nodes/ResponseNodeLoader.h" using namespace std::literals::chrono_literals; +using BackTrace = utils::trace_resolver::BackTrace; namespace org::apache::nifi::minifi::test { @@ -79,15 +80,13 @@ class TestStateController : public minifi::state::StateController { std::atomic<bool> is_running; }; -class TestBackTrace : public BackTrace { - public: - using BackTrace::BackTrace; - void addTraceLines(uint32_t line_count) { - for (uint32_t i = 1; i <= line_count; ++i) { - addLine("bt line " + std::to_string(i) + " for " + getName()); - } +namespace { +void addTraceLines(BackTrace& back_trace, uint32_t line_count) { + for (uint32_t i = 1; i <= line_count; ++i) { + back_trace.trace.push_back(minifi::utils::string::join_pack("bt line ", std::to_string(i), " for ", back_trace.name)); } -}; +} +} // namespace class TestUpdateSink : public minifi::state::StateMonitor { public: @@ -138,11 +137,11 @@ class TestUpdateSink : public minifi::state::StateMonitor { } std::vector<BackTrace> getTraces() override { std::vector<BackTrace> traces; - TestBackTrace trace1("trace1"); - trace1.addTraceLines(2); + BackTrace trace1{.name = std::string{"trace1"}, .trace = {}}; + addTraceLines(trace1, 2); traces.push_back(trace1); - TestBackTrace trace2("trace2"); - trace2.addTraceLines(3); + BackTrace trace2{.name = std::string{"trace2"}, .trace = {}}; + addTraceLines(trace2, 3); traces.push_back(trace2); return traces; } diff --git a/core-framework/include/core/ThreadedRepository.h b/core-framework/include/core/ThreadedRepository.h index 19942d457..fa0a78a20 100644 --- a/core-framework/include/core/ThreadedRepository.h +++ b/core-framework/include/core/ThreadedRepository.h @@ -80,13 +80,13 @@ class ThreadedRepositoryImpl : public core::RepositoryImpl, public virtual core: return running_state_.load() == RunningState::Running; } - BackTrace getTraces() override { + utils::trace_resolver::BackTrace getTraces() override { // If the thread is joinable then it is finished, we cannot interrupt and collect its stack traces // It can occur with an empty run() implementation like the NoOpThreadedRepository where the stack trace is unavailable if (getThread().joinable()) { return {}; } - return TraceResolver::getResolver().getBackTrace(getName(), getThread().native_handle()); + return utils::trace_resolver::getBackTrace(getName(), getThread().native_handle()); } private: diff --git a/core-framework/include/utils/BackTrace.h b/core-framework/include/utils/BackTrace.h index 1f4e558bc..a2c31e3d8 100644 --- a/core-framework/include/utils/BackTrace.h +++ b/core-framework/include/utils/BackTrace.h @@ -17,153 +17,18 @@ #pragma once #include <string> - -#ifdef HAS_EXECINFO -#include <execinfo.h> -#include <csignal> -#endif +#include <string_view> #include <thread> -#include <utility> #include <vector> -#include <mutex> -#include <condition_variable> -#include <iostream> -#include <sstream> -#include <memory> - -#define TRACE_BUFFER_SIZE 128 - -/** - * Forward declaration allows us to tightly couple TraceResolver - * with BackTrace. - */ -class TraceResolver; -/** - * Purpose: Backtrace is a vector of trace lines. - * - */ -class BackTrace { - public: - BackTrace() = default; +namespace org::apache::nifi::minifi::utils::trace_resolver { - BackTrace(std::string name) // NOLINT - : name_(std::move(name)) { - } - - std::vector<std::string> getTraces() const { - return trace_; - } - - /** - * Return thread name of f this caller - * @returns name ; - */ - std::string getName() const { - return name_; - } - - protected: - void addLine(std::string symbol_line) { - trace_.emplace_back(std::move(symbol_line)); - } - - private: - std::string name_; - std::vector<std::string> trace_; - friend class TraceResolver; +struct BackTrace { + std::string name; + std::vector<std::string> trace; }; -/** - * Pulls the trace and places it onto the TraceResolver instance. - */ -void pull_trace(uint8_t frames_to_skip = 1); +BackTrace getBackTrace(std::string_view thread_name, std::thread::native_handle_type thread); +BackTrace getBackTrace(std::string_view thread_name); -/** - * Emplaces a signal handler for SIGUSR2 - */ -void emplace_handler(); - -/** - * Purpose: Provides a singular instance to grab the call stack for thread(s). - * Design: is a singleton to avoid multiple signal handlers. - */ -class TraceResolver { - public: - /** - * Retrieves the backtrace for the provided thread reference - * @return BackTrace instance - */ - BackTrace getBackTrace(std::string thread_name, std::thread::native_handle_type thread); - - /** - * Retrieves the backtrace for the calling thread - * @returns BackTrace instance - */ - BackTrace getBackTrace(std::string thread_name) { -#ifdef WIN32 - // currrently not supported in windows - return BackTrace(std::move(thread_name)); -#else - return getBackTrace(std::move(thread_name), pthread_self()); -#endif - } - - /** - * Returns a static instance of the thread resolver. - */ - static TraceResolver &getResolver() { - static TraceResolver resolver; - return resolver; - } - - /** - * Adds a trace line with an optional function - * @param symbol_line symbol line that was produced - * @param func function name - */ - void addTraceLine(const char *symbol_line, const char *func = nullptr) { - std::stringstream line; - line << symbol_line; - if (nullptr != func) { - line << " @" << func; - } - trace_.addLine(line.str()); - } - - /** - * Adds a trace line in the format "<file_name> @ <symbol_name> + <symbol_offset>", if symbol_name is not nullptr, - * "<file_name>" otherwise. - * @param file_name the filename of the shared object - * @param symbol_name the name of the symbol (or of the shared object, if the offset is supplied from that) - * @param symbol_offset offset from the base address of the symbol (or the shared object) - */ - void addTraceLine(const char* file_name, const char* symbol_name, uintptr_t symbol_offset) { - std::stringstream line; - line << file_name; - if (symbol_name != nullptr) { - line << " @ " << symbol_name << " + " << symbol_offset; - } - trace_.addLine(line.str()); - } - - std::unique_lock<std::mutex> lock() { - return std::unique_lock<std::mutex>(trace_mutex_); - } - - void notifyPullTracesDone(std::unique_lock<std::mutex>& lock) { - std::unique_lock<std::mutex> tlock(std::move(lock)); - pull_traces_ = true; - trace_condition_.notify_one(); - } - - private: - TraceResolver() = default; - - BackTrace trace_; - mutable std::mutex mutex_; - - bool pull_traces_{false}; - mutable std::mutex trace_mutex_; - std::condition_variable trace_condition_; -}; +} // namespace org::apache::nifi::minifi::utils::trace_resolver diff --git a/core-framework/include/utils/ThreadPool.h b/core-framework/include/utils/ThreadPool.h index 4f2b2af79..5b90ca93d 100644 --- a/core-framework/include/utils/ThreadPool.h +++ b/core-framework/include/utils/ThreadPool.h @@ -187,8 +187,8 @@ class ThreadPool { return running_.load(); } - std::vector<BackTrace> getTraces() { - std::vector<BackTrace> traces; + std::vector<utils::trace_resolver::BackTrace> getTraces() { + std::vector<utils::trace_resolver::BackTrace> traces; std::lock_guard<std::recursive_mutex> lock(manager_mutex_); std::unique_lock<std::mutex> wlock(worker_queue_mutex_); // while we may be checking if running, we don't want to @@ -197,7 +197,7 @@ class ThreadPool { if (running_) { for (const auto &worker : thread_queue_) { if (worker->is_running_) - traces.emplace_back(TraceResolver::getResolver().getBackTrace(worker->name_, worker->thread_.native_handle())); + traces.emplace_back(utils::trace_resolver::getBackTrace(worker->name_, worker->thread_.native_handle())); } } return traces; diff --git a/core-framework/src/utils/BackTrace.cpp b/core-framework/src/utils/BackTrace.cpp index af989222f..ea04a5646 100644 --- a/core-framework/src/utils/BackTrace.cpp +++ b/core-framework/src/utils/BackTrace.cpp @@ -13,58 +13,73 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "utils/BackTrace.h" - -#ifdef HAS_EXECINFO -#include <cxxabi.h> -#include <execinfo.h> #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif + +#include "utils/BackTrace.h" + +#ifndef HAS_EXECINFO +namespace org::apache::nifi::minifi::utils::trace_resolver { +BackTrace getBackTrace(std::string_view thread_name, std::thread::native_handle_type) { + return BackTrace{.name = std::string{thread_name}, .trace = {}}; +} +BackTrace getBackTrace(std::string_view thread_name) { + return BackTrace{.name = std::string{thread_name}, .trace = {}}; +} +} // namespace org::apache::nifi::minifi::utils::trace_resolver +#else + +#include <cxxabi.h> #include <dlfcn.h> +#include <execinfo.h> +#include <pthread.h> #ifdef __linux__ #include <link.h> #endif -#include <cstring> -#include <iostream> -#include <utility> + +#include <array> +#include <atomic> +#include <chrono> +#include <csignal> +#include <cerrno> #include <memory> +#include <mutex> +#include <optional> +#include "core/logging/LoggerFactory.h" +#include "fmt/format.h" +#include "fmt/ranges.h" #include "utils/Deleters.h" -#endif -#include "utils/OptionalUtils.h" +using namespace std::literals::chrono_literals; -#ifdef HAS_EXECINFO namespace { - using std::optional; - /** - * Demangles a symbol name using the cxx abi. - * @param symbol_name the mangled name of the symbol - * @return the demangled name on success, empty string on failure - */ - optional<std::string> demangle_symbol(const char* symbol_name) { - int status = 0; - std::unique_ptr<char, org::apache::nifi::minifi::utils::FreeDeleter> demangled(abi::__cxa_demangle(symbol_name, nullptr, nullptr, &status)); - if (status == 0) { - std::string demangled_name = demangled.get(); - return { demangled_name }; - } else { - return {}; - } +std::optional<std::string> demangle_symbol(const char* symbol_name) { + int status = 0; + std::unique_ptr<char, org::apache::nifi::minifi::utils::FreeDeleter> demangled(abi::__cxa_demangle(symbol_name, nullptr, nullptr, &status)); + if (status == 0) { + std::string demangled_name = demangled.get(); + return { demangled_name }; + } else { + return {}; } -} // namespace -#endif +} + +constexpr size_t TRACE_BUFFER_SIZE = 128; -void pull_trace([[maybe_unused]] uint8_t frames_to_skip /* = 1 */) { -#ifdef HAS_EXECINFO - void* stack_buffer[TRACE_BUFFER_SIZE + 1]; // NOLINT(cppcoreguidelines-avoid-c-arrays) +struct Capture { + pthread_t target{}; + std::array<void*, TRACE_BUFFER_SIZE> stack_buffer{}; + int trace_size{0}; + std::atomic<bool> done{false}; +}; - /* Get the backtrace of the current thread */ - int trace_size = backtrace(stack_buffer, TRACE_BUFFER_SIZE); +std::vector<std::string> resolveRawTrace(const Capture& capture, const uint8_t frames_to_skip) { + std::vector<std::string> trace; - /* We can skip the signal handler, call to pull_trace, and the first entry for backtrace_symbols */ - for (int i = frames_to_skip; i < trace_size; i++) { + // Skip the innermost frame(s) common to all stack traces + for (int i = frames_to_skip; i < capture.trace_size; i++) { const char* file_name = "???"; uintptr_t symbol_offset = 0; @@ -72,13 +87,13 @@ void pull_trace([[maybe_unused]] uint8_t frames_to_skip /* = 1 */) { Dl_info dl_info{}; #ifdef __linux__ struct link_map* l_map = nullptr; - int res = dladdr1(stack_buffer[i], &dl_info, reinterpret_cast<void**>(&l_map), RTLD_DL_LINKMAP); + int res = dladdr1(capture.stack_buffer[i], &dl_info, reinterpret_cast<void**>(&l_map), RTLD_DL_LINKMAP); #else // __linux__ - int res = dladdr(stack_buffer[i], &dl_info); + int res = dladdr(capture.stack_buffer[i], &dl_info); #endif // __linux__ if (res == 0 || dl_info.dli_fname == nullptr || dl_info.dli_fname[0] == '\0') { /* We could not determine symbolic information for this address*/ - TraceResolver::getResolver().addTraceLine(file_name, nullptr, symbol_offset); + trace.emplace_back(file_name); continue; } @@ -94,7 +109,7 @@ void pull_trace([[maybe_unused]] uint8_t frames_to_skip /* = 1 */) { } const std::string symbol_name = dl_info.dli_sname - ? demangle_symbol(dl_info.dli_sname).value_or(file_name) + ? demangle_symbol(dl_info.dli_sname).value_or(dl_info.dli_sname) : file_name; /* Determine our offset */ @@ -115,50 +130,97 @@ void pull_trace([[maybe_unused]] uint8_t frames_to_skip /* = 1 */) { #endif // __linux__ base_address = reinterpret_cast<uintptr_t>(dl_info.dli_fbase); } - symbol_offset = reinterpret_cast<uintptr_t>(stack_buffer[i]) - base_address; + symbol_offset = reinterpret_cast<uintptr_t>(capture.stack_buffer[i]) - base_address; - TraceResolver::getResolver().addTraceLine(file_name, symbol_name.c_str(), symbol_offset); + trace.push_back(fmt::format("{} @ {} + {}", file_name, symbol_name, symbol_offset)); } -#endif // HAS_EXECINFO + + return trace; } -BackTrace TraceResolver::getBackTrace(std::string thread_name, [[maybe_unused]] std::thread::native_handle_type thread_handle) { - // lock so that we only perform one backtrace at a time. -#ifdef HAS_EXECINFO - std::lock_guard<std::mutex> lock(mutex_); - trace_ = BackTrace(std::move(thread_name)); +std::atomic<Capture*> in_flight_capture{nullptr}; - if (0 == thread_handle || pthread_equal(pthread_self(), thread_handle)) { - pull_trace(); - } else { - emplace_handler(); - std::unique_lock<std::mutex> ulock(trace_mutex_); - if (pthread_kill(thread_handle, SIGUSR2) != 0) { - return std::move(trace_); - } - pull_traces_ = false; - trace_condition_.wait(ulock, [this] { return pull_traces_; }); - } -#else - // even if tracing is disabled, include thread name into the trace object - trace_ = BackTrace(std::move(thread_name)); -#endif - return std::move(trace_); -} -#ifdef HAS_EXECINFO void handler(int /*signr*/, siginfo_t* /*info*/, void* /*secret*/) { - std::unique_lock<std::mutex> lock(TraceResolver::getResolver().lock()); - pull_trace(); - TraceResolver::getResolver().notifyPullTracesDone(lock); + const int saved_errno = errno; + Capture* capture = in_flight_capture.load(std::memory_order_acquire); + if (capture != nullptr && pthread_equal(pthread_self(), capture->target)) { + capture->trace_size = backtrace(capture->stack_buffer.data(), static_cast<int>(capture->stack_buffer.size())); + capture->done.store(true, std::memory_order_release); + } + errno = saved_errno; } -#endif void emplace_handler() { -#ifdef HAS_EXECINFO struct sigaction sa{}; sigfillset(&sa.sa_mask); sa.sa_flags = SA_SIGINFO; sa.sa_sigaction = handler; sigaction(SIGUSR2, &sa, nullptr); -#endif } + +bool wait_for_capture_done(const Capture& capture, const std::chrono::milliseconds timeout) { + const auto deadline = std::chrono::steady_clock::now() + timeout; + while (!capture.done.load(std::memory_order_acquire)) { + if (std::chrono::steady_clock::now() >= deadline) { return false; } + std::this_thread::sleep_for(100us); + } + return true; +} +} // namespace + +namespace org::apache::nifi::minifi::utils::trace_resolver { + +BackTrace getBackTrace(std::string_view thread_name, std::thread::native_handle_type thread_handle) { + static std::mutex mutex; + std::scoped_lock guard(mutex); + + static const auto logger = core::logging::LoggerFactory<BackTrace>::getLogger(); + logger->log_trace("getting BackTrace for thread '{}'", thread_name); + + if (0 == thread_handle || pthread_equal(pthread_self(), thread_handle)) { + Capture capture; + capture.trace_size = backtrace(capture.stack_buffer.data(), static_cast<int>(capture.stack_buffer.size())); + auto trace = resolveRawTrace(capture, 1); + logger->log_debug("returning BackTrace for thread '{}' (current thread): {}", thread_name, trace); + return BackTrace{.name = std::string{thread_name}, .trace = std::move(trace)}; + } + + [[maybe_unused]] static const bool warm_up_backtrace = [] { + // Warm up backtrace()/libgcc here, where we are allowed to allocate, so that its one-time lazy dlopen never runs inside the signal handler. + std::array<void*, 1> buffer{}; + backtrace(buffer.data(), static_cast<int>(buffer.size())); + return true; + }(); + + auto capture = std::make_unique<Capture>(); + capture->target = thread_handle; + emplace_handler(); + + in_flight_capture.store(capture.get(), std::memory_order_release); + const auto zero_out_in_flight_capture = gsl::finally([&] { + in_flight_capture.store(nullptr, std::memory_order_release); + }); + + if (pthread_kill(thread_handle, SIGUSR2) != 0) { + logger->log_debug("SIGUSR2 failed, returning empty BackTrace for thread '{}'", thread_name); + return BackTrace{.name = std::string{thread_name}, .trace = {}}; + } + + if (!wait_for_capture_done(*capture, 1s)) { + logger->log_warn("timed out waiting for the stack trace of thread '{}', returning an empty BackTrace", thread_name); + std::ignore = capture.release(); // leaked intentionally, so capture won't be deleted while handle() may still be running + return BackTrace{.name = std::string{thread_name}, .trace = {}}; + } + + auto trace = resolveRawTrace(*capture, 1); + logger->log_debug("returning BackTrace for thread '{}': {}", thread_name, trace); + return BackTrace{.name = std::string{thread_name}, .trace = std::move(trace)}; +} + +BackTrace getBackTrace(std::string_view thread_name) { + return getBackTrace(thread_name, pthread_self()); +} + +} // namespace org::apache::nifi::minifi::utils::trace_resolver + +#endif // HAS_EXECINFO diff --git a/libminifi/include/FlowController.h b/libminifi/include/FlowController.h index e0e9073a1..1190a35b1 100644 --- a/libminifi/include/FlowController.h +++ b/libminifi/include/FlowController.h @@ -142,7 +142,7 @@ class FlowController : public core::controller::ForwardingControllerServiceProvi uint64_t getUptime() override; - std::vector<BackTrace> getTraces() override; + std::vector<utils::trace_resolver::BackTrace> getTraces() override; std::map<std::string, std::unique_ptr<io::InputStream>> getDebugInfo() override; diff --git a/libminifi/include/core/state/UpdateController.h b/libminifi/include/core/state/UpdateController.h index 96d7ece99..06f908375 100644 --- a/libminifi/include/core/state/UpdateController.h +++ b/libminifi/include/core/state/UpdateController.h @@ -150,7 +150,7 @@ class StateMonitor : public StateController { virtual uint64_t getUptime() = 0; - virtual std::vector<BackTrace> getTraces() = 0; + virtual std::vector<utils::trace_resolver::BackTrace> getTraces() = 0; virtual std::map<std::string, std::unique_ptr<io::InputStream>> getDebugInfo() = 0; diff --git a/libminifi/src/FlowController.cpp b/libminifi/src/FlowController.cpp index 62ab8c20b..ed34ff24e 100644 --- a/libminifi/src/FlowController.cpp +++ b/libminifi/src/FlowController.cpp @@ -452,18 +452,15 @@ uint64_t FlowController::getUptime() { return time_since; } -std::vector<BackTrace> FlowController::getTraces() { - std::vector<BackTrace> traces{thread_pool_.getTraces()}; +std::vector<utils::trace_resolver::BackTrace> FlowController::getTraces() { + auto traces{thread_pool_.getTraces()}; if (auto provenance_repo = std::dynamic_pointer_cast<core::ThreadedRepository>(provenance_repo_)) { - auto prov_repo_trace = provenance_repo->getTraces(); - traces.emplace_back(std::move(prov_repo_trace)); + traces.push_back(provenance_repo->getTraces()); } if (auto flow_file_repo = std::dynamic_pointer_cast<core::ThreadedRepository>(flow_file_repo_)) { - auto flow_repo_trace = flow_file_repo->getTraces(); - traces.emplace_back(std::move(flow_repo_trace)); + traces.push_back(flow_file_repo->getTraces()); } - auto my_traces = TraceResolver::getResolver().getBackTrace("main"); - traces.emplace_back(std::move(my_traces)); + traces.push_back(utils::trace_resolver::getBackTrace("main")); return traces; } diff --git a/libminifi/src/c2/C2Agent.cpp b/libminifi/src/c2/C2Agent.cpp index d4b44a12b..849b71668 100644 --- a/libminifi/src/c2/C2Agent.cpp +++ b/libminifi/src/c2/C2Agent.cpp @@ -571,18 +571,18 @@ void C2Agent::handle_describe(const C2ContentResponse &resp) { } case DescribeOperand::jstack: { if (update_sink_->isRunning()) { - const std::vector<BackTrace> traces = update_sink_->getTraces(); + const std::vector<utils::trace_resolver::BackTrace> traces = update_sink_->getTraces(); for (const auto &trace : traces) { - for (const auto & line : trace.getTraces()) { - logger_->log_trace("{} -- {}", trace.getName(), line); + for (const auto & line : trace.trace) { + logger_->log_trace("{} -- {}", trace.name, line); } } auto keys = configuration_->getConfiguredKeys(); C2Payload response(Operation::acknowledge, resp.ident, true); for (const auto &trace : traces) { C2Payload options(Operation::acknowledge, resp.ident, true); - options.setLabel(trace.getName()); - for (const auto &line : trace.getTraces()) { + options.setLabel(trace.name); + for (const auto &line : trace.trace) { C2ContentResponse option(Operation::acknowledge); option.name = line; option.operation_arguments[line] = C2Value{line}; diff --git a/libminifi/src/c2/ControllerSocketProtocol.cpp b/libminifi/src/c2/ControllerSocketProtocol.cpp index c7f6a78a5..c64cd84e4 100644 --- a/libminifi/src/c2/ControllerSocketProtocol.cpp +++ b/libminifi/src/c2/ControllerSocketProtocol.cpp @@ -337,8 +337,8 @@ std::string ControllerSocketProtocol::getJstack() { std::stringstream result; const auto traces = update_sink_.getTraces(); for (const auto& trace : traces) { - for (const auto& line : trace.getTraces()) { - result << trace.getName() << " -- " << line << "\n"; + for (const auto& line : trace.trace) { + result << trace.name << " -- " << line << "\n"; } } return result.str(); diff --git a/libminifi/test/unit/BackTraceTests.cpp b/libminifi/test/unit/BackTraceTests.cpp index b73187909..0aee3d243 100644 --- a/libminifi/test/unit/BackTraceTests.cpp +++ b/libminifi/test/unit/BackTraceTests.cpp @@ -1,5 +1,4 @@ /** - * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. @@ -15,23 +14,44 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef NDEBUG // TestBase.h #undef's NDEBUG +constexpr bool IsDebugBuild = true; +#else +constexpr bool IsDebugBuild = false; +#endif + +#ifdef HAS_EXECINFO +#include <pthread.h> +#endif +#include <algorithm> +#include <csignal> #include <utility> #include <future> #include <memory> +#include <string> +#include <thread> #include "unit/TestBase.h" #include "unit/Catch.h" #include "utils/BackTrace.h" #include "utils/Monitors.h" #include "utils/ThreadPool.h" -#include "range/v3/algorithm/any_of.hpp" -using namespace std::literals::chrono_literals; +using BackTrace = utils::trace_resolver::BackTrace; -TEST_CASE("BT1", "[TPT1]") { - const BackTrace trace = TraceResolver::getResolver().getBackTrace("BT1"); +TEST_CASE("Simple backtrace test", "[BT1]") { + LogTestController::getInstance().setTrace<BackTrace>(); + + const BackTrace back_trace = utils::trace_resolver::getBackTrace("BT1"); #ifdef HAS_EXECINFO - CHECK(!trace.getTraces().empty()); + const auto& lines = back_trace.trace; + CHECK(!lines.empty()); + CHECK(std::ranges::all_of(lines, + [](const std::string& line) { return line.contains(" @ ") && line.contains(" + "); })); + if constexpr (IsDebugBuild) { + CHECK(std::ranges::any_of(lines, + [](const std::string& line) { return line.contains("getBackTrace"); })); + } #endif } @@ -46,7 +66,9 @@ void outer_function(std::atomic_flag& ready_to_check, std::atomic_flag& checking } -TEST_CASE("BT2", "[TPT2]") { +TEST_CASE("Backtrace test with thread pool", "[BT2]") { + LogTestController::getInstance().setTrace<BackTrace>(); + std::atomic_flag ready_for_checking; std::atomic_flag done_with_checking; @@ -67,15 +89,22 @@ TEST_CASE("BT2", "[TPT2]") { CHECK(traces.size() <= number_of_worker_threads); REQUIRE(!traces.empty()); for (const auto &trace : traces) { - CHECK(trace.getName().starts_with(thread_pool_name)); + CHECK(trace.name.starts_with(thread_pool_name)); + CHECK(std::ranges::all_of(trace.trace, + [](const std::string& line) { return line.contains(" @ ") && line.contains(" + "); })); } #ifdef HAS_EXECINFO - auto first_worker_trace = traces.front(); - CHECK(ranges::any_of(first_worker_trace.getTraces(), [](const std::string& trace_line) { return trace_line.find("run_tasks") != trace_line.npos; })); -#ifdef DEBUG - CHECK(ranges::any_of(first_worker_trace.getTraces(), [](const std::string& trace_line) { return trace_line.find("outer_function") != trace_line.npos; })); - CHECK(ranges::any_of(first_worker_trace.getTraces(), [](const std::string& trace_line) { return trace_line.find("inner_function") != trace_line.npos; })); -#endif + if constexpr (IsDebugBuild) { + const auto active_trace_it = std::ranges::find_if(traces, [&](const BackTrace& trace) { + return std::ranges::any_of(trace.trace, [&](const std::string& line) { return line.contains("Worker::run"); }); + }); + REQUIRE(active_trace_it != traces.end()); + const auto& lines = active_trace_it->trace; + CHECK(std::ranges::any_of(lines, + [](const std::string& line) { return line.contains("outer_function"); })); + CHECK(std::ranges::any_of(lines, + [](const std::string& line) { return line.contains("inner_function"); })); + } #endif done_with_checking.test_and_set(); done_with_checking.notify_all(); diff --git a/libminifi/test/unit/CMakeLists.txt b/libminifi/test/unit/CMakeLists.txt index ebbe26a26..9363d596f 100644 --- a/libminifi/test/unit/CMakeLists.txt +++ b/libminifi/test/unit/CMakeLists.txt @@ -37,4 +37,11 @@ FOREACH(testfile ${UNIT_TESTS}) ENDFOREACH() message("-- Finished building ${UNIT_TEST_COUNT} unit test file(s)...") +if (NOT WIN32) + set_target_properties(BackTraceTests PROPERTIES ENABLE_EXPORTS ON) + if (APPLE) + target_link_options(BackTraceTests PRIVATE -rdynamic) + endif() +endif() + add_subdirectory(performance) diff --git a/minifi-api/include/minifi-cpp/core/TraceableResource.h b/minifi-api/include/minifi-cpp/core/TraceableResource.h index 828bab679..9a4ca45a8 100644 --- a/minifi-api/include/minifi-cpp/core/TraceableResource.h +++ b/minifi-api/include/minifi-cpp/core/TraceableResource.h @@ -35,7 +35,7 @@ class TraceableResource { /** * Since SerializableComponents represent a runnable object, we should return traces */ - virtual BackTrace getTraces() = 0; + virtual utils::trace_resolver::BackTrace getTraces() = 0; }; } // namespace org::apache::nifi::minifi::core
