The CPU percentage shown by docker stats is not reported by the daemon — it is derived on the client side from raw counters, and you have to fetch those counters yourself.
You are given a client, which behaves like the object docker.from_env() returns. Implement:
container_cpu_percent(client, container_id: str) -> float
Fetch the container's stats through the SDK, then compute its CPU percentage.
The API you need:
container = client.containers.get(container_id) # raises NotFound for an unknown id
stats = container.stats(stream=False) # one snapshot, as a dict
stats(stream=False) returns a single payload. Calling stats() without arguments streams continuously and will not work here — the same is true of the real SDK, where the default stream=True returns a generator.
The payload has this shape, where every usage value is in nanoseconds:
{
"cpu_stats": { "cpu_usage": { "total_usage": <ns> }, "system_cpu_usage": <ns>, "online_cpus": <n> },
"precpu_stats": { "cpu_usage": { "total_usage": <ns> }, "system_cpu_usage": <ns> }
}
The calculation is unchanged: (cpu_delta / system_delta) * online_cpus * 100.0, rounded to 2 decimal places, returning 0.0 when either delta is not positive.
Constraints:
container_id — several containers exist and they report different usagestats exactly once, with stream=False0.0 rather than dividing by zeroOfficial solution locked
Give the problem a real attempt before peeking — revealing it affects your credit for this problem for 4 hours.