Skip to content

mgr/ThreadMonitor: return false from read_thread_stat() on parse failure - #72354

Open
stzuraski898 wants to merge 3 commits into
ceph:mainfrom
stzuraski898:wip-sz-81337-threadmonitor-read-thread-stat-parse
Open

stzuraski898 wants to merge 3 commits into
ceph:mainfrom
stzuraski898:wip-sz-81337-threadmonitor-read-thread-stat-parse

Conversation

@stzuraski898

@stzuraski898 stzuraski898 commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

ThreadMonitor::read_thread_stat() parses /proc/<tid>/stat to extract a
thread's utime/stime. It had two defects on malformed input:

  1. Unchecked extraction. ss >> utime >> stime was not checked. On a short
    line the extraction fails and, per C++11 [istream.formatted.arithmetic],
    writes 0 into the targets. The function still returned success, so the
    caller (process_thread_stats()) computed a bogus CPU percentage from the
    zeroed values (e.g. 0 - last.utime underflowing to a huge unsigned delta).
    This is defined-but-wrong behaviour, not undefined behaviour.

  2. Out-of-range substr. line.substr(end + 2) (skipping the comm field's
    closing ")") threw std::out_of_range if the line ended at or just after
    the ). Because read_thread_stat() runs on the monitoring std::thread,
    an uncaught exception there would terminate the ceph-mgr process.

Fix

  • Parse into local temporaries and assign the out-parameters only after both
    extractions succeed; return false otherwise (out-params left unmodified).
  • Bounds-check before substr and return false on a truncated line.
  • Correct the header contract to "on a false return the out-parameters are
    not modified."

Reachability / likelihood

Low. /proc/<tid>/stat is kernel-generated with a stable format and read
atomically, so a malformed or truncated line is not expected in normal
operation. The pre-existing worst case was a single wrong CPU-percentage
sample (self-correcting the next cycle); the substr path would only throw on
a line truncated exactly at the comm ). This is defensive hardening that also
makes the helper's return contract honest, rather than a fix for an observed
field failure.

Tests

Adds the first ThreadMonitor unit-test target with cases for a well-formed
line, a truncated line (returns false, no throw), and the
"outputs unchanged on failure" contract. The test scaffolding/CMake target is
cherry-picked from #71237 and will be reconciled when that lands.

Fixes: https://tracker.ceph.com/issues/81337

Contribution Guidelines

  • To sign and title your commits, please refer to Submitting Patches to Ceph.

  • If you are submitting a fix for a stable branch (e.g. "quincy"), please refer to Submitting Patches to Ceph - Backports for the proper workflow.

  • When filling out the below checklist, you may click boxes directly in the GitHub web UI. When entering or editing the entire PR message in the GitHub web UI editor, you may also select a checklist item by adding an x between the brackets: [x]. Spaces and capitalization matter when checking off items this way.

Checklist

  • Tracker (select at least one)
    • References tracker ticket
    • Very recent bug; references commit where it was introduced
    • New feature (ticket optional)
    • Doc update (no ticket needed)
    • Code cleanup (no ticket needed)
  • Component impact
    • Affects Dashboard, opened tracker ticket
    • Affects Orchestrator, opened tracker ticket
    • No impact that needs to be tracked
  • Documentation (select at least one)
    • Updates relevant documentation
    • No doc update is appropriate
  • Tests (select at least one)
Show available Jenkins commands

You must only issue one Jenkins command per-comment. Jenkins does not understand
comments with more than one command.

@stzuraski898
stzuraski898 requested a review from a team as a code owner October 2, 2026 22:04
@stzuraski898
stzuraski898 requested a balanced review from Copilot and removed request for a team October 2, 2026 22:08

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Some malformed inputs can still throw, and partial extraction violates the documented output contract.

Review effort: Balanced
Findings: 2 Medium severity

Open (2)
What changed in this PR

Fixes malformed /proc thread-stat handling to prevent invalid CPU calculations.

Changes:

  • Extracts stat parsing into a testable helper.
  • Returns failure when CPU-time fields cannot be parsed.
  • Adds unit-test scaffolding and regression coverage.
File Description
src/​mgr/​ThreadMonitor.cc Validates parsed thread CPU times.
src/​mgr/​ThreadMonitor.h Exposes the parsing helper.
src/​test/​mgr/​TestMgr.h Adds the test fixture.
src/​test/​mgr/​test_threadmonitor.cc Tests valid and truncated input.
src/​test/​mgr/​CMakeLists.txt Registers the new unit-test target.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/mgr/ThreadMonitor.cc
Comment on lines +219 to +220
bool ThreadMonitor::parse_thread_stat(const std::string& line, long long& utime,
long long& stime) {
Comment thread src/mgr/ThreadMonitor.cc Outdated
Comment on lines 236 to 239
if (!(ss >> utime >> stime)) {
return false;
}
return true;
@stzuraski898
stzuraski898 force-pushed the wip-sz-81337-threadmonitor-read-thread-stat-parse branch 3 times, most recently from 5fd35c4 to 1222d84 Compare October 27, 2026 22:23

@NitzanMordhai NitzanMordhai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@stzuraski898 please see my comments

#include "TestMgr.h"
#include "mgr/ThreadMonitor.h"

TEST_F(ThreadMonitorTestHelper, BasicCreation) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please explain what the idea behind that test is

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These tests are a part of the initial scaffolding added in #71237. The cherrypicked commit is temporary while that PR is in review.

Comment thread src/test/mgr/test_threadmonitor.cc Outdated
ASSERT_NE(cct, nullptr);
}

TEST_F(ThreadMonitorTestHelper, Construction) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please explain what the idea behind that test is

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These tests are a part of the initial scaffolding added in #71237. The cherrypicked commit is temporary while that PR is in review.

Comment thread src/test/mgr/test_threadmonitor.cc Outdated
// Should not crash
}

TEST(ThreadMonitor, ReadThreadStatReturnsFalseOnMalformedLine) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All the tests with ReadThreadStat* are actually need to be called ParseThreadStat*

Comment thread src/mgr/ThreadMonitor.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can use that opportunity and fix that as well.

Comment thread src/mgr/ThreadMonitor.cc Outdated
@@ -209,23 +209,42 @@ bool ThreadMonitor::read_thread_stat(pid_t tid, long long& utime, long long& sti
}
std::string line;
std::getline(stat_file, line);
if (!parse_thread_stat(line, utime, stime)) {
dout(20) << __func__ << "Malformed stat file for TID " << tid << dendl;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We already printing "func" also add space before the string

Problem: src/mgr/ThreadMonitor.cc has no unit-test harness, so its
behaviour cannot be covered by unit tests.

Solution: add the ThreadMonitor unit-test target and its fixture:

  - src/test/mgr/test_threadmonitor.cc with a fixture smoke test
  - a ThreadMonitorTestHelper fixture in src/test/mgr/TestMgr.h
  - the unittest_mgr_threadmonitor target (and the unittest_mgr_base_obj
    object library it depends on) in src/test/mgr/CMakeLists.txt

This scaffolding is cherry-picked from ceph#71237
pending its merge and should be reconciled when that PR lands; #81336 and
#81338 cherry-pick the same scaffolding, so if all three land it is added once.

Assisted-by: Claude Opus 4.8
Signed-off-by: Steven Zuraski <[email protected]>
…ed input

Problem: read_thread_stat() and read_process_statm() parsed the
/proc/self/task/<tid>/stat and /proc/self/statm lines without validating
them, which is unsafe when the kernel returns a short or truncated read:

  - In the stat path, line.substr(end + 2) was called without a bounds
    check. If the line ends exactly at the closing ')' of the comm field,
    end + 2 meets or exceeds line.size() and substr() throws
    std::out_of_range. That exception is thrown inside the monitoring
    std::thread where nothing catches it, so the runtime calls
    std::terminate and the whole mgr process crashes.

  - Both paths extracted fields with an unchecked operator>> and returned
    true unconditionally. On a failed extraction the out-parameters were
    left at an unspecified value (operator>> writes 0 on failure) while
    the function still reported success, so a caller could act on a bogus
    utime/stime/RSS without any way to tell the read had failed.

  - The dout() lines prepended "<< __func__" even though dout_prefix
    already emits __func__ followed by a space, producing a doubled,
    unseparated function name in the log.

Solution: extract pure, static parse_thread_stat() and
parse_process_statm() helpers. Each validates its delimiters/boundaries,
parses into local temporaries, and assigns the out-parameters only after
every extraction succeeds; on any failure it returns false and leaves the
out-parameters untouched. The stat path also bounds-checks before substr()
so a line truncated at ')' returns false instead of throwing. Drop the
redundant "<< __func__" from the dout() calls.

Fixes: https://tracker.ceph.com/issues/81337
Assisted-by: Claude Opus 4.8
Signed-off-by: Steven Zuraski <[email protected]>
Problem: the parse_thread_stat() and parse_process_statm() helpers that
guard against malformed /proc input had no unit coverage, so their
failure contracts could regress unnoticed.

Solution: add unit tests for both helpers:

  - parse_thread_stat(): a well-formed line yields the expected
    utime/stime; a line truncated before the fields, truncated exactly at
    the closing ')', or carrying utime but no stime returns false without
    throwing and leaves the out-parameters at their pre-call values.

  - parse_process_statm(): a well-formed line yields the RSS (2nd field);
    an empty, truncated, or non-numeric line returns false and leaves
    rss_pages unmodified.

Fixes: https://tracker.ceph.com/issues/81337
Assisted-by: Claude Opus 4.8
Signed-off-by: Steven Zuraski <[email protected]>
@stzuraski898
stzuraski898 force-pushed the wip-sz-81337-threadmonitor-read-thread-stat-parse branch from 1222d84 to 4b42f13 Compare October 30, 2026 22:23
@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown

This pull request can no longer be automatically merged: a rebase is needed and changes have to be manually resolved

@stzuraski898
stzuraski898 force-pushed the wip-sz-81337-threadmonitor-read-thread-stat-parse branch from 4b42f13 to b29bad3 Compare November 9, 2026 21:55
@SrinivasaBharath

Copy link
Copy Markdown
Contributor

This PR has been added to wip-bharath3-testing-20261127.055027-main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants