system-stats.sh 1000 B

123456789101112131415161718192021222324252627
  1. #!/usr/bin/env bash
  2. #
  3. # Reports cpu and ram usage statistics
  4. #
  5. set -e
  6. [[ $(uname) == Linux ]] || exit 0
  7. # need to cd like this to avoid #SC1091
  8. cd "$(dirname "$0")/.."
  9. source scripts/configure-metrics.sh
  10. while true; do
  11. # collect top twice because the first time is inaccurate
  12. top_output="$(top -bn2 -d1)"
  13. # collect the total cpu usage by subtracting idle usage from 100%
  14. cpu_usage=$(echo "${top_output}" | grep '%Cpu(s):' | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | tail -1 | awk '{print 100 - $1}')
  15. # collect the total ram usage by dividing used memory / total memory
  16. ram_total_and_usage=$(echo "${top_output}" | grep '.*B Mem'| tail -1 | sed "s/.*: *\([0-9.]*\)%* total.*, *\([0-9.]*\)%* used.*/\1 \2/")
  17. read -r total used <<< "$ram_total_and_usage"
  18. ram_usage=$(awk "BEGIN {print $used / $total * 100}")
  19. cpu_report="cpu_usage=$cpu_usage,ram_usage=$ram_usage"
  20. report="${cpu_report}"
  21. ./scripts/metrics-write-datapoint.sh "system-stats,hostname=$HOSTNAME $report"
  22. sleep 1
  23. done