#!/usr/bin/env python3
# Can this host hold enough regular files open at once to run Soong?
# On a gVisor build box the sentry can run out of *host* handles after a long
# build: every process then gets EMFILE after a few hundred opens no matter
# what `ulimit -n` says, and Soong dies at the finder or at analysis. Only a
# restart of the box clears it, so say that plainly instead of building.
import os, sys
root = sys.argv[1] if len(sys.argv) > 1 else "/usr"
want = int(sys.argv[2]) if len(sys.argv) > 2 else 4000
if not os.path.isdir(root):
    root = "/usr"
held = []
try:
    for d, _, files in os.walk(root):
        for f in files:
            p = os.path.join(d, f)
            if not os.path.isfile(p) or os.path.islink(p):
                continue
            held.append(os.open(p, os.O_RDONLY))
            if len(held) >= want:
                print(f"fdprobe: ok, held {want} files open under {root}")
                sys.exit(0)
except OSError as e:
    print(f"fdprobe: EMFILE-class failure after {len(held)} opens ({e}).")
    print("fdprobe: the sandbox is out of host file handles; restart the build box, then rerun.")
    sys.exit(1)
print(f"fdprobe: only {len(held)} files under {root}; not a useful probe, passing")
