Skip to content

Instantly share code, notes, and snippets.

@abelardojarab
Created October 4, 2025 19:10
Show Gist options
  • Select an option

  • Save abelardojarab/777a315e1736ba2b6d1c32212566cb48 to your computer and use it in GitHub Desktop.

Select an option

Save abelardojarab/777a315e1736ba2b6d1c32212566cb48 to your computer and use it in GitHub Desktop.
Script to periodically sample WCPU using top and aggregate it over all openssl processes
#!/bin/sh
# FreeBSD: sample 'top' every INTERVAL seconds, sum WCPU for lines matching PATTERN,
# write CSV, stop after MISSING_LIMIT consecutive snapshots with zero matches.
#
# Usage:
# ./openssl_top_watch.sh [interval_secs] [missing_limit] [out_csv]
# Defaults:
# interval_secs = 5
# missing_limit = 3
# out_csv = /var/tmp/openssl_top_$(hostname -s)_$(date -u +%Y%m%dT%H%M%SZ).csv
#
# Env:
# PATTERN='openssl' # awk regex to match process lines (against full line)
# TOP_N=64 # how many rows to ask 'top' to print (best-effort)
set -eu
INTERVAL="${1:-5}"
MISSING_LIMIT="${2:-3}"
HOST="$(hostname -s 2>/dev/null || hostname)"
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
CSV="${3:-/var/tmp/openssl_top_${HOST}_${STAMP}.csv}"
PATTERN="${PATTERN:-openssl}"
TOP_N="${TOP_N:-64}"
command -v top >/dev/null || { echo "top not found"; exit 1; }
command -v awk >/dev/null || { echo "awk not found"; exit 1; }
echo "# writing CSV to: $CSV"
echo "timestamp,openssl_wcpu_sum,match_count" > "$CSV"
misses=0
samples=0
trap 'echo "# stop signal"; exit 0' INT TERM
while :; do
TS="$(date -u +%FT%TZ)"
# One snapshot; -b=batch, -n=rows; -d=delay-per-refresh (not needed for single)
SNAP="$(top -b -n "$TOP_N" -d 1 2>/dev/null || true)"
# Sum WCPU over matching lines in the *process table*.
# We start after the header line that begins with "PID USERNAME".
read -r SUM CNT <<EOF
$(printf "%s\n" "$SNAP" | awk -v pat="$PATTERN" '
start==0 && $1=="PID" && $2=="USERNAME" { start=1; next }
start==1 && NF==0 { start=0; next }
start==1 {
if ($0 ~ pat) {
# WCPU is the last field that looks like 12.34%
for (i=NF; i>=1; i--) if ($i ~ /^[0-9.]+%$/) { v=$i; gsub("%","",v); s+=v; c++; break }
}
}
END {
if (s=="") s=0;
if (c=="") c=0;
printf "%.2f %d", s, c
}')
EOF
echo "$TS,$SUM,$CNT" >> "$CSV"
samples=$((samples+1))
echo "[#${samples}] $TS openssl_wcpu_sum=${SUM}% matches=${CNT}"
if [ "$CNT" -eq 0 ]; then
misses=$((misses+1))
else
misses=0
fi
if [ "$misses" -ge "$MISSING_LIMIT" ]; then
echo "# no \"$PATTERN\" for last $MISSING_LIMIT samples — stopping."
break
fi
sleep "$INTERVAL"
done
echo "# done. CSV: $CSV"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment