Files
nixos/configurations/server.nix
T
oqyude 2980a8e9e8 backup: суточные дампы PostgreSQL на архивный диск, владелец тома — postgres
Симптом (ревью 2026-11-29): `postgresqlBackup` был выключен
(закомментированная строка), то есть единственной защитой живой БД оставалось
rsync-зеркало на тот же диск — копия, снятая с работающих файлов.

Решение владельца 2026-12-03: «через postgresql бэкапы как дополнительная
мера, на этот же диск, куда делается rsync зеркало». Зеркало остаётся.

Правка:
- `services.postgresqlBackup`: `enable`, `location =
  "/mnt/archive/postgresql"`, `startAt = "*-*-* 03:20:00"` (не 00:00, чтобы
  не совпадать с `rsync-archivesta`, у которого `OnCalendar = "daily"`),
  `compression = "zstd"`;
- юнит `postgresqlBackup`: `ConditionPathIsMountPoint`/`RequiresMountsFor`
  на `/mnt/archive` — якорь `mkStorageGuard` переопределён с server-home на
  архивный том, чтобы дамп не ушёл в пустой каталог на корневой ФС;
- `configurations/server.nix`: том `archive` монтируется с
  `ownerUid/ownerGid` пользователя postgres; `lib/xlib/helpers.nix:
  mkExfatMount` получил необязательные `ownerUid`/`ownerGid` (по умолчанию
  прежние uid/gid, остальные тома не меняются).

Почему владелец тома, а не права на каталог: exFAT не хранит uid/gid, они
задаются только опцией монтирования и действуют на все inode; `chmod`/
`chown` на exFAT молча возвращают 0 и ничего не меняют. Сервис работает под
пользователем `postgres` (так задано в модуле nixpkgs), поэтому при
`uid=1000` он не может ни создать каталог, ни открыть файл на запись.
Проверено на тестовом exFAT-образе (loop, mkfs.exfat): при uid/gid=postgres
каталог и дамп создаются, при uid=1000 — EACCES; `chown`/`chmod` на образе —
rc=0 без эффекта. Root (rsync-зеркало) от владельца тома не зависит.

Проверено (nix eval, sapphira):
- `services.postgresqlBackup` → `{enable:true, location:"/mnt/archive/postgresql",
  startAt:"*-*-* 03:20:00", compression:"zstd", backupAll:true}`;
- `systemd.services.postgresqlBackup` → `User=postgres`,
  `ConditionPathIsMountPoint=["/mnt/archive"]`,
  `RequiresMountsFor=["/mnt/archive"]`;
- `fileSystems."/mnt/archive".options` → `["nofail" "uid=71" "gid=71"
  "noauto" "x-systemd.automount"]`.
2026-12-03 15:31:45 +03:00

200 lines
8.8 KiB
Nix
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Host: "sapphira" (device: server)
#
# The host record lives in configurations/default.nix; this file is only the
# module body. `xlib` (identity, dirs, helpers) arrives as a module argument.
{
config,
lib,
pkgs,
xlib,
inputs,
...
}:
{
imports = [
./hardware/server.nix
inputs.self.nixosModules.default
];
boot = {
# kernelPackages = pkgs.linuxPackages_xanmod_stable;
hardwareScan = true;
loader = {
systemd-boot.enable = lib.mkDefault true;
efi.canTouchEfiVariables = lib.mkDefault true;
};
};
hardware = {
bluetooth.enable = true;
graphics = {
enable = true;
extraPackages = with pkgs; [
intel-media-driver
intel-ocl
intel-vaapi-driver
];
};
intel-gpu-tools.enable = true;
};
fileSystems =
(xlib.helpers.mkExfatMount {
path = xlib.dirs.archive-drive;
label = "archive";
# Том `archive` (exfat, 466 ГБ, диск sda) НЕ нужен на пути загрузки:
# его не держит ни один юнит, `lsof +f -- /mnt/archive` пуст, нужен
# «когда понадобится».
#
# ЗАМЕР 2026-11-24 (после обрыва питания): проверка ФС этого тома
# занимала 7 мин 15 с на КАЖДОЙ загрузке — «Starting File System Check
# on /dev/disk/by-label/archive… 19:06:18» → «Finished … 19:13:33», и
# `systemd-analyze` показывал userspace 7min 13s, из них 7min 7s —
# systemd-fsck@dev-disk-by\x2dlabel-archive.service.
#
# Поэтому: noauto + x-systemd.automount. Проверка ФС НЕ отключается
# (noCheck не добавляем!) — она выполняется при ПЕРВОМ обращении к
# /mnt/archive (её поднимает automount), а не на пути загрузки.
# `mobile` ниже намеренно остаётся как есть: он грузится как раньше.
options = [
"noauto"
"x-systemd.automount"
];
# Владелец тома — postgres: с 2026-12-03 на этот диск пишутся дампы
# `postgresqlBackup` (modules/server/postgresql.nix), а сервис работает
# под пользователем postgres и на exFAT не может писать в каталоги,
# принадлежащие uid=1000 (права там задаются только при монтировании).
# Проверено на тестовом exFAT-образе: при uid/gid=postgres юнит создаёт
# каталог и пишет дамп; при uid=1000 — EACCES.
ownerUid = config.users.users.postgres.uid;
ownerGid = config.users.groups.postgres.gid;
})
// (xlib.helpers.mkExfatMount {
path = xlib.dirs.mobile-drive;
uuid = "7EB1-DC99";
})
// (xlib.helpers.mkBindMount {
what = xlib.dirs.services-folder;
where = xlib.dirs.services-mnt-folder;
})
// {
# External drive
"${xlib.dirs.server-home}" = {
device = "/dev/disk/by-uuid/37e53ebc-5343-a94d-9fe2-0ca39e13a8de";
fsType = "ext4";
};
};
systemd.tmpfiles.rules = [
"z ${xlib.dirs.services-mnt-folder} 0777 root root -"
];
host.ssh.enable = true;
# Daily closure prebuild on a 2-core / 5.6 GiB box that also hosts CI and
# every service. On rydiwo this exact unit was OOM-killed before the
# host-scoped `MemoryMax = "6G"` (configurations/mini-laptop.nix:126).
# Owner decision 2026-11-27: 2G on sapphira. A killed prebuild is harmless
# (the next run resumes from /nix/store) and cannot push the host into swap.
systemd.services.nixos-prebuild.serviceConfig.MemoryMax = "2G";
# PowerShell — хостовый инструмент, а не пользовательский.
#
# Зачем: на sapphira живёт `metaagent-director`, у которого есть вторая
# реализация на PowerShell (`director.ps1`) и ps1-набор тестов. Без `pwsh`
# в системном PATH эти тесты на данном хосте всегда уходят в skip, то есть
# ps1-ветка проверяется только чтением. `pwsh` становится доступен всем
# сессиям (директор, воркеры, CI-джобы) без `nix shell`.
#
# Почему здесь, а не в `modules/essentials/packages.nix`: тот список —
# общий для ВСЕХ NixOS-хостов флейка, включая 1-vCPU vds `otreca`; тащить
# туда .NET-рантайм ради одного сервера незачем. `configurations/server.nix`
# импортируется ровно одной записью реестра (`sapphira`, см.
# `configurations/default.nix`), поэтому правка не меняет ни один другой хост.
# `pkgs.powershell` — это nixpkgs-атрибут 7.x (7.6.6 на текущем пине).
environment.systemPackages = [ pkgs.powershell ];
# Offload Nix builds to the WSL2 NixOS instance running on vetymae
# (Windows 11 host). Sapphira only has 2 logical cores; the WSL exposes
# 24 cores + 14 GiB. The matchBlock with ProxyCommand is generated by
# modules/server/builder.nix, the other side of the same option lives in
# modules/wsl/builder.nix.
#
# `proxyCommand` is what marks this builder as needing the SSH matchBlock
# (see modules/server/builder.nix). A builder reachable directly would
# omit it.
#
# ---- DISABLED 2026-10-04 ----
# Remote building temporarily turned off coordinator-side. `host.builder.clients`
# falls back to its default `[]` (declared in modules/options.nix), so
# modules/server/builder.nix's `lib.mkIf (clients != [])` never fires and no
# buildMachines / SSH blocks / distributedBuilds override get generated.
# All builds run locally on sapphira's 2 cores. Re-enable by removing the
# Nix comments on the block below (and on `host.builder.enable = true;`
# in configurations/wsl.nix).
#
# host.builder.clients = [
# {
# hostName = "vetymae-nix";
# sshUser = "oqyude";
# sshKey = "/root/.ssh/id_ed25519";
# # NixOS calls this `systems` (plural), not `systemTypes`. The
# # default is empty — every derivation is rejected. The WSL NixOS
# # runs on x86_64-linux, matching sapphira.
# systems = [ "x86_64-linux" ];
# # vetymae-nix drops kvm + nixos-test from its advertised
# # system-features (see modules/wsl/builder.nix). Listing them here
# # would not break anything (Nix intersects), but listing the
# # features the WSL actually has is the documented contract.
# supportedFeatures = [
# "benchmark"
# "big-parallel"
# ];
# mandatoryFeatures = [ ];
# maxJobs = 24;
# speedFactor = 0.5;
# # Keep the SSH session alive across many small builds in one daemon
# # session — compile-heavy workloads spam the daemon with hundreds of
# # derivations and ControlMaster collapses those into one Windows hop.
# # NB: `nix.buildMachines` has no `sshOptions` attribute, so the
# # ControlMaster directive lives in the SSH matchBlock instead (see
# # modules/server/builder.nix).
# #
# # The OpenSSH alias for this host (matches the user's
# # ~/.ssh/config so known_hosts entries do not collide with the
# # Windows OpenSSH entry on 127.0.0.1/vetymae) is consumed only by
# # the SSH matchBlock below — not by `nix.buildMachines`, which has
# # no such attribute.
# hostKeyAlias = "wsl-nixos-on-vetymae";
# # Use the Windows host's IP directly so the nix-daemon (running as
# # root, without the user's ~/.ssh/config) does not need a separate
# # `vetymae` host alias. With StrictHostKeyChecking=accept-new the
# # first connection adds the Windows host key to /root/.ssh/known_hosts.
# proxyCommand = "ssh oqyude@192.168.1.100 'wsl -d NixOS -- nc 127.0.0.1 22'";
# }
# ];
networking = {
networkmanager.enable = true;
firewall.enable = false;
# nameservers = [
# "192.168.1.1"
# "127.0.0.1"
# ];
};
# engipy frontend on sapphira: nginx vhost + Authelia forward-auth +
# tmpfiles для /var/lib/engipy/web. Backend крутится на rydiwo
# (см. configurations/mini-laptop.nix).
host.engipy-frontend = {
enable = true;
# По умолчанию — LAN-адрес rydiwo из реестра флота (lib/xlib/net.nix).
# Если rydiwo переедет на другой адрес — менять нужно там, а не здесь.
backendHost = xlib.net.hosts.rydiwo.lan;
};
system = {
stateVersion = "25.05";
};
}