repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
fan.nixNix125 lines6.2 KiBraw download
# modules/home/fan.nix — `fan`: the laptop's fans from the terminal, safely.
#
#   fan              one line: CPU °C, fan rpm and %, clock cap, load, clamp yes/no, EC mode
#   fan watch [s]    the same line every s seconds (default 2), Ctrl-C to stop
#   fan max          100 % now, with the watchdog (below)        fan 60   fixed 60 % (30-100)
#   fan auto         back to the EC's own curve; stops the watchdog
#   fan log          what the watchdog has done
#
# Why a watchdog: this laptop's EC, once in manual fan mode, asserts PROCHOT
# and pins every core at 399 MHz as soon as load starts (fan-throttle-guard.nix).
# `fan max` therefore starts a transient user unit (fan-watchdog) that samples
# /proc/stat and /proc/cpuinfo every second and, the moment CPU busy ≥ 25 %
# while no core is above 600 MHz (fanfix's clamp rule), runs `fan-ec auto`,
# sends a notification and exits. Root access is `sudo -n fan-ec …`
# (modules/hosts/laptop/fan-cli.nix: a store script with a passwordless rule for wheel).
# Reads need no root at all: k10temp and the uniwill hwmon are world-readable.
{ ... }:
{
  flake.homeModules.fan =
  { pkgs, lib, ... }:
  let
    bin = lib.makeBinPath [ pkgs.coreutils pkgs.gawk pkgs.gnugrep pkgs.gnused pkgs.systemd pkgs.libnotify ];
    # NixOS's setuid sudo lives in /run/wrappers; the store copy is not setuid
    # and refuses to run ("must be owned by uid 0 and have the setuid bit set").
    sudo = "/run/wrappers/bin/sudo";

    # shared read-only sampler, sourced by both scripts
    lib-sh = pkgs.writeText "fan-lib.sh" ''
      TRIP_MHZ=600; BUSY_MIN=25
      STATE=''${XDG_RUNTIME_DIR:-/tmp}/fan.stat
      hw() { local n; for h in /sys/class/hwmon/hwmon*; do n=$(cat "$h/name" 2>/dev/null); [ "$n" = "$1" ] && { echo "$h"; return; }; done; }
      cpu_temp() { local h; h=$(hw k10temp); [ -n "$h" ] && echo $(( $(cat "$h/temp1_input") / 1000 )) || echo -; }
      fan_rpm()  { local h; h=$(hw uniwill); [ -n "$h" ] && cat "$h/fan1_input" || echo -; }
      fan_pct()  { local h; h=$(hw uniwill); [ -n "$h" ] && echo $(( $(cat "$h/pwm1") * 100 / 255 )) || echo -; }
      gpu_temp() { local h; h=$(hw uniwill); [ -n "$h" ] && echo $(( $(cat "$h/temp2_input") / 1000 )) || echo -; }
      cap_mhz()  { echo $(( $(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq) / 1000 )); }
      clocks()   { awk '/^cpu MHz/ {s+=$4; n++; if ($4>m) m=$4} END {printf "%d %d", (n?s/n:0), m}' /proc/cpuinfo; }
      # CPU busy % since the previous call (snapshot in $STATE); 0 on the first call
      busy() {
        local cur prev b=0
        cur=$(head -1 /proc/stat)
        [ -r "$STATE" ] && prev=$(cat "$STATE") || prev=
        printf '%s' "$cur" > "$STATE"
        [ -n "$prev" ] && b=$(awk -v a="$prev" -v b="$cur" 'BEGIN {
          na=split(a,x," "); nb=split(b,y," "); ta=0; tb=0
          for (i=2;i<=na;i++) ta+=x[i]; for (i=2;i<=nb;i++) tb+=y[i]
          ia=x[5]+x[6]; ib=y[5]+y[6]; d=tb-ta; if (d<=0) {print 0; exit}
          printf "%d", 100*(d-(ib-ia))/d }')
        echo "$b"
      }
      clamped() {  # 1 when busy yet no core above TRIP_MHZ
        local b=$1 mx=$2; [ "$b" -ge "$BUSY_MIN" ] && [ "$mx" -gt 0 ] && [ "$mx" -lt "$TRIP_MHZ" ] && echo 1 || echo 0
      }
      ec_mode() { ${sudo} -n /run/current-system/sw/bin/fan-ec mode 2>/dev/null || echo "?"; }
      status_line() {
        local b mx avg; b=$(busy); read -r avg mx <<< "$(clocks)"
        local cl; cl=$(clamped "$b" "$mx")
        printf 'CPU %s°C · GPU %s°C · fan %s rpm %s%% · cap %s MHz · clocks avg %s / max %s · load %s%% · clamp %s · fans %s\n' \
          "$(cpu_temp)" "$(gpu_temp)" "$(fan_rpm)" "$(fan_pct)" "$(cap_mhz)" "$avg" "$mx" "$b" \
          "$([ "$cl" = 1 ] && echo YES || echo no)" "$(ec_mode)"
      }
    '';

    fan-watchdog = pkgs.writeShellScriptBin "fan-watchdog" ''
      set -uo pipefail
      PATH=${bin}:$PATH
      . ${lib-sh}
      LOG=''${XDG_STATE_HOME:-$HOME/.local/state}/fan-watchdog.log; mkdir -p "$(dirname "$LOG")"
      log() { printf '%s %s\n' "$(date '+%F %T')" "$*" >> "$LOG"; }
      log "armed: fans manual ($1), watching for the EC clamp"
      busy >/dev/null; sleep 1
      while :; do
        b=$(busy); read -r _ mx <<< "$(clocks)"
        if [ "$(clamped "$b" "$mx")" = 1 ]; then
          out=$(${sudo} -n /run/current-system/sw/bin/fan-ec auto 2>&1)
          log "CLAMP: load $b %, max core $mx MHz -> fan-ec auto: $out"
          notify-send -a fan -u critical "Fans back to auto" "EC clamp hit (load $b %, cores at $mx MHz). Manual fan mode released."
          exit 0
        fi
        sleep 1
      done
    '';

    fan = pkgs.writeShellScriptBin "fan" ''
      set -uo pipefail
      PATH=${bin}:$PATH
      . ${lib-sh}
      UNIT=fan-watchdog
      EC=/run/current-system/sw/bin/fan-ec
      LOG=''${XDG_STATE_HOME:-$HOME/.local/state}/fan-watchdog.log

      arm() {  # start (or restart) the watchdog as a transient user unit
        systemctl --user stop "$UNIT" 2>/dev/null || true
        systemd-run --user --unit="$UNIT" --collect --quiet ${fan-watchdog}/bin/fan-watchdog "$1" \
          && echo "watchdog armed: back to auto the moment the EC clamps the CPU (fan log)"
      }
      disarm() { systemctl --user stop "$UNIT" 2>/dev/null || true; }

      if [ "$(id -u)" = 0 ]; then
        echo "fan: run this as yourself, not under sudo (it needs your user session for the watchdog; root access is handled inside)" >&2
        exit 1
      fi

      case "''${1:-}" in
        ""|status) status_line ;;
        watch)
          iv=''${2:-2}; busy >/dev/null; sleep "$iv"
          while :; do status_line; sleep "$iv"; done ;;
        max)   ${sudo} -n "$EC" max  && arm max ;;
        auto)  disarm; ${sudo} -n "$EC" auto ;;
        [0-9]*) p=''${1%\%}; ${sudo} -n "$EC" "$p" && arm "$p %" ;;
        ec)    ${sudo} -n "$EC" status ;;
        log)   [ -r "$LOG" ] && tail -n ''${2:-20} "$LOG" || echo "no watchdog log yet" ;;
        -h|--help|help)
          echo "usage: fan [status] | watch [sec] | max | <30-100> | auto | ec | log [n]"
          echo "  max / <pct> put the fans in manual mode WITH the clamp watchdog; auto releases them." ;;
        *) echo "fan: unknown command '$1' (try: fan help)" >&2; exit 2 ;;
      esac
    '';
  in
  {
    home.packages = [ fan fan-watchdog ];
  }
  ;
}