This is an automated email from the ASF dual-hosted git repository.
lordgamez pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/nifi-minifi-cpp.git
The following commit(s) were added to refs/heads/main by this push:
new 65677423b MINIFICPP-2877 Reorganize BackTrace (#2304)
65677423b is described below
commit 65677423b19a4cbc727d84404f08828282df6071
Author: Ferenc Gerlits <[email protected]>
AuthorDate: Tue Nov 17 16:46:04 2026 +0100
MINIFICPP-2877 Reorganize BackTrace (#2304)
* 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
- log the stack traces (on debug level); this could be useful for
troubleshooting
- fix the unit test: some of it used to be always skipped
* Fix a bug in ThreadedRepository::getTraces()
The logic was reversed: we can only get a stack trace when the thread is
joinable, not when it is non-joinable.
But if the thread is joinable and the run() function has finished already,
then
we can't get a stack trace, either.
---
controller/tests/ControllerTests.cpp | 24 +--
core-framework/include/core/ThreadedRepository.h | 32 ++--
core-framework/include/utils/BackTrace.h | 151 +--------------
core-framework/include/utils/ThreadPool.h | 6 +-
core-framework/src/utils/BackTrace.cpp | 212 ++++++++++++++-------
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 | 61 ++++--
libminifi/test/unit/CMakeLists.txt | 7 +
libminifi/test/unit/ThreadedRepositoryTests.cpp | 123 ++++++++++++
.../include/minifi-cpp/core/TraceableResource.h | 2 +-
14 files changed, 373 insertions(+), 276 deletions(-)
diff --git a/controller/tests/ControllerTests.cpp
b/controller/tests/ControllerTests.cpp
index 91c23ff48..649967610 100644
--- a/controller/tests/ControllerTests.cpp
+++ b/controller/tests/ControllerTests.cpp
@@ -7,6 +7,7 @@
#include <string>
#include <filesystem>
#include <fstream>
+#include "fmt/format.h"
#include "range/v3/algorithm/find.hpp"
#include "unit/TestBase.h"
@@ -22,6 +23,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 {
@@ -65,15 +67,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(fmt::format("bt line {} for {}", i,
back_trace.name));
}
-};
+}
+} // namespace
class TestUpdateSink : public minifi::state::StateMonitor {
public:
@@ -124,11 +124,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 a37c28ceb..fae6e32a1 100644
--- a/core-framework/include/core/ThreadedRepository.h
+++ b/core-framework/include/core/ThreadedRepository.h
@@ -30,8 +30,7 @@ class ThreadedRepositoryImpl : public core::RepositoryImpl,
public virtual core:
// Starts repository monitor thread
bool start() override {
// if Stopped, turn to Starting, otherwise return
- RunningState expected{RunningState::Stopped};
- if (!running_state_.compare_exchange_strong(expected,
RunningState::Starting)) {
+ if (!changeRunningState(RunningState::Stopped, RunningState::Starting)) {
return false;
}
if (purge_period_ <= std::chrono::milliseconds(0)) {
@@ -41,7 +40,10 @@ class ThreadedRepositoryImpl : public core::RepositoryImpl,
public virtual core:
// must set Running state before calling run(), as run() might check state
running_state_.store(RunningState::Running);
- getThread() = std::thread(&ThreadedRepositoryImpl::run, this);
+ getThread() = std::thread([this] {
+ run();
+ changeRunningState(RunningState::Running, RunningState::RunFinished);
+ });
logger_->log_debug("{} ThreadedRepository monitor thread start", name_);
return true;
@@ -49,9 +51,9 @@ class ThreadedRepositoryImpl : public core::RepositoryImpl,
public virtual core:
// Stops repository monitor thread
bool stop() override {
- // if RUNNING, turn to STOPPING, otherwise return
- RunningState expected{RunningState::Running};
- if (!running_state_.compare_exchange_strong(expected,
RunningState::Stopping)) {
+ // if Running or RunFinished, turn to Stopping, otherwise return
+ if (!(changeRunningState(RunningState::Running, RunningState::Stopping)
+ || changeRunningState(RunningState::RunFinished,
RunningState::Stopping))) {
return false;
}
if (getThread().joinable()) {
@@ -63,16 +65,15 @@ class ThreadedRepositoryImpl : public core::RepositoryImpl,
public virtual core:
}
bool isRunning() const override {
- return running_state_.load() == RunningState::Running;
+ const auto running_state = running_state_.load();
+ return running_state == RunningState::Running || running_state ==
RunningState::RunFinished;
}
- 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 {};
+ utils::trace_resolver::BackTrace getTraces() override {
+ if (!getThread().joinable() || running_state_.load() !=
RunningState::Running) {
+ return {.name = getName(), .trace = {}};
}
- return TraceResolver::getResolver().getBackTrace(getName(),
getThread().native_handle());
+ return utils::trace_resolver::getBackTrace(getName(),
getThread().native_handle());
}
private:
@@ -89,10 +90,15 @@ class ThreadedRepositoryImpl : public core::RepositoryImpl,
public virtual core:
enum class RunningState : uint8_t {
Starting,
Running,
+ RunFinished,
Stopping,
Stopped
};
+ bool changeRunningState(RunningState old_state, RunningState new_state) {
+ return running_state_.compare_exchange_strong(old_state, new_state);
+ }
+
std::atomic<RunningState> running_state_{RunningState::Stopped};
std::shared_ptr<logging::Logger> logger_
{logging::LoggerFactory<ThreadedRepository>::getLogger()};
};
diff --git a/core-framework/include/utils/BackTrace.h
b/core-framework/include/utils/BackTrace.h
index 2f40b0282..98879b748 100644
--- a/core-framework/include/utils/BackTrace.h
+++ b/core-framework/include/utils/BackTrace.h
@@ -4,153 +4,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;
-
- BackTrace(std::string name) // NOLINT
- : name_(std::move(name)) {
- }
- std::vector<std::string> getTraces() const {
- return trace_;
- }
+namespace org::apache::nifi::minifi::utils::trace_resolver {
- /**
- * 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);
-
-/**
- * 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);
+BackTrace getBackTrace(std::string_view thread_name,
std::thread::native_handle_type thread);
+BackTrace getBackTrace(std::string_view thread_name);
- /**
- * 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 8088f33e7..959fc1f20 100644
--- a/core-framework/include/utils/ThreadPool.h
+++ b/core-framework/include/utils/ThreadPool.h
@@ -174,8 +174,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
@@ -184,7 +184,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 40ee09ce7..38ca80ab4 100644
--- a/core-framework/src/utils/BackTrace.cpp
+++ b/core-framework/src/utils/BackTrace.cpp
@@ -1,58 +1,78 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
-#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 <array>
+#include <atomic>
+#include <cerrno>
+#include <chrono>
+#include <csignal>
+#include <cstdint>
#include <cstring>
-#include <iostream>
-#include <utility>
#include <memory>
+#include <mutex>
+#include <optional>
+#include <utility>
+#include "core/logging/LoggerFactory.h"
+#include "fmt/format.h"
+#include "fmt/ranges.h"
+#include "minifi-cpp/utils/gsl.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
+}
-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)
+constexpr size_t TRACE_BUFFER_SIZE = 128;
- /* Get the backtrace of the current thread */
- int trace_size = backtrace(stack_buffer, TRACE_BUFFER_SIZE);
+struct Capture {
+ pthread_t target{};
+ std::array<void*, TRACE_BUFFER_SIZE> stack_buffer{};
+ int trace_size{0};
+ std::atomic<bool> done{false};
+};
- /* 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++) {
+std::vector<std::string> resolveRawTrace(const Capture& capture, const uint8_t
frames_to_skip) {
+ std::vector<std::string> trace;
+
+ // 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;
@@ -60,13 +80,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;
}
@@ -82,7 +102,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 */
@@ -103,50 +123,102 @@ 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)
+ && in_flight_capture.compare_exchange_strong(capture, nullptr,
std::memory_order_acq_rel)) {
+ 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_flags = SA_SIGINFO | SA_RESTART;
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;
+ }();
+
+ [[maybe_unused]] static const bool signal_handler_installed = [] {
+ emplace_handler();
+ return true;
+ }();
+
+ auto capture = std::make_unique<Capture>();
+ capture->target = thread_handle;
+
+ 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 handler() 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 aa919993b..c49bb4e08 100644
--- a/libminifi/include/FlowController.h
+++ b/libminifi/include/FlowController.h
@@ -126,7 +126,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 97d7af64d..dc0fa7678 100644
--- a/libminifi/include/core/state/UpdateController.h
+++ b/libminifi/include/core/state/UpdateController.h
@@ -136,7 +136,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 fdd476a7e..86c09805a 100644
--- a/libminifi/src/FlowController.cpp
+++ b/libminifi/src/FlowController.cpp
@@ -436,18 +436,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() {
+ std::vector<utils::trace_resolver::BackTrace>
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 b35353e09..6f91b9690 100644
--- a/libminifi/src/c2/C2Agent.cpp
+++ b/libminifi/src/c2/C2Agent.cpp
@@ -557,18 +557,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 5612931bd..0b3912fe5 100644
--- a/libminifi/src/c2/ControllerSocketProtocol.cpp
+++ b/libminifi/src/c2/ControllerSocketProtocol.cpp
@@ -324,8 +324,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 a71cc20a7..7edc024e1 100644
--- a/libminifi/test/unit/BackTraceTests.cpp
+++ b/libminifi/test/unit/BackTraceTests.cpp
@@ -1,23 +1,39 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+#ifndef NDEBUG // TestBase.h #undef's NDEBUG
+constexpr bool IsDebugBuild = true;
+#else
+constexpr bool IsDebugBuild = false;
+#endif
-#include <utility>
+#include <algorithm>
+#include <csignal>
#include <future>
-#include <memory>
+#include <string>
+#include <utility>
+
#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("Simple backtrace test", "[BT1]") {
+ LogTestController::getInstance().setTrace<BackTrace>();
-TEST_CASE("BT1", "[TPT1]") {
- const BackTrace trace = TraceResolver::getResolver().getBackTrace("BT1");
+ 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(" + ")) || line == "???"; }));
+ if constexpr (IsDebugBuild) {
+ CHECK(std::ranges::any_of(lines,
+ [](const std::string& line) { return line.contains("getBackTrace");
}));
+ }
#endif
}
@@ -32,7 +48,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;
@@ -49,22 +67,31 @@ TEST_CASE("BT2", "[TPT2]") {
pool.start();
{
ready_for_checking.wait(false);
+ const auto release_worker = gsl::finally([&]() {
+ done_with_checking.test_and_set();
+ done_with_checking.notify_all();
+ });
std::vector<BackTrace> traces = pool.getTraces();
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(" + ")) || line == "???"; }));
}
#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();
}
future.wait();
}
diff --git a/libminifi/test/unit/CMakeLists.txt
b/libminifi/test/unit/CMakeLists.txt
index 42ff319a1..21350564e 100644
--- a/libminifi/test/unit/CMakeLists.txt
+++ b/libminifi/test/unit/CMakeLists.txt
@@ -22,4 +22,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/libminifi/test/unit/ThreadedRepositoryTests.cpp
b/libminifi/test/unit/ThreadedRepositoryTests.cpp
new file mode 100644
index 000000000..05b1899aa
--- /dev/null
+++ b/libminifi/test/unit/ThreadedRepositoryTests.cpp
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+#include <algorithm>
+#include <atomic>
+#include <string>
+#include <thread>
+
+#include "core/ThreadedRepository.h"
+#include "core/repository/NoOpThreadedRepository.h"
+#include "unit/TestBase.h"
+#include "unit/Catch.h"
+#include "unit/TestUtils.h"
+#include "utils/BackTrace.h"
+
+using namespace std::literals::chrono_literals;
+
+namespace org::apache::nifi::minifi::core::test {
+
+using BackTrace = utils::trace_resolver::BackTrace;
+
+class BlockingThreadedRepository : public core::ThreadedRepositoryImpl {
+ public:
+ BlockingThreadedRepository() : ThreadedRepositoryImpl("BlockingRepo") {}
+
+ BlockingThreadedRepository(BlockingThreadedRepository&&) = delete;
+ BlockingThreadedRepository(const BlockingThreadedRepository&) = delete;
+ BlockingThreadedRepository& operator=(BlockingThreadedRepository&&) = delete;
+ BlockingThreadedRepository& operator=(const BlockingThreadedRepository&) =
delete;
+
+ ~BlockingThreadedRepository() override {
+ release();
+ stop();
+ }
+
+ uint64_t getRepositorySize() const override {
+ return 0;
+ }
+
+ uint64_t getRepositoryEntryCount() const override {
+ return 0;
+ }
+
+ void waitUntilRunIsInProgress() {
+ run_in_progress_.wait(false);
+ }
+
+ void release() {
+ release_.test_and_set();
+ release_.notify_all();
+ }
+
+ private:
+ void run() override {
+ run_in_progress_.test_and_set();
+ run_in_progress_.notify_all();
+ release_.wait(false);
+ }
+
+ std::thread& getThread() override {
+ return thread_;
+ }
+
+ std::atomic_flag run_in_progress_;
+ std::atomic_flag release_;
+ std::thread thread_;
+};
+
+TEST_CASE("ThreadedRepository returns the stack trace of its thread while it
is running", "[ThreadedRepository][getTraces]") {
+ LogTestController::getInstance().setTrace<BackTrace>();
+
+ BlockingThreadedRepository repository;
+
+ SECTION("before start") {
+ const BackTrace back_trace = repository.getTraces();
+ CHECK(back_trace.name == "BlockingRepo");
+ CHECK(back_trace.trace.empty());
+ }
+
+ SECTION("while running") {
+ REQUIRE(repository.start());
+ repository.waitUntilRunIsInProgress();
+
+ const BackTrace back_trace = repository.getTraces();
+ CHECK(back_trace.name == "BlockingRepo");
+#ifdef HAS_EXECINFO
+ CHECK_FALSE(back_trace.trace.empty());
+#endif
+ }
+
+ SECTION("after stop") {
+ REQUIRE(repository.start());
+ repository.waitUntilRunIsInProgress();
+ repository.release();
+ REQUIRE(repository.stop());
+
+ const BackTrace back_trace = repository.getTraces();
+ CHECK(back_trace.name == "BlockingRepo");
+ CHECK(back_trace.trace.empty());
+ }
+}
+
+TEST_CASE("ThreadedRepository returns an empty stack trace if run() has
finished", "[ThreadedRepository][getTraces]") {
+ LogTestController::getInstance().setTrace<BackTrace>();
+
+ core::repository::NoOpThreadedRepository repository{"NoOpRepo"};
+ REQUIRE(repository.start());
+ CHECK(repository.isRunning());
+
+ // the thread exits as soon as it starts, as run() is empty; but if it
hasn't exited yet, we'll get a non-empty trace
+ std::this_thread::sleep_for(100ms);
+ REQUIRE(minifi::test::utils::verifyEventHappenedInPollTime(1s, [&] {
+ const BackTrace back_trace = repository.getTraces();
+ return back_trace.name == "NoOpRepo" && back_trace.trace.empty();
+ }));
+ CHECK_FALSE(LogTestController::getInstance().contains("timed out waiting for
the stack trace", 0s));
+
+ CHECK(repository.isRunning());
+ CHECK(repository.stop());
+ CHECK_FALSE(repository.isRunning());
+}
+
+} // namespace org::apache::nifi::minifi::core::test
diff --git a/minifi-api/include/minifi-cpp/core/TraceableResource.h
b/minifi-api/include/minifi-cpp/core/TraceableResource.h
index 3f7dbf335..b108db563 100644
--- a/minifi-api/include/minifi-cpp/core/TraceableResource.h
+++ b/minifi-api/include/minifi-cpp/core/TraceableResource.h
@@ -21,7 +21,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