Skip to content

Instantly share code, notes, and snippets.

@mlin
Last active March 5, 2020 09:43
Show Gist options
  • Save mlin/6ff9b577703165d6d5833ea70b5dd5e6 to your computer and use it in GitHub Desktop.
Save mlin/6ff9b577703165d6d5833ea70b5dd5e6 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Running inside a docker container, periodically read the container's CPU/memory usage counters
# and log them to standard error. Fields:
#
# cpu_pct average user %CPU usage over the most recent period
# mem_MiB container's current RSS (excludes file cache), in mebibytes (= 2**20 bytes)
# cpu_total_s container's user CPU time consumption since this script started, in seconds
# elapsed_s wall time elapsed since this script started, in seconds
#
#
# YMMV: host OS version & configuration may affect availability of the needed counters under
# /sys/fs/cgroup
log_cpu_mem_in_docker() {
PERIOD_SECS=${1:-10} # logging period (default 10s)
JIFFIES_PER_SEC=100 # see http://man7.org/linux/man-pages/man7/time.7.html
T_0=$(date +%s)
cpu_user_jiffies() {
cut -f2 -d ' ' /sys/fs/cgroup/cpuacct/cpuacct.stat | head -n 1
}
user_jiffies_0=$(cpu_user_jiffies)
user_jffies_last=$user_jiffies_0
t_last=$T_0
while true; do
sleep "$PERIOD_SECS"
t=$(date +%s)
wall_secs=$(( t - T_0 ))
user_jiffies=$(cpu_user_jiffies)
user_pct=$(( 100*(user_jiffies - user_jffies_last)/JIFFIES_PER_SEC/(t - t_last) ))
user_secs=$(( (user_jiffies - user_jiffies_0)/ JIFFIES_PER_SEC ))
user_jffies_last=$user_jiffies
t_last=$t
rss_bytes=$(awk -F ' ' '$1 == "total_rss" { print $2 }' /sys/fs/cgroup/memory/memory.stat)
>&2 echo "container_usage :: cpu_pct: ${user_pct}, mem_MiB: $(( rss_bytes/1048576 )), cpu_total_s: ${user_secs}, elapsed_s: ${wall_secs}"
done
}
log_cpu_mem_in_docker "$1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment