#!/bin/sh
#
# suricatavel-pgtune: tunes PostgreSQL to the machine it runs on.
#
# Measures the disk that holds the data directory, works out the settings from that and from
# the cores and memory, and prints them (messages go to stderr, settings to stdout). The measurement is kept beside postgresql.conf and
# taken again only when the cores, the memory or the disk change, or with --rebench.
#
# With --apply it writes the settings to suricatavel-tuning.conf beside postgresql.conf,
# includes that file from the last line of postgresql.conf (so it wins over earlier values,
# timescaledb-tune's among them), reloads PostgreSQL if it is running and lists the settings
# that still need a restart.
#
# The measurement is deliberately rough: an fsync rate (pg_test_fsync) and a 256 MB sequential
# write, about half a minute in all. It only has to tell an SD card from an SSD from an NVMe
# drive, and a slow one from a fast one within each.
#
# Usage: suricatavel-pgtune [--apply] [--rebench] [--data-dir DIR] [--config FILE]
#
# Without --data-dir and --config, both are asked of the running server.

set -eu

apply=0
rebench=0
data_dir=''
config_file=''

usage() {
    cat <<'EOF'
Usage: suricatavel-pgtune [--apply] [--rebench] [--data-dir DIR] [--config FILE]

Prints PostgreSQL settings tuned to this machine's cores, memory and disk.

  --apply          Write them to suricatavel-tuning.conf, include it from postgresql.conf
                   and reload PostgreSQL.
  --rebench        Measure the disk again instead of reusing the last measurement.
  --data-dir DIR   The data directory (default: asked of the running server).
  --config FILE    postgresql.conf (default: asked of the running server).
EOF
}

while [ $# -gt 0 ]; do
    case "$1" in
        --apply) apply=1 ;;
        --rebench) rebench=1 ;;
        --data-dir) data_dir=${2:?--data-dir needs a directory}; shift ;;
        --config) config_file=${2:?--config needs a file}; shift ;;
        -h | --help) usage; exit 0 ;;
        *) usage >&2; exit 2 ;;
    esac
    shift
done

log() {
    printf 'suricatavel-pgtune: %s\n' "$*" >&2
}

die() {
    log "$*"
    exit 1
}

# Runs a shell command as the postgres user when run by root, keeping stdin.
as_postgres() {
    if [ "$(id -u)" -eq 0 ] && id postgres >/dev/null 2>&1; then
        su -s /bin/sh -c "$1" postgres
    else
        sh -c "$1"
    fi
}

# Runs one SQL statement on the local server and prints its unaligned result; fails when the
# server cannot be reached.
pg_query() {
    printf '%s\n' "$1" | as_postgres 'psql -XAtq -v ON_ERROR_STOP=1 -d postgres' 2>/dev/null
}

clamp() {
    if [ "$1" -lt "$2" ]; then echo "$2"; elif [ "$1" -gt "$3" ]; then echo "$3"; else echo "$1"; fi
}

# Hundredths of a second since boot.
now_cs() {
    awk '{ printf "%d", $1 * 100 }' /proc/uptime
}

# Online cores, lowered to the cgroup CPU quota inside a container.
cpu_cores() {
    n=$(nproc 2>/dev/null || getconf _NPROCESSORS_ONLN 2>/dev/null || echo 1)
    if [ -r /sys/fs/cgroup/cpu.max ]; then
        read -r quota period </sys/fs/cgroup/cpu.max || true
        if [ "${quota:-max}" != max ] && [ "${period:-0}" -gt 0 ]; then
            q=$(((quota + period - 1) / period))
            [ "$q" -lt "$n" ] && n=$q
        fi
    fi
    [ "$n" -ge 1 ] || n=1
    echo "$n"
}

# Total memory in MB, lowered to the cgroup memory limit inside a container.
memory_mb() {
    m=$(awk '/^MemTotal:/ { printf "%d", $2 / 1024 }' /proc/meminfo)
    for limit_file in /sys/fs/cgroup/memory.max /sys/fs/cgroup/memory/memory.limit_in_bytes; do
        [ -r "$limit_file" ] || continue
        limit=$(cat "$limit_file")
        case "$limit" in
            '' | max | *[!0-9]*) ;;
            *)
                limit=$((limit / 1048576))
                if [ "$limit" -gt 0 ] && [ "$limit" -lt "$m" ]; then m=$limit; fi
                ;;
        esac
    done
    echo "$m"
}

# The whole disk under a directory (partitions and device-mapper layers resolved), or "unknown".
disk_of() {
    dev=$(stat -c %d "$1" 2>/dev/null || echo 0)
    major=$(((dev >> 8) & 0xfff))
    minor=$(((dev & 0xff) | ((dev >> 12) & 0xfff00)))
    sys=$(readlink -f "/sys/dev/block/$major:$minor" 2>/dev/null || true)
    if [ "$major" -eq 0 ] || [ -z "$sys" ] || [ ! -d "$sys" ]; then
        echo unknown
        return
    fi
    while :; do
        if [ -e "$sys/partition" ]; then
            sys=$(dirname "$sys")
        elif [ -d "$sys/slaves" ] && [ -n "$(ls "$sys/slaves" 2>/dev/null)" ]; then
            sys=$(readlink -f "$sys/slaves/$(ls "$sys/slaves" | head -n 1)")
        else
            break
        fi
    done
    basename "$sys"
}

# sd, emmc, usb, hdd, ssd, nvme or unknown.
disk_class() {
    case "$1" in
        unknown) echo unknown ;;
        mmcblk*)
            if [ "$(cat "/sys/block/$1/device/type" 2>/dev/null)" = MMC ]; then echo emmc; else echo sd; fi
            ;;
        nvme*) echo nvme ;;
        *)
            if [ "$(cat "/sys/block/$1/queue/rotational" 2>/dev/null)" = 1 ]; then
                echo hdd
            elif readlink -f "/sys/block/$1" 2>/dev/null | grep -q /usb; then
                echo usb
            else
                echo ssd
            fi
            ;;
    esac
}

find_pg_test_fsync() {
    if command -v pg_test_fsync >/dev/null 2>&1; then
        command -v pg_test_fsync
        return
    fi
    for candidate in $(ls -d /usr/lib/postgresql/*/bin/pg_test_fsync /usr/pgsql-*/bin/pg_test_fsync 2>/dev/null | sort -V -r); do
        [ -x "$candidate" ] && echo "$candidate" && return
    done
    if command -v pg_config >/dev/null 2>&1 && [ -x "$(pg_config --bindir)/pg_test_fsync" ]; then
        echo "$(pg_config --bindir)/pg_test_fsync"
    fi
}

# fdatasync calls per second for one 8 kB write, or 0 when it cannot be measured. awk stops
# reading at that line, so pg_test_fsync ends there instead of running its other tests.
fsync_rate() {
    tool=$(find_pg_test_fsync)
    rate=''
    if [ -n "$tool" ]; then
        rate=$(LC_ALL=C "$tool" -s 1 -f "$1" 2>/dev/null \
            | awk '/one 8kB write/ { section = 1 } section && $1 == "fdatasync" && $2 ~ /^[0-9.]+$/ { printf "%d", $2; exit }' || true)
    fi
    rm -f "$1"
    echo "${rate:-0}"
}

# MB per second writing 256 MB and syncing them.
sequential_write_rate() {
    start=$(now_cs)
    if ! dd if=/dev/zero of="$1" bs=1048576 count=256 conv=fsync 2>/dev/null; then
        rm -f "$1"
        die "failed to write 256 MB test file in $(dirname "$1")"
    fi
    end=$(now_cs)
    rm -f "$1"
    elapsed=$((end - start))
    [ "$elapsed" -ge 1 ] || elapsed=1
    echo $((256 * 100 / elapsed))
}

bench_value() {
    sed -n "s/^$1=//p" "$bench_file" 2>/dev/null | head -n 1
}

# --- Where things are -------------------------------------------------------------------------

[ -n "$config_file" ] || config_file=$(pg_query 'SHOW config_file' || true)
[ -n "$data_dir" ] || data_dir=$(pg_query 'SHOW data_directory' || true)
[ -n "$config_file" ] && [ -f "$config_file" ] || die 'postgresql.conf not found: start PostgreSQL or pass --config'
[ -n "$data_dir" ] && [ -d "$data_dir" ] || die 'data directory not found: start PostgreSQL or pass --data-dir'

conf_dir=$(dirname "$config_file")
tuning_name=suricatavel-tuning.conf
tuning_file="$conf_dir/$tuning_name"
bench_file="$conf_dir/suricatavel-tuning.bench"

# --- The machine and its disk -----------------------------------------------------------------

cores=$(cpu_cores)
memory=$(memory_mb)
disk=$(disk_of "$data_dir")
class=$(disk_class "$disk")
fingerprint="$cores cores, $memory MB, $disk"

if [ "$rebench" -eq 0 ] && [ -f "$bench_file" ] && [ "$(bench_value fingerprint)" = "$fingerprint" ]; then
    fsync=$(bench_value fsync)
    seq_write=$(bench_value seq_write)
    bench_date=$(bench_value date)
else
    [ -w "$data_dir" ] || die "cannot write to $data_dir: run as root or as the postgres user"
    log "measuring the disk under $data_dir (about half a minute)"
    probe="$data_dir/suricatavel-pgtune.$$"
    trap 'rm -f "$probe"' EXIT INT TERM
    fsync=$(fsync_rate "$probe")
    seq_write=$(sequential_write_rate "$probe")
    bench_date=$(date +%Y-%m-%d)
    if [ -w "$conf_dir" ]; then
        printf 'fingerprint=%s\ndate=%s\nfsync=%s\nseq_write=%s\n' "$fingerprint" "$bench_date" "$fsync" "$seq_write" >"$bench_file"
        if [ "$(id -u)" -eq 0 ]; then
            chown "$(stat -c %u:%g "$config_file")" "$bench_file" 2>/dev/null || true
        fi
    fi
fi

case "$fsync" in '' | *[!0-9]*) fsync=0 ;; esac
case "$seq_write" in '' | *[!0-9]*) seq_write=1 ;; esac
[ "$seq_write" -ge 1 ] || seq_write=1

# slow (0): SD cards, USB sticks, hard disks; medium (1): SATA SSDs, eMMC; fast (2): NVMe and
# SSDs with power-loss protection. The worse of the two measurements decides: an SD card's
# cache can absorb small synced writes at SSD rates while it writes 8 MB/s sustained. Without
# an fsync rate, the kind of disk stands in for it. A disk reported as rotational is not taken
# at its word when measured: virtual disks (WSL, Docker Desktop, many VMs) report it on SSDs.
if [ "$seq_write" -lt 60 ]; then tier=0; elif [ "$seq_write" -lt 1000 ]; then tier=1; else tier=2; fi
if [ "$fsync" -gt 0 ]; then
    if [ "$fsync" -lt 500 ]; then fsync_tier=0; elif [ "$fsync" -lt 5000 ]; then fsync_tier=1; else fsync_tier=2; fi
else
    case "$class" in
        nvme) fsync_tier=2 ;;
        ssd | emmc) fsync_tier=1 ;;
        *) fsync_tier=0 ;;
    esac
fi
[ "$fsync_tier" -lt "$tier" ] && tier=$fsync_tier
case "$tier" in 0) tier=slow ;; 1) tier=medium ;; *) tier=fast ;; esac

# --- Settings ---------------------------------------------------------------------------------

# Write capacity in MB/s: the sequential rate, capped by what the fsync rate suggests for the
# scattered writes vacuum and checkpoints make (64 kB per fsync).
capacity=$seq_write
if [ "$fsync" -gt 0 ] && [ $((fsync / 16)) -lt "$capacity" ]; then
    capacity=$((fsync / 16))
fi
[ "$capacity" -ge 1 ] || capacity=1

# Autovacuum dirties at most a quarter of that: with the default 2 ms delay and 20 credits per
# dirtied 8 kB page, each credit of the limit is about 0.195 MB/s.
vacuum_cost_limit=$(clamp $((capacity * 128 / 100)) 20 2000)

case "$tier" in
    slow)
        if [ "$cores" -ge 4 ]; then autovacuum_workers=2; else autovacuum_workers=1; fi
        io_concurrency=2
        random_page_cost=2.0
        ;;
    medium)
        autovacuum_workers=3
        io_concurrency=64
        random_page_cost=1.1
        ;;
    fast)
        autovacuum_workers=$(clamp $((cores / 2)) 3 8)
        io_concurrency=256
        random_page_cost=1.1
        ;;
esac
if [ "$class" = hdd ] && [ "$tier" = slow ]; then random_page_cost=4.0; fi

# WAL: a larger max_wal_size spaces checkpoints, so fewer full-page writes; 3 % of the
# filesystem, between 1 and 8 GB.
fs_mb=$(df -Pk "$data_dir" | awk 'NR == 2 { printf "%d", $2 / 1024 }')
max_wal=$(clamp $((fs_mb * 3 / 100)) 1024 8192)
min_wal=$((max_wal / 4))

# lz4 when this build has it: asked of the server, or of pg_config when it is stopped, so that
# both give the same file.
lz4=$(pg_query "SELECT 'lz4' = ANY(enumvals) FROM pg_settings WHERE name = 'wal_compression'" || true)
if [ -z "$lz4" ]; then
    pg_config=$(dirname "$(find_pg_test_fsync)")/pg_config
    command -v "$pg_config" >/dev/null 2>&1 || pg_config=pg_config
    if "$pg_config" --configure 2>/dev/null | grep -q -- --with-lz4; then lz4=t; fi
fi
if [ "$lz4" = t ]; then wal_compression=lz4; else wal_compression=on; fi

# Asked of the server, or the last value in postgresql.conf when it is stopped.
max_connections=$(pg_query 'SHOW max_connections' || true)
if [ -z "$max_connections" ]; then
    max_connections=$(awk -F= '/^[[:space:]]*max_connections[[:space:]]*=/ { v = $2 } END { gsub(/^[[:space:]]*/, "", v); gsub(/[^0-9].*$/, "", v); print v }' "$config_file")
fi
case "$max_connections" in '' | *[!0-9]*) max_connections=100 ;; esac

shared_buffers=$(clamp $((memory / 4)) 128 16384)
effective_cache=$((memory * 3 / 4))
maintenance_work_mem=$(clamp $((memory / 16)) 64 1024)
work_mem=$(clamp $(((memory - shared_buffers) / (max_connections * 3))) 4 64)
parallel_per_gather=$(clamp $((cores / 2)) 1 8)
background_workers=$(clamp $((cores * 2)) 8 16)
worker_processes=$((background_workers + cores + 3))

settings=$(cat <<EOF
# Written by suricatavel-pgtune; run it again (with --apply) rather than editing this file.
# Machine: $cores cores, $memory MB of memory, data directory on $disk ($class disk).
# Measured on $bench_date: $fsync fsync/s, $seq_write MB/s sequential write ($tier disk).

shared_buffers = '${shared_buffers}MB'
effective_cache_size = '${effective_cache}MB'
work_mem = '${work_mem}MB'
maintenance_work_mem = '${maintenance_work_mem}MB'
wal_buffers = -1

max_worker_processes = $worker_processes
max_parallel_workers = $cores
max_parallel_workers_per_gather = $parallel_per_gather
max_parallel_maintenance_workers = $parallel_per_gather
timescaledb.max_background_workers = $background_workers
max_locks_per_transaction = 256

effective_io_concurrency = $io_concurrency
maintenance_io_concurrency = $io_concurrency
random_page_cost = $random_page_cost

checkpoint_timeout = '15min'
checkpoint_completion_target = 0.9
max_wal_size = '${max_wal}MB'
min_wal_size = '${min_wal}MB'
wal_compression = $wal_compression

autovacuum_max_workers = $autovacuum_workers
autovacuum_naptime = '1min'
autovacuum_vacuum_cost_delay = '2ms'
autovacuum_vacuum_cost_limit = $vacuum_cost_limit
EOF
)

printf '%s\n' "$settings"
[ "$apply" -eq 1 ] || exit 0

# --- Apply ------------------------------------------------------------------------------------

[ -w "$conf_dir" ] || die "cannot write to $conf_dir: run as root or as the postgres user"

if [ -f "$tuning_file" ] && [ "$(cat "$tuning_file")" = "$settings" ]; then
    changed=0
else
    printf '%s\n' "$settings" >"$tuning_file"
    changed=1
fi

include="include_if_exists = '$tuning_name'"
if [ "$(awk 'NF { last = $0 } END { print last }' "$config_file")" != "$include" ]; then
    rewritten="$config_file.suricatavel-pgtune.$$"
    grep -vxF "$include" "$config_file" >"$rewritten" || true
    printf '%s\n' "$include" >>"$rewritten"
    # Rewriting in place keeps the file's owner and mode.
    cat "$rewritten" >"$config_file"
    rm -f "$rewritten"
    changed=1
fi

if [ "$(id -u)" -eq 0 ]; then
    chown "$(stat -c %u:%g "$config_file")" "$tuning_file" "$bench_file" 2>/dev/null || true
fi

if [ "$changed" -eq 1 ]; then
    log "applied to $tuning_file"
else
    log 'unchanged'
fi

if [ "$(pg_query 'SELECT pg_reload_conf()' || true)" != t ]; then
    log 'PostgreSQL is not running: the settings apply when it starts'
    exit 0
fi

sleep 1
# Settings that need a restart are reported by pending_restart below, not as errors.
errors=$(pg_query "SELECT string_agg(name || ': ' || error, '; ') FROM pg_file_settings WHERE error IS NOT NULL AND error <> 'setting could not be applied' AND sourcefile LIKE '%/$tuning_name'" || true)
[ -z "$errors" ] || die "PostgreSQL rejected settings: $errors"

pending=$(pg_query "SELECT string_agg(name, ', ' ORDER BY name) FROM pg_settings WHERE pending_restart" || true)
if [ -n "$pending" ]; then
    log "restart PostgreSQL to apply: $pending"
fi
