← Back to Pull requests

fix(sftp): fix startup cleanup and fusermount3 fallback in mount/umount-sshfs #7202

Closed
unknown closed this pull request without merging on Nov 05, 2026 12:32 UTC
View on GitHub
unknown unknown commented on Oct 29, 2026 13:02 UTC
Author

What type of PR is this?

/kind bug

What this PR does / why we need it:

Wait for the sftp server and the launch goroutines when mount-sshfs
fails to start, so that no zombie or orphan is left behind. Also fix
typos in umount-sshfs (the fusermount3 command name, and Stdin being
set on the wrong command), and swapped log arguments.

How to verify it

The script below checks whether buildah mount-sshfs cleans up after a
startup failure.

"sshfs" on $PATH is an empty executable, so exec() fails with ENOEXEC
after the sftp server has been started. A fixed buildah reaps that
server before exiting and sees the error without polling the mountpoint.

By setting PR_SET_CHILD_SUBREAPER, any process buildah leaves behind is
reparented to the script: as a zombie if buildah didn't Wait() for it, or
still running if buildah exited before its deferred cleanup ran.

Build buildah before and after this PR, and run the script against each
binary:

python verify.py ./bin/buildah

import ctypes
import os
import signal
import subprocess
import sys
import tempfile

# include/uapi/linux/prctl.h: #define PR_SET_CHILD_SUBREAPER 36
PR_SET_CHILD_SUBREAPER = 36


def collect_and_reap():
    """Inspect children reparented to us, then kill and reap them all."""
    children_file = f"/proc/self/task/{os.getpid()}/children"
    with open(children_file) as f:
        pids = [int(p) for p in f.read().split()]

    found = []
    for pid in pids:
        try:
            with open(f"/proc/{pid}/stat") as f:
                stat = f.read()
            comm = stat[stat.index("(") + 1:stat.rindex(")")]
            state = stat[stat.rindex(")") + 2]
            status = "zombie" if state == "Z" else "running"
            found.append(f"{pid}({comm}): {status}")
            os.kill(pid, signal.SIGKILL)
        except ProcessLookupError:
            pass

    # Reap everything so nothing outlives this script
    while True:
        try:
            os.waitpid(-1, 0)
        except ChildProcessError:
            break

    return found


def main():
    if len(sys.argv) != 2:
        sys.exit(f"usage: {sys.argv[0]} BUILDAH_BIN")
    buildah = os.path.abspath(sys.argv[1])
    if os.path.basename(buildah) != "buildah":
        sys.exit(f"{sys.argv[1]}: specify a buildah binary "
                 "(stevedore and lumper won't do either)")

    libc = ctypes.CDLL(None, use_errno=True)
    if libc.prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) != 0:
        sys.exit(f"prctl(PR_SET_CHILD_SUBREAPER): {os.strerror(ctypes.get_errno())}")

    with tempfile.TemporaryDirectory(prefix="repro-sshfs-") as tmp:
        # Stub "sshfs" that exec.LookPath accepts (+x) but execve rejects (ENOEXEC).
        # An empty file matches no binary format (no ELF magic, no "#!"), and
        # execve(2) says: "ENOEXEC An executable is not in a recognized format,
        # is for the wrong architecture, or has some other format error that
        # means it cannot be executed."
        fakebin = os.path.join(tmp, "bin")
        os.mkdir(fakebin)
        stub = os.path.join(fakebin, "sshfs")
        open(stub, "w").close()
        os.chmod(stub, 0o755)
        env = dict(os.environ, PATH=f"{fakebin}:{os.environ['PATH']}")

        storage = ["--root", f"{tmp}/store", "--runroot", f"{tmp}/run",
                   "--storage-driver", "vfs"]
        cid = subprocess.check_output([buildah, *storage, "from", "scratch"],
                                      text=True).strip()

        proc = subprocess.run(
            [buildah, *storage, "--log-level", "debug", "mount-sshfs", cid],
            env=env, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True)

        orphans = collect_and_reap()

    # cmd/buildah/sftp.go, mountSshfsCmd(): logged each time the mountpoint
    # poll sleeps without having seen a startup error:
    #   logrus.Debugf("%q is not (yet?) a mountpoint, waiting %s", where, mountUmountCheckInterval)
    poll_miss = "is not (yet?) a mountpoint" in proc.stderr

    print("[1] sftp server is reaped before buildah exits (serveSftp.Wait() + wg.Wait())")
    print(f"    {'OK  ' if not orphans else 'FAIL'}  left behind: "
          f"{', '.join(orphans) if orphans else 'none'}")
    print()
    print("[2] startup error is recorded before mountpoint polling (wg.Wait())")
    print(f"    {'OK  ' if not poll_miss else 'FAIL'}  poll missed the error: "
          f"{'yes' if poll_miss else 'no'}")


if __name__ == "__main__":
    main()

Before:

[1] sftp server is reaped before buildah exits (serveSftp.Wait() + wg.Wait())
    FAIL  left behind: 13889(exe): zombie

[2] startup error is recorded before mountpoint polling (wg.Wait())
    FAIL  poll missed the error: yes

After:

[1] sftp server is reaped before buildah exits (serveSftp.Wait() + wg.Wait())
    OK    left behind: none

[2] startup error is recorded before mountpoint polling (wg.Wait())
    OK    poll missed the error: no

Which issue(s) this PR fixes:

None

Special notes for your reviewer:

  • I haven't added an automated test. There's no clean way to use

  • PR_SET_CHILD_SUBREAPER from BATS, and tests that check processes or
    signals across the process tree and namespaces could themselves make CI flaky.
  • The change itself isn't about a subtle edge case; it just adds Waits

  • where the code should have been waiting, so I prioritized fixing
    that obvious problem over adding a test.

    Given the above, I'd like a maintainer to decide whether to apply the 'No New Tests' label.

    Does this PR introduce a user-facing change?

    ``release-note
    buildah umount-sshfs now falls back to fusermount3 correctly when umount fails.
    ``

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: ajoshua2004 Review duration: 10050m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #7202"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%