dockerode
dockerode copied to clipboard
Container stats returns incorrect data
I`m trying to get "live" stats of the container with the following code:
const stats = (await getContainer.stats({ stream: true })) as any;
stats.on("data", (rawstat: Buffer) => {
console.log(rawstat.toString());
const { cpu_stats, precpu_stats, memory_stats } = JSON.parse(
rawstat.toString()
) as Dockerode.ContainerStats;
if (Object.keys(memory_stats).length == 0) stats.destroy;
console.log(memory_stats);
const cpuDelta =
cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage;
const systemDelta =
cpu_stats.system_cpu_usage - precpu_stats.system_cpu_usage;
const used_memory = memory_stats.usage - (memory_stats.stats.cache || 0);
const available_memory = memory_stats.limit;
console.log({
memory: Math.round((used_memory / available_memory) * 100.0),
cpu: Math.round((cpuDelta / systemDelta) * 100),
});
});
stats.on("end", () => {
console.log("stopped loggin resources for", id);
});
However sometimes it returns invalid JSON and it also seems to be cut off: {"read":"2022-07-01T19:48:36.597431164Z","preread":"2022-07-01T19:48:35.575833364Z","pids_stats":{"current":7,"limit":2276},"blkio_stats":{"io_service_bytes_recursive":[{"major":8,"minor":0,"op":"read","value":0},{"major":8,"minor":0,"op":"write","value":397312}],"io_serviced_recursive":null,"io_queue_recursive":null,"io_service_time_recursive":null,"io_wait_time_recursive":null,"io_merged_recursive":null,"io_time_recursive":null,"sectors_recursive":null},"num_procs":0,"storage_stats":{},"cpu_stats":{"cpu_usage":{"total_usage":388555000,"usage_in_kernelmode":212350000,"usage_in_usermode":176205000},"system_cpu_usage":4309308580000000,"online_cpus":1,"throttling_data":{"periods":224,"throttled_periods":0,"throttled_time":0}},"precpu_stats":{"cpu_usage":{"total_usage":388555000,"usage_in_kernelmode":212350000,"usage_in_usermode":176205000},"system_cpu_usage":4309307570000000,"online_cpus":1,"throttling_data":{"periods":224,"throttled_periods":0,"throttled_time":0}},"memory_stats":{"usage":19972096,"stats":{"active_anon":4866048,"active_file":135168,"anon":3907584,"anon_thp":0,"file":13922304,"file_dirty":0,"file_mapped":11354112,"file_writeback":0,"inactive_anon":12820480,"inactive_file":135168,"kernel_stack":147456,"pgactivate":1221,"pgdeactivate":0,"pgfault":20691,"pglazyfree":0,"pglazyfreed":0,"pgmajfault":0,"pgrefill":0,"pgscan":0,"pgsteal":0,"shmem":13787136,"slab":1050248,"slab_reclaimable":262904,"slab_unreclaimable":7
As you can see, there is a piece missing. Does someone know a better way of getting the stats or how to solve this?
quick note, i am streaming from a server at the moment, the docker deamon is not running on localhost