#!/usr/bin/env bash
# HostingSpecs VPS benchmark — https://hostingspecs.com/bench
#
#   curl -sL https://hostingspecs.com/bench.sh | bash            # test this server (about 1 minute)
#   curl -sL https://hostingspecs.com/bench.sh | bash -s -- --no-disk
#
# Measures the same things, the same way, as our own test servers:
#   CPU steal   share of CPU time taken by other customers on the same machine (/proc/stat)
#   CPU         sysbench prime test, 1 thread and all threads (events per second, higher is better)
#   Disk        fio 4k random read and random write (IOPS, read latency), 256 MB file, direct I/O
# Nothing is uploaded. At the end you get a link that shows your results next to
# ours; the numbers travel in the link itself (after the #), so our server never sees them.
#
# --agent mode is what runs hourly on HostingSpecs' own test servers (infra/vps/setup.sh):
# it writes JSON to $HS_OUT (default /var/www/hs/hs-vps.json) for our probe to read,
# runs the disk test only once a day (03:xx UTC) and samples steal for 60 s.
#
# Needs: bash, sysbench and fio (sudo apt install -y sysbench fio). Python 3 is used
# to read fio's output if present. Safe to read before running: it only reads /proc,
# runs the two benchmarks and deletes its test file.
set -u
VERSION=1
MODE=report; DISK=1
for a in "$@"; do case "$a" in --agent) MODE=agent ;; --no-disk) DISK=0 ;; --disk) DISK=2 ;; esac; done
OUT="${HS_OUT:-/var/www/hs/hs-vps.json}"
TMPDIR="${HS_TMP:-${TMPDIR:-/tmp}}"
say() { [ "$MODE" = report ] && printf '%s\n' "$*"; }

need() { command -v "$1" >/dev/null 2>&1; }
if ! need sysbench; then
  say "sysbench is not installed. Install it and run again:"
  say "  Debian/Ubuntu: sudo apt install -y sysbench fio"
  say "  RHEL/Fedora:   sudo dnf install -y sysbench fio   (EPEL on RHEL)"
  exit 1
fi

# --- CPU steal: two /proc/stat samples ------------------------------------------
cpu_line() { awk '/^cpu /{print $2+$3+$4+$5+$6+$7+$8+$9, $9}' /proc/stat; }
SAMPLE=$([ "$MODE" = agent ] && echo 60 || echo 15)
say "HostingSpecs VPS benchmark v$VERSION"
say "Sampling CPU steal for ${SAMPLE}s..."
read -r T1 S1 < <(cpu_line); sleep "$SAMPLE"; read -r T2 S2 < <(cpu_line)
STEAL=$(awk -v t=$((T2 - T1)) -v s=$((S2 - S1)) 'BEGIN { printf "%.2f", (t > 0 ? 100 * s / t : 0) }')

# --- CPU -------------------------------------------------------------------------
VCPUS=$(nproc 2>/dev/null || echo 1)
cpu_eps() { sysbench cpu --cpu-max-prime=20000 --threads="$1" --time=10 run 2>/dev/null | awk -F: '/events per second/ { gsub(/ /, "", $2); print $2 }'; }
say "CPU test, 1 thread (10s)..."; CPU1=$(cpu_eps 1)
say "CPU test, $VCPUS threads (10s)..."; CPUN=$(cpu_eps "$VCPUS")

# --- Disk ------------------------------------------------------------------------
RIOPS=null; WIOPS=null; RLAT=null
RUN_DISK=0
if [ "$DISK" -ge 1 ] && need fio; then
  if [ "$MODE" = report ] || [ "$DISK" = 2 ] || [ "$(date -u +%H)" = "03" ]; then RUN_DISK=1; fi
elif [ "$DISK" -ge 1 ]; then say "fio is not installed: skipping the disk test (sudo apt install -y fio)."; fi
fio_run() { # $1 = randread | randwrite ; prints "iops lat_us"
  local f="$TMPDIR/hs-fio-$$.tmp" j
  j=$(fio --name=hs --filename="$f" --size=256M --direct=1 --rw="$1" --bs=4k --iodepth=32 --ioengine=libaio \
        --runtime=15 --time_based --group_reporting --output-format=json 2>/dev/null)
  rm -f "$f"
  if need python3; then
    printf '%s' "$j" | python3 -c 'import json,sys
d=json.load(sys.stdin)["jobs"][0]; k="read" if d["read"]["iops"]>0 else "write"
lat=d[k].get("clat_ns",{}).get("mean") or 0
print(int(d[k]["iops"]), int(lat/1000))' 2>/dev/null
  else
    printf '%s' "$j" | grep -o '"iops" : [0-9.]*' | awk '$3 > 0 { printf "%d null\n", $3; exit }'
  fi
}
if [ "$RUN_DISK" = 1 ]; then
  say "Disk test, 4k random read (15s)..."; read -r RIOPS RLAT < <(fio_run randread || echo "null null")
  say "Disk test, 4k random write (15s)..."; read -r WIOPS _ < <(fio_run randwrite || echo "null null")
  RIOPS=${RIOPS:-null}; WIOPS=${WIOPS:-null}; RLAT=${RLAT:-null}
fi

MODEL=$(awk -F: '/model name/ { sub(/^ +/, "", $2); print $2; exit }' /proc/cpuinfo | tr -d '"\\' | cut -c1-120)
KERNEL=$(uname -r | tr -d '"\\')
TS=$(date -u +%Y-%m-%dT%H:%M:%SZ)
JSON=$(printf '{"hs_vps":1,"v":%s,"ts":"%s","steal_pct":%s,"cpu_single":%s,"cpu_multi":%s,"disk_read_iops":%s,"disk_write_iops":%s,"disk_lat_us":%s,"vcpus":%s,"cpu_model":"%s","kernel":"%s"}' \
  "$VERSION" "$TS" "$STEAL" "${CPU1:-null}" "${CPUN:-null}" "$RIOPS" "$WIOPS" "$RLAT" "$VCPUS" "$MODEL" "$KERNEL")

if [ "$MODE" = agent ]; then
  # Disk numbers are null except on the daily disk run; the database keeps one value a day.
  mkdir -p "$(dirname "$OUT")" && printf '%s\n' "$JSON" > "$OUT.tmp" && mv "$OUT.tmp" "$OUT"
  exit 0
fi

echo
echo "Your server"
printf '  %-24s %s\n' "CPU" "$MODEL ($VCPUS vCPU)"
printf '  %-24s %s%%\n' "CPU steal (${SAMPLE}s)" "$STEAL"
printf '  %-24s %s events/s\n' "CPU, 1 thread" "${CPU1:-n/a}"
printf '  %-24s %s events/s\n' "CPU, all threads" "${CPUN:-n/a}"
printf '  %-24s %s IOPS\n' "Disk, random read" "$RIOPS"
printf '  %-24s %s IOPS\n' "Disk, random write" "$WIOPS"
echo
if need base64; then
  B=$(printf '%s' "$JSON" | base64 | tr -d '\n=' | tr '+/' '-_')
  echo "Compare with the providers we test:"
  echo "  https://hostingspecs.com/bench#r=$B"
fi
echo "One run is a snapshot: CPU steal in particular varies hour to hour. Run it a few times."
