diff --git a/modules/services/monitoring/_mocha.nix b/modules/services/monitoring/_mocha.nix new file mode 100644 index 0000000..968d537 --- /dev/null +++ b/modules/services/monitoring/_mocha.nix @@ -0,0 +1,80 @@ +{ pkgs, grafana }: let + swaps = [ + [ ''gray05:"#111217"'' ''gray05:"#11111b"'' ] + [ ''gray10:"#181b1f"'' ''gray10:"#1e1e2e"'' ] + [ ''gray15:"#22252b"'' ''gray15:"#313244"'' ] + [ ''gray20:"#2c2f35"'' ''gray20:"#45475a"'' ] + [ ''gray25:"#383b42"'' ''gray25:"#585b70"'' ] + [ ''whiteBase="204, 204, 220"'' ''whiteBase="205, 214, 244"'' ] + + [ ''blueDarkMain:"#3d71d9"'' ''blueDarkMain:"#cba6f7"'' ] + [ ''blueDarkText:"#6e9fff"'' ''blueDarkText:"#cba6f7"'' ] + [ ''redDarkMain:"#d10e5c"'' ''redDarkMain:"#f38ba8"'' ] + [ ''redDarkText:"#ff5286"'' ''redDarkText:"#f38ba8"'' ] + [ ''greenDarkMain:"#1a7f4b"'' ''greenDarkMain:"#a6e3a1"'' ] + [ ''greenDarkText:"#6ccf8e"'' ''greenDarkText:"#a6e3a1"'' ] + [ ''orangeDarkMain:"#ff9900"'' ''orangeDarkMain:"#fab387"'' ] + [ ''orangeDarkText:"#fbad37"'' ''orangeDarkText:"#fab387"'' ] + + [ ''{color:"#73BF69",name:"green"'' ''{color:"#a6e3a1",name:"green"'' ] + [ ''{color:"#F2495C",name:"red"'' ''{color:"#f38ba8",name:"red"'' ] + [ ''{color:"#FADE2A",name:"yellow"'' ''{color:"#f9e2af",name:"yellow"'' ] + [ ''{color:"#5794F2",name:"blue"'' ''{color:"#89b4fa",name:"blue"'' ] + [ ''{color:"#FF9830",name:"orange"'' ''{color:"#fab387",name:"orange"'' ] + [ ''{color:"#B877D9",name:"purple"'' ''{color:"#cba6f7",name:"purple"'' ] + + [ ''X=h==="kiosk";if(W||'' ''X=h==="kiosk";if(!0||'' ] + + [ ''["#7EB26D","#EAB839","#6ED0E0","#EF843C","#E24D42","#1F78C1","#BA43A9","#705DA0","#508642","#CCA300","#447EBC","#C15C17","#890F02","#0A437C"'' + ''["#cba6f7","#89b4fa","#a6e3a1","#fab387","#f5c2e7","#94e2d5","#f9e2af","#89dceb","#f38ba8","#b4befe","#f2cdcd","#eba0ac","#74c7ec","#f5e0dc"'' ] + ]; + esc = s: builtins.replaceStrings [ "\\" "/" "&" "[" "]" "." "*" "$" "^" ] [ "\\\\" "\\/" "\\&" "\\[" "\\]" "\\." "\\*" "\\$" "\\^" ] s; + escR = s: builtins.replaceStrings [ "\\" "/" "&" ] [ "\\\\" "\\/" "\\&" ] s; + script = pkgs.writeText "mocha.sed" (pkgs.lib.concatStrings (map (x: "s/${esc (builtins.elemAt x 0)}/${escR (builtins.elemAt x 1)}/g\n") swaps)); + patterns = pkgs.writeText "mocha.patterns" (pkgs.lib.concatStringsSep "\n" (map builtins.head swaps)); +in pkgs.runCommand "grafana-public-mocha" { nativeBuildInputs = [ pkgs.jq pkgs.openssl ]; } '' + cp -rs ${grafana}/share/grafana/public $out + chmod -R u+w $out + + rm -rf $out/app && cp -r ${grafana}/share/grafana/public/app $out/app + files=$(grep -RlF -f ${patterns} $out/build --include='*.js') + [ -n "$files" ] || { echo "mocha: no palette files found"; exit 1; } + for f in $files; do cp --remove-destination "$(readlink -f "$f")" "$f"; chmod u+w "$f"; sed -i -f ${script} "$f"; done + while IFS= read -r p; do + grep -RqF "$p" $out/build && { echo "mocha: unpatched: $p"; exit 1; } + grep -rqF "$p" ${grafana}/share/grafana/public/build || { echo "mocha: pattern gone upstream: $p"; exit 1; } + done < ${patterns} + + m=$out/build/assets-manifest.json + cp --remove-destination "$(readlink -f $m)" $m; chmod u+w $m + rt=$out/$(jq -r '."runtime.js".src | ltrimstr("public/")' $m) + cp --remove-destination "$(readlink -f $rt)" $rt; chmod u+w $rt + sha384() { echo "sha384-$(openssl dgst -sha384 -binary "$1" | base64 -w0)"; } + rename() { + local f=$1 old new + old=$(basename "$f"); new="''${old%.js}.mocha$(sha256sum "$f" | head -c 8).js" + mv "$f" "$out/build/$new"; rm -f "$f.map" + jq --arg o "public/build/$old" --arg n "public/build/$new" \ + --arg s "$(sha384 "$out/build/$new") sha512-$(openssl dgst -sha512 -binary "$out/build/$new" | base64 -w0)" \ + 'walk(if type == "object" and .src == $o then .src = $n | .integrity = $s + elif type == "string" and . == $o then $n else . end) + | with_entries(if .key == ($o | ltrimstr("public/build/")) then .key = ($n | ltrimstr("public/build/")) else . end)' \ + $m > $m.new && mv $m.new $m + grep -qF "$old" $m && { echo "mocha: $old still in manifest"; exit 1; } + echo "$new" + } + for f in $files; do + old=$(basename "$f") + if grep -qF "public/build/$old" $m; then rename "$f" >/dev/null; continue; fi + id=''${old%%.*}; hash=''${old#*.}; hash=''${hash%.js} + grep -qF "$id:\"$hash\"" $rt || { echo "mocha: $old neither in manifest nor runtime"; exit 1; } + new=$(rename "$f"); nh=''${new#*.}; nh=''${nh%.js} + sed -i "s/\([{,]\)$id:\"$hash\"/\1$id:\"$nh\"/; s#\([{,]\)$id:\"sha384-[^\"]*\"#\1$id:\"$(sha384 "$out/build/$new")\"#" $rt + grep -qF "$id:\"$nh\"" $rt || { echo "mocha: runtime map not updated for $old"; exit 1; } + done + rename "$rt" >/dev/null + + cp --remove-destination "$(readlink -f $out/views/index.html)" $out/views/index.html + chmod u+w $out/views/index.html + sed -i 's/#111217/#11111b/g; s/#181b1f/#1e1e2e/g' $out/views/index.html +'' diff --git a/modules/services/monitoring/_overview.nix b/modules/services/monitoring/_overview.nix new file mode 100644 index 0000000..f8c04d3 --- /dev/null +++ b/modules/services/monitoring/_overview.nix @@ -0,0 +1,217 @@ +{ lib }: let + ds = { type = "prometheus"; uid = "prometheus"; }; + h = ''instance=~"$host"''; + phys = ''device=~"en.*|wl.*|eth.*"''; + realfs = ''fstype=~"ext4|btrfs|xfs|zfs",mountpoint!~"/boot.*|/nix/store"''; + svc = e: ''label_replace(${e}, "svc", "$1", "instance", "https://([^.]+)[.].*")''; + + q = expr: legendFormat: { inherit expr legendFormat; datasource = ds; }; + qi = expr: { inherit expr; datasource = ds; instant = true; range = false; format = "table"; }; + refs = lib.imap0 (i: t: t // { refId = lib.elemAt [ "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" ] i; }); + + thresh = steps: { mode = "absolute"; steps = map (s: { color = s.c; value = s.v or null; }) steps; }; + pctThresh = thresh [ { c = "green"; } { c = "yellow"; v = 70; } { c = "red"; v = 90; } ]; + + panel = type: title: x: y: w: hh: targets: extra: lib.recursiveUpdate { + inherit type title; + datasource = ds; + gridPos = { inherit x y w; h = hh; }; + targets = refs targets; + } extra; + + ts = title: x: y: w: hh: unit: targets: extra: panel "timeseries" title x y w hh targets (lib.recursiveUpdate { + fieldConfig.defaults = { + inherit unit; + custom = { lineWidth = 1; fillOpacity = 12; showPoints = "never"; gradientMode = "opacity"; }; + }; + options = { + legend = { displayMode = "list"; placement = "bottom"; showLegend = true; }; + tooltip = { mode = "multi"; sort = "desc"; }; + }; + } extra); + + mirrored = suffix: { + fieldConfig.overrides = [{ + matcher = { id = "byRegexp"; options = ".* ${suffix}$"; }; + properties = [{ id = "custom.transform"; value = "negative-Y"; }]; + }]; + }; + + col = name: props: { matcher = { id = "byName"; options = name; }; properties = props; }; + gaugeCol = name: col name [ + { id = "unit"; value = "percent"; } { id = "min"; value = 0; } { id = "max"; value = 100; } + { id = "thresholds"; value = pctThresh; } + { id = "decimals"; value = 0; } + { id = "custom.width"; value = 58; } + { id = "custom.cellOptions"; value = { type = "color-text"; }; } + ]; + unitCol = name: unit: col name [ { id = "unit"; value = unit; } ]; + + table = title: x: y: w: hh: targets: names: overrides: sort: panel "table" title x y w hh targets { + options = { showHeader = true; cellHeight = "sm"; footer.show = false; sortBy = [ sort ]; }; + fieldConfig = { defaults.custom = { align = "auto"; cellOptions.type = "auto"; }; inherit overrides; }; + transformations = [ + { id = "merge"; options = { }; } + { id = "organize"; options = { + excludeByName = { Time = true; }; + renameByName = names; + }; } + ]; + }; + + row = title: y: { type = "row"; inherit title; collapsed = false; gridPos = { x = 0; inherit y; w = 24; h = 1; }; panels = [ ]; }; + + cpu = by: ''100 * (1 - avg by (${by}) (rate(node_cpu_seconds_total{mode="idle",${h}}[$__rate_interval])))''; + ram = ''100 * (1 - max by (instance) (node_memory_MemAvailable_bytes{${h}}) / max by (instance) (node_memory_MemTotal_bytes{${h}}))''; + + panels = [ + (table "Hosts" 0 0 13 7 [ + (qi ''time() - max by (instance) (max_over_time(node_time_seconds{${h}}[7d]))'') + (qi ''max by (instance) (time() - node_boot_time_seconds{${h}})'') + (qi ''100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle",${h}}[2m])))'') + (qi ram) + (qi ''max by (instance) (node_drm_gpu_busy_percent{${h}}) or max by (instance) (100 * nvidia_smi_utilization_gpu_ratio{${h}})'') + (qi ''100 * sum by (instance) (node_drm_memory_vram_used_bytes{${h}}) / sum by (instance) (node_drm_memory_vram_size_bytes{${h}}) or 100 * sum by (instance) (nvidia_smi_memory_used_bytes{${h}}) / sum by (instance) (nvidia_smi_memory_total_bytes{${h}})'') + (qi ''100 * max by (instance) (1 - node_filesystem_avail_bytes{${realfs},${h}} / node_filesystem_size_bytes{${realfs},${h}})'') + (qi ''sum by (instance) (rate(node_network_receive_bytes_total{${phys},${h}}[2m]))'') + (qi ''sum by (instance) (rate(node_network_transmit_bytes_total{${phys},${h}}[2m]))'') + ] { + instance = "Host"; "Value #A" = "Status"; "Value #B" = "Uptime"; "Value #C" = "CPU"; "Value #D" = "RAM"; + "Value #E" = "GPU"; "Value #F" = "VRAM"; "Value #G" = "Disk"; "Value #H" = "Net in"; "Value #I" = "Net out"; + } [ + (col "Status" [ + { id = "mappings"; value = [ + { type = "range"; options = { from = 0; to = 180; result = { text = "online"; color = "green"; index = 0; }; }; } + { type = "range"; options = { from = 180; to = 1.0e12; result = { text = "offline"; color = "red"; index = 1; }; }; } + ]; } + { id = "custom.cellOptions"; value = { type = "color-text"; }; } + { id = "custom.width"; value = 70; } + ]) + (col "Uptime" [ { id = "unit"; value = "dtdurations"; } { id = "custom.width"; value = 95; } ]) + (gaugeCol "CPU") (gaugeCol "RAM") (gaugeCol "GPU") (gaugeCol "VRAM") (gaugeCol "Disk") + (col "Net in" [ { id = "unit"; value = "Bps"; } { id = "custom.width"; value = 85; } ]) + (col "Net out" [ { id = "unit"; value = "Bps"; } { id = "custom.width"; value = 85; } ]) + (col "Host" [ { id = "custom.width"; value = 60; } ]) + ] { displayName = "Host"; desc = false; }) + + (panel "state-timeline" "Services" 13 0 11 7 [ + (q (svc ''avg by (instance) (probe_success{from=~"$host"})'') "{{svc}}") + ] { + options = { showValue = "never"; mergeValues = true; rowHeight = 0.85; alignValue = "left"; legend.showLegend = false; tooltip.mode = "single"; }; + fieldConfig.defaults = { + color.mode = "thresholds"; + mappings = [ + { type = "value"; options."1" = { text = "up"; color = "green"; index = 0; }; } + { type = "value"; options."0" = { text = "down"; color = "red"; index = 1; }; } + { type = "range"; options = { from = 0.01; to = 0.99; result = { text = "partly down"; color = "yellow"; index = 2; }; }; } + ]; + custom = { lineWidth = 0; fillOpacity = 85; }; + }; + }) + + (ts "CPU" 0 7 6 7 "percent" [ (q (cpu "instance") "{{instance}}") ] { fieldConfig.defaults = { min = 0; max = 100; }; }) + (ts "RAM" 6 7 6 7 "percent" [ (q ram "{{instance}}") ] { fieldConfig.defaults = { min = 0; max = 100; }; }) + (ts "GPU" 12 7 6 7 "percent" [ + (q ''node_drm_gpu_busy_percent{${h}}'' "{{instance}} {{card}}") + (q ''100 * nvidia_smi_utilization_gpu_ratio{${h}}'' "{{instance}} nvidia") + ] { fieldConfig.defaults = { min = 0; max = 100; }; }) + (ts "Network (physical)" 18 7 6 7 "Bps" [ + (q ''sum by (instance) (rate(node_network_receive_bytes_total{${phys},${h}}[$__rate_interval]))'' "{{instance}} in") + (q ''sum by (instance) (rate(node_network_transmit_bytes_total{${phys},${h}}[$__rate_interval]))'' "{{instance}} out") + ] (mirrored "out")) + + (panel "bargauge" "Disks" 0 14 8 10 [ + (q ''100 * (1 - node_filesystem_avail_bytes{${realfs},${h}} / node_filesystem_size_bytes{${realfs},${h}})'' "{{instance}} {{mountpoint}}" // { instant = true; }) + ] { + options = { orientation = "horizontal"; displayMode = "gradient"; showUnfilled = true; minVizHeight = 12; valueMode = "color"; namePlacement = "left"; text = { titleSize = 13; valueSize = 15; }; }; + fieldConfig.defaults = { unit = "percent"; min = 0; max = 100; thresholds = pctThresh; }; + }) + + (table "Service details" 8 14 16 10 [ + (qi (svc ''min by (instance) (probe_success{from=~"$host"})'')) + (qi (svc ''100 * avg by (instance) (avg_over_time(probe_success{from=~"$host"}[$__range]))'')) + (qi (svc ''avg by (instance) (probe_duration_seconds{from=~"$host"})'')) + (qi (svc ''min by (instance) ((probe_ssl_earliest_cert_expiry{from=~"$host"} - time()) / 86400)'')) + ] { + svc = "Service"; "Value #A" = "Now"; "Value #B" = "Uptime"; "Value #C" = "Response"; "Value #D" = "TLS days"; + } [ + (col "instance" [ { id = "custom.hidden"; value = true; } ]) + (col "Now" [ + { id = "mappings"; value = [ + { type = "value"; options."1" = { text = "up"; color = "green"; index = 0; }; } + { type = "value"; options."0" = { text = "down"; color = "red"; index = 1; }; } + ]; } + { id = "custom.cellOptions"; value = { type = "color-text"; }; } + ]) + (col "Uptime" [ + { id = "unit"; value = "percent"; } { id = "decimals"; value = 2; } + { id = "thresholds"; value = thresh [ { c = "red"; } { c = "yellow"; v = 95; } { c = "green"; v = 99.5; } ]; } + { id = "custom.cellOptions"; value = { type = "color-text"; }; } + ]) + (unitCol "Response" "s") + (col "TLS days" [ + { id = "decimals"; value = 0; } + { id = "thresholds"; value = thresh [ { c = "red"; } { c = "yellow"; v = 14; } { c = "green"; v = 30; } ]; } + { id = "custom.cellOptions"; value = { type = "color-text"; }; } + ]) + ] { displayName = "Uptime"; desc = false; }) + + (row "Processes (box)" 24) + (table "Top processes" 0 25 10 8 (let + top = ''topk(15, 100 * sum by (groupname) (rate(namedprocess_namegroup_cpu_seconds_total{instance="box"}[2m])))''; + in [ + (qi top) + (qi ''sum by (groupname) (namedprocess_namegroup_memory_bytes{instance="box",memtype="resident"}) and on (groupname) ${top}'') + (qi ''sum by (groupname) (namedprocess_namegroup_num_procs{instance="box"}) and on (groupname) ${top}'') + ]) { groupname = "Process"; "Value #A" = "CPU"; "Value #B" = "Memory"; "Value #C" = "Count"; } [ + (col "CPU" [ { id = "unit"; value = "percent"; } { id = "decimals"; value = 1; } ]) + (unitCol "Memory" "bytes") + ] { displayName = "CPU"; desc = true; }) + (ts "Process CPU (top 8)" 10 25 14 8 "percent" [ + (q ''topk(8, 100 * sum by (groupname) (rate(namedprocess_namegroup_cpu_seconds_total{instance="box"}[$__rate_interval])))'' "{{groupname}}") + ] { fieldConfig.defaults.custom = { stacking.mode = "normal"; fillOpacity = 40; }; }) + + (row "Details" 33) + (ts "Temperatures" 0 34 12 7 "celsius" [ + (q ''max by (instance, chip_name) (node_hwmon_temp_celsius{${h}} * on (instance, chip) group_left (chip_name) node_hwmon_chip_names{chip_name=~"k10temp|coretemp"})'' "{{instance}} cpu") + (q ''label_replace(max by (instance, chip) (node_hwmon_temp_celsius{${h}} * on (instance, chip) group_left (chip_name) node_hwmon_chip_names{chip_name="amdgpu"}), "pci", "$1", "chip", ".*_0000:([0-9a-f]+):.*")'' "{{instance}} gpu {{pci}}") + (q ''nvidia_smi_temperature_gpu{${h}}'' "{{instance}} gpu nvidia") + (q ''max by (instance, chip) (node_hwmon_temp_celsius{${h}} * on (instance, chip) group_left (chip_name) node_hwmon_chip_names{chip_name="nvme"})'' "{{instance}} {{chip}}") + ] { }) + (ts "Network per interface" 12 34 12 7 "Bps" [ + (q ''rate(node_network_receive_bytes_total{device!~"lo|veth.*",${h}}[$__rate_interval])'' "{{instance}} {{device}} in") + (q ''rate(node_network_transmit_bytes_total{device!~"lo|veth.*",${h}}[$__rate_interval])'' "{{instance}} {{device}} out") + ] (mirrored "out")) + (ts "Disk I/O" 0 41 8 7 "Bps" [ + (q ''sum by (instance, device) (rate(node_disk_read_bytes_total{device!~"loop.*|zram.*|dm-.*|sr.*",${h}}[$__rate_interval]))'' "{{instance}} {{device}} read") + (q ''sum by (instance, device) (rate(node_disk_written_bytes_total{device!~"loop.*|zram.*|dm-.*|sr.*",${h}}[$__rate_interval]))'' "{{instance}} {{device}} write") + ] (mirrored "write")) + (ts "Tunnel requests" 8 41 8 7 "reqps" [ + (q ''sum(rate(cloudflared_tunnel_total_requests[$__rate_interval]))'' "requests") + (q ''sum(rate(cloudflared_tunnel_request_errors[$__rate_interval]))'' "errors") + ] { }) + (ts "Tunnel responses by code" 16 41 8 7 "reqps" [ + (q ''sum by (status_code) (rate(cloudflared_tunnel_response_by_code[$__rate_interval]))'' "{{status_code}}") + ] { fieldConfig.defaults.custom = { stacking.mode = "normal"; fillOpacity = 40; }; }) + (ts "Load (1m)" 0 48 12 6 "short" [ (q ''node_load1{${h}}'' "{{instance}}") ] { }) + (ts "Swap / zram used" 12 48 12 6 "bytes" [ + (q ''node_memory_SwapTotal_bytes{${h}} - node_memory_SwapFree_bytes{${h}}'' "{{instance}}") + ] { }) + ]; +in { + uid = "overview"; + title = "Overview"; + editable = false; + graphTooltip = 1; + refresh = "30s"; + time = { from = "now-6h"; to = "now"; }; + timepicker.refresh_intervals = [ "30s" "1m" "5m" ]; + schemaVersion = 39; + templating.list = [{ + type = "query"; name = "host"; label = "Host"; datasource = ds; + query = { query = "label_values(node_uname_info, instance)"; refId = "host"; }; + includeAll = true; multi = true; refresh = 2; sort = 1; + current = { text = [ "All" ]; value = [ "$__all" ]; }; + }]; + panels = lib.imap1 (id: p: p // { inherit id; }) panels; +} diff --git a/modules/services/monitoring.nix b/modules/services/monitoring/default.nix similarity index 61% rename from modules/services/monitoring.nix rename to modules/services/monitoring/default.nix index 0aa2ed6..3652242 100644 --- a/modules/services/monitoring.nix +++ b/modules/services/monitoring/default.nix @@ -1,11 +1,7 @@ { - # Central monitoring on the server: Prometheus (30d, receives remote_write from the other hosts) + Grafana. - # monitor. = Grafana (anonymous read-only, admin = owner), metrics. = Prometheus (basic auth). - # Secrets in ~/.config/monitoring/ on the server: password (plain), web.yml (bcrypt of it for user "push"), - # grafana-secret (random). Dashboards from grafana.com, pinned by revision + hash. - den.aspects.services.monitoring = let grafanaPort = 3005; in { + den.aspects.services.monitoring = let grafanaPort = 3005; proxyPort = 3006; in { tunnel = [ - { subdomain = "monitor"; port = grafanaPort; } + { subdomain = "monitor"; port = proxyPort; } { subdomain = "metrics"; port = 9090; } ]; @@ -13,18 +9,7 @@ home = config.users.users.${host.owner}.home; secrets = "${home}/.config/monitoring"; cred = name: "$__file{/run/credentials/grafana.service/${name}}"; - dashboard = id: rev: hash: pkgs.fetchurl { - url = "https://grafana.com/api/dashboards/${toString id}/revisions/${toString rev}/download"; - inherit hash; - }; - dashboards = pkgs.runCommand "grafana-dashboards" { } '' - mkdir $out - for f in ${dashboard 1860 45 "sha256-GExrdAnzBtp1Ul13cvcZRbEM6iOtFrXXjEaY6g6lGYY="}:node \ - ${dashboard 7587 3 "sha256-zkA7uHjiLdJQd1t6qFIZE+YgF0EXfKlU+npPsd2Jj6w="}:uptime \ - ${dashboard 249 2 "sha256-fX+krJmDDSwC87Xoecy70vUnLdOQ8sKkXPppgQy/FVE="}:processes; do - sed -E 's/\$\{DS_[A-Za-z0-9_-]+\}/prometheus/g' "''${f%:*}" > "$out/''${f##*:}.json" - done - ''; + overview = pkgs.writeTextDir "overview.json" (builtins.toJSON (import ./_overview.nix { inherit lib; })); exp = config.services.prometheus.exporters; in { services.prometheus = { @@ -48,7 +33,6 @@ systemd.services.prometheus.serviceConfig.LoadCredential = [ "web.yml:${secrets}/web.yml" ]; - # cloudflared's own metrics (requests / errors per tunnel) systemd.services."cloudflared-tunnel-${host.cloudflared.uuid}".environment.TUNNEL_METRICS = "127.0.0.1:9300"; services.grafana = { @@ -60,6 +44,7 @@ http_port = grafanaPort; domain = "monitor.${host.domain}"; root_url = "https://monitor.${host.domain}"; + static_root_path = "${import ./_mocha.nix { inherit pkgs; grafana = config.services.grafana.package; }}"; }; security = { admin_user = host.owner; @@ -68,6 +53,14 @@ }; "auth.anonymous" = { enabled = true; org_role = "Viewer"; }; analytics.reporting_enabled = false; + dashboards.default_home_dashboard_path = "${overview}/overview.json"; + unified_alerting.enabled = false; + explore.enabled = false; + news.news_feed_enabled = false; + help.enabled = false; + profile.enabled = false; + public_dashboards.enabled = false; + users = { allow_sign_up = false; home_page = "/d/overview"; default_theme = "dark"; }; }; provision = { @@ -79,9 +72,32 @@ isDefault = true; basicAuth = true; basicAuthUser = "push"; + jsonData.timeInterval = "1m"; secureJsonData.basicAuthPassword = cred "pw"; }]; - dashboards.settings.providers = [{ name = "default"; options.path = dashboards; }]; + dashboards.settings.providers = [{ name = "default"; options.path = overview; }]; + }; + }; + + services.caddy = { + enable = true; + globalConfig = "auto_https off"; + virtualHosts."http://:${toString proxyPort}" = { + listenAddresses = [ "127.0.0.1" ]; + extraConfig = '' + @pin { + not header Cookie *grafana_session=* + not path /login* /logout* /api/* /apis/* /public/* /avatar/* /bootdata* /manifest.json /favicon.ico /d/overview* + } + @nokiosk { + not header Cookie *grafana_session=* + path /d/overview* + not query kiosk=* + } + redir @pin /d/overview?kiosk 302 + redir @nokiosk /d/overview?kiosk&{query} 302 + reverse_proxy 127.0.0.1:${toString grafanaPort} + ''; }; }; diff --git a/modules/system/monitoring.nix b/modules/system/monitoring.nix index 96bfca0..a138017 100644 --- a/modules/system/monitoring.nix +++ b/modules/system/monitoring.nix @@ -1,15 +1,13 @@ { inputs, ... }: { - # Every host: node + blackbox exporters scraped by a local Prometheus. - # Hosts without services.monitoring run it in agent mode and push to https://metrics. (basic auth "push", - # password in ~/.config/monitoring/password), buffering in the WAL while the server is unreachable. - # Uptime probes go to every http(s) tunnel hostname of the server, labelled with the probing host (`from`). den.aspects.system.monitoring = { nixos = { config, lib, host, ... }: let name = config.networking.hostName; home = config.users.users.${host.owner}.home; ingress = lib.foldl' (a: t: a // t.ingress) { } (lib.attrValues inputs.self.nixosConfigurations.box.config.services.cloudflared.tunnels); - targets = map (h: "https://${h}") (lib.attrNames (lib.filterAttrs (_: lib.hasPrefix "http") ingress)); + noProbe = [ "music" "monitor" "metrics" ]; + targets = map (h: "https://${h}") (lib.attrNames (lib.filterAttrs + (n: v: lib.hasPrefix "http" v && !lib.elem (lib.head (lib.splitString "." n)) noProbe) ingress)); nvidia = lib.elem "nvidia" config.services.xserver.videoDrivers; exp = config.services.prometheus.exporters; local = job: port: { @@ -21,13 +19,13 @@ enable = true; enableAgentMode = lib.mkDefault true; listenAddress = "127.0.0.1"; - checkConfig = "syntax-only"; # credential files only exist at runtime + checkConfig = "syntax-only"; exporters = { node = { enable = true; listenAddress = "127.0.0.1"; - enabledCollectors = [ "systemd" "drm" ]; # drm: amdgpu busy / vram + enabledCollectors = [ "systemd" "drm" ]; }; blackbox = { @@ -73,6 +71,8 @@ }]; }; + systemd.services.prometheus-node-exporter.serviceConfig.ProtectHome = lib.mkForce "read-only"; + systemd.services.prometheus.serviceConfig.LoadCredential = lib.mkIf config.services.prometheus.enableAgentMode [ "pw:${home}/.config/monitoring/password" ]; };