[BUG] Exception escaping noexcept Session::SendRequest in curl HTTP client calls std::terminate, killing the host process

未关闭
#4,792 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
45/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
cpp

调研方向

Start with ext/src/http/client/curl/http_client_curl.cc, especially Session::SendRequest and HttpClient::MaybeSpawnBackgroundThread; read the SendRequest contract in ext/include/opentelemetry/ext/http/client/http_client.h and the existing cleanup path in exporters/otlp/src/otlp_http_client.cc. Trace how a failed send releases the session and wakes synchronous exports, then check the curl client tests for coverage. Done means exceptions from these noexcept paths are handled without terminating the host process, with session cleanup preserved and failures reported through the error handler.

由索引模型根据 Issue 内容生成。

描述

bug needs-triage

Describe your environment

  • opentelemetry-cpp v1.22.0. Also verified present on main as of 2026-11-16 — see "Additional context".
  • Linux x86-64, Clang, libstdc++, static libs.
  • Build options: WITH_OTLP_HTTP=ON, OPENTELEMETRY_ABI_VERSION_NO=2, OPENTELEMETRY_STL_VERSION=2023, OPENTELEMETRY_NO_DEPRECATED_CODE, HAVE_ABSEIL. ENABLE_ASYNC_EXPORT not defined, so the synchronous OtlpHttpClient::Export(message) path is used.
  • Exporter: OTLP/HTTP metric exporter behind PeriodicExportingMetricReader.

Steps to reproduce

Session::SendRequest is declared noexcept but performs several operations that can throw.
Any of them terminates the process. The most deterministic to demonstrate is the lazy creation
of the curl background thread, which throws std::system_error when pthread_create fails.

repro.cc:

#include <opentelemetry/exporters/otlp/otlp_http_metric_exporter_factory.h>
#include <opentelemetry/exporters/otlp/otlp_http_metric_exporter_options.h>
#include <opentelemetry/sdk/metrics/export/periodic_exporting_metric_reader.h>
#include <opentelemetry/sdk/metrics/export/periodic_exporting_metric_reader_options.h>
#include <opentelemetry/sdk/metrics/meter_provider.h>
#include <opentelemetry/sdk/metrics/view/view_registry.h>

#include <chrono>
#include <memory>
#include <thread>

int main()
{
  namespace otlp    = opentelemetry::exporter::otlp;
  namespace metrics = opentelemetry::sdk::metrics;

  // Default endpoint; nothing needs to be listening for this repro.
  otlp::OtlpHttpMetricExporterOptions exporter_options;
  auto exporter = otlp::OtlpHttpMetricExporterFactory::Create(exporter_options);

  metrics::PeriodicExportingMetricReaderOptions reader_options;
  reader_options.export_interval_millis = std::chrono::milliseconds(10000);
  reader_options.export_timeout_millis  = std::chrono::milliseconds(5000);

  auto reader = std::make_shared<metrics::PeriodicExportingMetricReader>(
      std::move(exporter), reader_options);

  auto provider = std::make_shared<metrics::MeterProvider>(
      std::make_unique<metrics::ViewRegistry>());
  provider->AddMetricReader(reader);

  auto counter = provider->GetMeter("repro")->CreateUInt64Counter("repro_counter");
  counter->Add(1);

  std::this_thread::sleep_for(std::chrono::seconds(20));  // allow one export
  return 0;
}

fail_pthread_create.c — makes pthread_create fail once the SDK's own threads are up, so
only the curl client's lazily-created background thread is affected:

#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <pthread.h>
#include <time.h>

static time_t start;
__attribute__((constructor)) static void init(void) { start = time(NULL); }

int pthread_create(pthread_t *t, const pthread_attr_t *a,
                   void *(*fn)(void *), void *arg)
{
  static int (*real)(pthread_t *, const pthread_attr_t *, void *(*)(void *), void *);
  if (!real) real = dlsym(RTLD_NEXT, "pthread_create");

  /* SDK reader threads are created during startup; the curl background thread is
     created lazily on the first export, at ~10s. Fail anything after 5s. */
  if (time(NULL) - start >= 5)
    return EAGAIN;

  return real(t, a, fn, arg);
}
cc -shared -fPIC -o fail_pthread_create.so fail_pthread_create.c -ldl
LD_PRELOAD=./fail_pthread_create.so ./repro

The process aborts at the first export, roughly 10 seconds in.

The same crash is reachable without any fault injection under genuine memory pressure, via the
allocating operations listed in "Additional context".

What is the expected behavior?

The export fails, the failure is reported through GlobalLogHandler, and the application keeps
running.

The error-handling specification
requires this. Four of its requirements apply:

  • Implementations must not throw unhandled exceptions at runtime.
  • The SDK must not throw unhandled exceptions for failures in its own operations — the spec's own
    illustrating example is an exporter that cannot reach the endpoint it sends telemetry to.
  • The API or SDK may fail fast at initialization, but must not cause the application to fail later
    at runtime.
  • Background tasks should run in the context of a global error handler so their exceptions do not
    affect the end user application.

PeriodicExportingMetricReader already implements this correctly:
sdk/src/metrics/export/periodic_exporting_metric_reader.cc:160-206 wraps the whole
collect-and-export call in try { ... } catch (std::exception &e) { OTEL_INTERNAL_LOG_ERROR(...); return false; } catch (...) { ... }.

What is the actual behavior?

std::terminate is called and the host process dies.

Frames #21 → #16 below are exactly the region inside that SDK try block. Because
Session::SendRequest at frame #11 is noexcept, the runtime terminates instead of unwinding,
so the SDK's handler never runs. The recovery code exists and is unreachable.

#8  __cxxabiv1::__terminate (handler=<optimized out>)  at libsupc++/eh_terminate.cc:48
#9  std::terminate ()                                   at libsupc++/eh_terminate.cc:58
#10 __clang_call_terminate ()
#11 opentelemetry::v2::ext::http::client::curl::Session::SendRequest (this=0x7f4693211210, callback=...)
      at ext/src/http/client/curl/http_client_curl.cc:145
#12 opentelemetry::v2::exporter::otlp::OtlpHttpClient::addSession (this=0x7f46a4ee1280, session_data=...)
      at exporters/otlp/src/otlp_http_client.cc:1028
#13 opentelemetry::v2::exporter::otlp::OtlpHttpClient::Export (this=0x7f46a4ee1280, message=...,
      result_callback=..., max_running_requests=0)
      at exporters/otlp/src/otlp_http_client.cc:759
#14 opentelemetry::v2::exporter::otlp::OtlpHttpClient::Export (this=0x7f46a4ee1280, message=...)
      at exporters/otlp/src/otlp_http_client.cc:725
#15 opentelemetry::v2::exporter::otlp::OtlpHttpMetricExporter::Export (this=0x7f46a4e0c780, data=...)
      at exporters/otlp/src/otlp_http_metric_exporter.cc:204
#16 opentelemetry::v2::sdk::metrics::PeriodicExportingMetricReader::CollectAndExportOnce()::$_0::operator()(
      opentelemetry::v2::sdk::metrics::ResourceMetrics&) const (this=0x7f46a057a120, metric_data=...)
      at sdk/src/metrics/export/periodic_exporting_metric_reader.cc:181
#17 opentelemetry::v2::nostd::function_ref<...>::BindTo<...>(...)::{lambda(void*, ResourceMetrics&)#1}::operator()
      at api/include/opentelemetry/nostd/function_ref.h:41
#18 opentelemetry::v2::nostd::function_ref<...>::BindTo<...>(...)::{lambda(void*, ResourceMetrics&)#1}::__invoke
      at api/include/opentelemetry/nostd/function_ref.h:40
#19 opentelemetry::v2::nostd::function_ref<bool(ResourceMetrics&)>::operator() (args=..., this=<optimized out>)
      at api/include/opentelemetry/nostd/function_ref.h:89
#20 opentelemetry::v2::sdk::metrics::MetricReader::Collect (this=<optimized out>, callback=...)
      at sdk/src/metrics/metric_reader.cc:46
#21 opentelemetry::v2::sdk::metrics::PeriodicExportingMetricReader::CollectAndExportOnce (this=0x7f46a4e65510)
      at sdk/src/metrics/export/periodic_exporting_metric_reader.cc:172
#22 opentelemetry::v2::sdk::metrics::PeriodicExportingMetricReader::DoBackgroundWork (this=0x7f46a4e65510)
      at sdk/src/metrics/export/periodic_exporting_metric_reader.cc:107
#23 std::execute_native_thread_routine (__p=<optimized out>)  at libstdc++-v3/src/c++11/thread.cc:104
#24 start_thread ()  from /lib64/libpthread.so.0
#25 clone ()         from /lib64/libc.so.6

Frames #0-#7 were the host application's own std::set_terminate handler writing a core dump;
they are omitted as they carry no information about this bug.

Additional context

Note on the line attribution in frame #11. It reads http_client_curl.cc:145, which is
const auto &url = host_ + http_request_->uri_;. That is misleading. Clang emits one shared
__clang_call_terminate landing pad per noexcept function and its line-table entry points into
the function body rather than the throw site; line 145 is just the first potentially-throwing
expression. In our dump curl_operation_ was already non-null and session_id_ == 1, proving
new HttpOperation(...) at line 227 had completed and the throw came from line 232 or later.

Unguarded operations in Session::SendRequest (ext/src/http/client/curl/http_client_curl.cc:141-242).
None of these is wrapped, and the function is noexcept:

Operation Location Throws
std::function constructed from the lambda capturing this + a shared_ptr http_client_curl.cc:233 std::bad_alloc — the capture holds a non-trivially-copyable shared_ptr, so libstdc++ cannot apply its small-object optimization and must heap-allocate
async_data_.reset(new AsyncData()); AsyncData holds a std::promise and std::future http_operation_curl.cc:1286, type at http_operation_curl.h:331-340 std::bad_alloc; std::promise construction allocates shared state and can also throw std::system_error
pending_to_add_session_ids_.insert(...) under std::lock_guard<std::recursive_mutex> http_client_curl.cc:635-645 std::bad_alloc from the node allocation; std::system_error from lock()
background_thread_.reset(new std::thread(...)) http_client_curl.cc:438-446 std::system_error when pthread_create fails (EAGAIN at a thread or RLIMIT_NPROC limit); also std::bad_alloc

There is no try or catch anywhere in ext/src/http/client/curl/http_client_curl.cc or
ext/src/http/client/curl/http_operation_curl.cc, on v1.22.0 or on main.

The same defect on the trace path. We have a second occurrence from an earlier version, ABI v1,
with an identical shape: BatchSpanProcessor::DoBackgroundWork → BatchSpanProcessor::Export →
OtlpHttpExporter::Export → OtlpHttpClient::Export → OtlpHttpClient::addSession →
Session::SendRequest → __clang_call_terminate → std::terminate. So this is not specific to
the metrics exporter; it is the shared curl HTTP client.

Suggested fix, and why it is not a breaking change. noexcept is part of the public
pure-virtual contract:

// ext/include/opentelemetry/ext/http/client/http_client.h:359
virtual void SendRequest(std::shared_ptr<EventHandler>) noexcept = 0;

So the fix should honour the noexcept by catching internally, not remove it. No signature
change, no ABI impact, no change required of any implementor of the interface.

The correct recovery already exists inside the function. Lines 234-241 handle SendAsync
returning non-OK by emitting SessionState::CreateFailed through the callback and clearing
is_session_active_. That is a complete cleanup rather than just a log: ResponseHandler::OnEvent
sets need_stop (exporters/otlp/src/otlp_http_client.cc:155-163), which at :310-317 calls
Unbind(kFailure) (:320-340), which calls OtlpHttpClient::ReleaseSession (:858-882), moving
the session out of running_sessions_ and calling session_waker_.notify_all() to release the
synchronous export waiting at :772-777. A catch handler doing exactly what that else branch
does would restore spec-compliant behaviour.

Two cautions for whoever implements it:

  1. Calling OTEL_INTERNAL_LOG_ERROR from the handler is risky. It dispatches to a user-supplied
    LogHandler and allocates, so in a bad_alloc-triggered handler it can throw again and return
    straight to terminate. The same applies to the std::stringstream built in
    ResponseHandler::OnEvent's CreateFailed case.
  2. The handler must leave curl_operation_ and async_data_ in a state the Session destructor
    and HttpClient::CleanupSession can handle, since the throw may land partway through
    SendAsync with a live curl easy handle that was never added to the multi handle. This is
    adjacent to #4397.

HttpClient::MaybeSpawnBackgroundThread (http_client_curl.cc:438-446) should also guard its own
thread creation and return false on failure, mirroring what was done for the file exporter in
#3012.

Other unguarded noexcept functions on the same path. Same defect class, worth fixing together:

  • OtlpHttpClient::Export (exporters/otlp/src/otlp_http_client.cc:748-787) — best single outer
    net, since it has a natural return ExportResult::kFailure. It is not a substitute for the
    SendRequest fix, though: catching only here would strand a session in running_sessions_ and
    hang ForceFlush (:789-812 waits for running_sessions_.empty()).
  • OtlpHttpClient::addSession (:1008-1029) — the running_sessions_[session.get()] insert at
    :1022 allocates.
  • HttpClient::CreateSession (ext/src/http/client/curl/http_client_curl.cc:323-341) —
    std::make_shared<Session> at :329/:332 and sessions_.insert at :337. This function
    already carries a // FIXME: Session may leak if it does not call SendRequest at line 339.

Related:

  • #4397 — an asynchronous curl request whose Setup fails leaks its easy handle and header list.
    Same function family, resource cleanup rather than the noexcept escape, but a fix for
    SendRequest should account for it.
  • #3012 — "Ignore exception when create thread in OTLP file exporter", the precedent for this
    change, applied to exporters/otlp/src/otlp_file_client.cc:1546-1551 only. The curl client was
    missed.
主要语言
C++
星标
1.4k
派生
663
平均合并
1 天 10 小时
30 天内合并 PR
44

环境准备

在 Codespaces 中打开

在浏览器里用你自己的 GitHub 账号启动这个项目的开发容器。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

open-telemetry/opentelemetry-cpp 的其他 Issue

查看 open-telemetry/opentelemetry-cpp 的全部 Issue

相似的 Issue

更多 C++ Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。