summaryrefslogtreecommitdiffstats
path: root/krops.nix
blob: 81320d08a5333ea13502ef9026ef62d37bcc36bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# NAME
#   krops.nix - deployment entry point
#
# SYNOPSIS
#   $(nix-build krops.nix --no-out-link --argstr name HOSTNAME -A ACTION)
#
# ACTIONS
#   deploy  build the system on the target and switch to it
#   diff    build the system on the target and show what switching to it
#           would change
#   bootimg build the boot image (spec.nix's bootimg, an attribute of the
#           host's nixosConfigurations entry) on a builder, and copy it to
#           $HOST_CACHEDIR/results/HOSTNAME.bootimg
#   fastboot.boot
#           build the boot image, and start it once
#   fastboot.flash
#           build the boot image, write it to the active slot, and reboot
#
# ARGUMENTS
#   name    the host to deploy
#   target  where to deploy it, instead of spec.nix's target
#   switch  what switch-to-configuration does: switch (the default), boot,
#           or test (no new generation)
#
# REMOTE BUILDS
#   A host whose spec.nix lists builders (targets like populate's,
#   [USER@]HOST[:PORT]/PATH, e.g. [ "tv@zu.r/home/tv/tmp/cache/hrm/roots" ])
#   gets evaluated on the deploying host, as on the target: from sources
#   populated into $HOST_CACHEDIR/src/HOSTNAME (default: ~/tmp/cache/hrm;
#   git sources as shallow clones, but for those this host has a checkout
#   of, of the same name at the same revision), which the evaluation sees
#   at the target's path, with those checkouts (mounted, by bubblewrap),
#   and built on the first builder that answers.  While deploying, the
#   builder keeps a GC root in PATH/HOSTNAME (as the user it's logged in
#   as, not necessarily root) and copies the system to the target
#   (or, with copyVia = "deployer", the deploying host copies it from the
#   builder).
#   The target gets only its secrets, and activates.  A record of each such
#   build goes to $PORTABLE_CACHEDIR/builds.jsonl (default:
#   ~/shared-tmp/cache/hrm), the evaluated derivation's GC root to
#   $HOST_CACHEDIR/roots/HOSTNAME.drv.
#
{ lib ? import ~/sync/src/krops/lib
, pkgs ? import ~/sync/src/krops/pkgs {}
, name
, target ? null
, switch ? "switch"
}@args:

assert builtins.elem switch [ "switch" "boot" "test" ];

rec {

  spec = {
    nixpkgs = "nixos-26.05";
    target = "root@${name}.r/var/src";
    builders = [];
    copyVia = "builder";
    targetStore = "ssh-ng";
  } // import ./systems/${name}/spec.nix;

  target = if args.target or null != null then args.target else spec.target;

  sources = {
    hrm.file = {
      path = toString ~/sync/src/hrm;
    };
    mobile-nixos.git = {
      ref = "406cd664f093a4ed7aab66274fe284b364e44547";
      url = "https://github.com/4z3/mobile-nixos";
    };
    nixos-config.symlink = {
      target = "hrm/systems/${name}/config.nix";
    };
    nixpkgs.git = {
      ref = (lib.importJSON ./nixpkgs.json).${spec.nixpkgs}.rev;
      url = "https://github.com/NixOS/nixpkgs";
    };
    # Hosts without secrets get no secrets source.
    secrets.passage = lib.optionalSource (builtins.pathExists ~/sync/secrets/${name}) {
      age = "${pkgs.rage}/bin/rage";
      dir = toString ~/sync/secrets/${name};
      identities_file = toString ~/.passage/identities;
    };
    stockholm.file = {
      path = toString ~/sync/src/stockholm;
    };
    # At the revision of pkgs/rust/tincr, for its NixOS module.
    tincr.git = {
      ref = (import ./pkgs/rust/tincr {
        fetchFromGitHub = lib.id;
        installShellFiles = null;
        runCommand = null;
      }).src.rev;
      url = "https://github.com/Mic92/tincr";
    };
  };

  source = lib.evalSource [ sources ];

  # What a host with builders gets on the target, which it needs at run
  # time: the sources named secrets*.  Everything else is for evaluation.
  targetSources =
    lib.filterAttrs (name: _: lib.hasPrefix "secrets" name) sources;

  deploy = hrm.legacy.deploy;
  diff = hrm.legacy.diff;

  hrm.legacy.deploy = mkAction "legacy" "deploy";
  hrm.legacy.diff = mkAction "legacy" "diff";
  hrm.flake.deploy = mkAction "flake" "deploy";
  hrm.flake.diff = mkAction "flake" "diff";

  bootimg = mkBootimgAction "bootimg";
  fastboot.boot = mkBootimgAction "fastboot.boot";
  fastboot.flash = mkBootimgAction "fastboot.flash";

  mkBootimgAction = action:
    assert lib.assertMsg (spec.builders != [])
      "${name}: ${action} needs a builder";
    assert lib.assertMsg (spec ? bootimg)
      "${name}: spec.nix doesn't say where the boot image is (bootimg)";
    pkgs.writers.writeDash "${name}-${action}" (remoteBuildScript action);

  mkAction = build-method: deploy-action:
    if spec.builders == [] then
      mkTargetBuildAction build-method deploy-action
    else
      assert build-method == "legacy";
      pkgs.writers.writeDash "${name}-deploy-remote-${deploy-action}"
        (remoteBuildScript deploy-action);

  mkTargetBuildAction = build-method: deploy-action: let
    target' = lib.mkTarget target;
    name' = "${name}-deploy-${build-method}-${deploy-action}";
  in
    pkgs.writers.writeDash name' /* sh */ ''
      set -efu
      ${pkgs.populate { source = source; target = target'; }}
      ${pkgs.krops.runShell target' { allocateTTY = true; } /* sh */ ''
        set -efu
        system=$(
          export NIX_PATH=${lib.escapeShellArg target'.path}
          ${builtins.getAttr build-method {
            legacy = /* sh */ ''
              nix-build \
                  -j 1 \
                  --show-trace \
                  --attr nixosConfigurations.${name}.config.system.build.toplevel \
                  '<hrm/legacy.nix>'
            '';
            flake = /* sh */ ''
              nix build \
                  --print-build-logs \
                  --show-trace \
                  --print-out-paths \
                  "$NIX_PATH"/hrm#nixosConfigurations.${name}.config.system.build.toplevel
            '';
          }}
        )
        ${builtins.getAttr deploy-action {
          deploy = let
            setAndSwitch = /* sh */ ''
              old_gen=$(readlink -f /nix/var/nix/profiles/system)
              new_gen=$(readlink -f "$system")
              if [ "x$old_gen" != "x$new_gen" ]; then
                nix-env -p /nix/var/nix/profiles/system --set "$system"
                "$system"/bin/switch-to-configuration ${switch}
              else
                echo 'Configuration is already up to date' >&2
              fi
            '';
          in builtins.getAttr switch {
            switch = setAndSwitch;
            boot = setAndSwitch;
            test = /* sh */ ''
              "$system"/bin/switch-to-configuration test
            '';
          };
          diff = /* sh */ ''
            nix --extra-experimental-features nix-command \
                store diff-closures /run/current-system "$system"
            if command -v nix-diff >/dev/null; then
              nix-diff --environment --skip-already-compared /run/current-system "$system"
            else
              NIX_PATH=${lib.escapeShellArg target'.path} \
              nix-shell -p nix-diff --run \
                  "nix-diff --environment --skip-already-compared /run/current-system $system"
            fi
            "$system"/bin/switch-to-configuration dry-activate
          '';
        }}
      ''}
    '';

  # The script of an action for a host with builders.  Its own attribute,
  # so its text can be checked without building it.
  remoteBuildScript = action: let
    # What gets built, and what its GC roots are called.
    build = let
      system = {
        attr = "config.system.build.toplevel";
        root = name;
      };
      bootimg = {
        attr = spec.bootimg;
        root = "${name}.bootimg";
      };
    in builtins.getAttr action {
      deploy = system;
      diff = system;
      inherit bootimg;
      "fastboot.boot" = bootimg;
      "fastboot.flash" = bootimg;
    };
    target' = lib.mkTarget target;
    q = lib.escapeShellArg;
    nix = "nix --extra-experimental-features nix-command";
    jq = "${pkgs.jq}/bin/jq";
    # A port is digits, so it needs no quoting in ssh's options.
    sshOptsOf = s: t:
      assert lib.assertMsg (t.port == null || lib.match "[0-9]+" t.port != null)
        "${name}: ${s}: port ${t.port} isn't a number";
      lib.optionalString (t.port != null) "-p ${t.port}";
    targetDest =
      lib.optionalString (target'.user != null) "${target'.user}@" + target'.host;
    targetSSHOpts = sshOptsOf target target';
    targetURL = "${spec.targetStore}://${targetDest}";
    # The builders, as targets like populate's, [USER@]HOST[:PORT]/PATH:
    # PATH is where a builder keeps the GC roots of the systems it builds,
    # while deploying them.
    builders = map (s: let
      t = lib.mkTarget s;
    in
      assert lib.assertMsg (lib.hasInfix "/" s)
        "${name}: builder ${s} needs a path for its GC roots";
      assert lib.assertMsg
        (spec.copyVia != "deployer" || t.port == null || target'.port == null)
        "${name}: copyVia = \"deployer\" can't use ports for both ${s} and the target";
    {
      dest = lib.optionalString (t.user != null) "${t.user}@" + t.host;
      sshOpts = sshOptsOf s t;
      inherit (t) path;
    }) spec.builders;
    targetSource = lib.evalSource [ targetSources ];
    # Sources for evaluating here, in a directory of this host, populated as
    # onto a target: everything but targetSources and mountSources.
    hostCache = let
      dir = builtins.getEnv "HOST_CACHEDIR";
    in if dir != "" then dir else toString ~/tmp/cache/hrm;
    evalTarget = lib.mkTarget "${hostCache}/src/${name}";
    # The revision of a checkout: its Git HEAD, or nixpkgs' .git-revision.
    revisionOf = path: let
      git = "${path}/.git";
      revisionFile = "${path}/.git-revision";
    in
      if lib.pathIsGitRepo git then lib.commitIdFromGitRepo git
      else if builtins.pathExists revisionFile then lib.fileContents revisionFile
      else null;
    # This host's <NAME>, if it's at revision REV.
    hereAt = name: rev: let
      found = builtins.tryEval (builtins.findFile builtins.nixPath name);
    in
      if found.success && revisionOf (toString found.value) == rev
      then toString found.value
      else null;
    # The Git sources this host has a checkout of at the same revision, by
    # name: the evaluation gets them mounted.
    mountSources = lib.filterAttrs (_: path: path != null)
      (lib.mapAttrs
        (name: source:
          if source.git or null != null
          then hereAt name source.git.ref
          else null)
        (removeAttrs sources (lib.attrNames targetSources)));
    # The rest gets populated, Git sources as shallow clones until populate
    # shares Git objects.
    evalSource = lib.evalSource [
      (lib.mapAttrs (name: source:
        if source.git or null != null
        then { git = source.git // { shallow = true; }; }
        else source
      ) (removeAttrs sources
        (lib.attrNames targetSources ++ lib.attrNames mountSources)))
    ];
    # Runs SCRIPT on the target, with the system's store path on standard
    # input (read -r system).
    onTarget = script: /* sh */ ''
      printf '%s\n' "$system" |
      ${pkgs.krops.runShell target' {} /* sh */ ''
        set -efu
        read -r system
        ${script}
      ''}
    '';
  in /* sh */ ''
    set -efu

    name=${q name}
    portable_cache=''${PORTABLE_CACHEDIR:-$HOME/shared-tmp/cache/hrm}
    host_cache=''${HOST_CACHEDIR:-$HOME/tmp/cache/hrm}
    mkdir -p "$portable_cache" "$host_cache"/roots

    #
    # Sources for evaluating here.  targetSources and mountSources get
    # empty directories: the former so that evaluation finds where they
    # are, but nothing in them, the latter as mount points.
    #
    eval_dir=${q evalTarget.path}
    ${pkgs.populate { source = evalSource; target = evalTarget; force = true; }}
    for source in ${lib.escapeShellArgs
        (lib.attrNames targetSources ++ lib.attrNames mountSources)}; do
      if test -L "$eval_dir/$source"; then
        rm "$eval_dir/$source"
      fi
      mkdir -p "$eval_dir/$source"
    done

    #
    # Choose the first builder that answers, and note its state.
    #
    builder_probe='printf "%s %s %s %s %s\n" "$(cut -d" " -f1 /proc/loadavg)" "$(nproc)" \
        "$(awk "/^MemAvailable:/{print \$2*1024}" /proc/meminfo)" \
        "$(df -B1 --output=avail /nix | tail -n 1)" \
        "$(nix-instantiate --eval --json -E builtins.currentSystem | tr -d \")"'
    builder=
    ${lib.concatMapStrings (b: /* sh */ ''
      if test -z "$builder"; then
        if builder_state=$(ssh -o BatchMode=yes -o ConnectTimeout=5 \
            ${b.sshOpts} ${q b.dest} "$builder_probe")
        then
          # *_quoted are quoted for the builder's shell, which parses the
          # commands ssh passes it.
          builder=${q b.dest} builder_ssh_opts=${q b.sshOpts} \
              builder_roots_quoted=${q (q b.path)} \
              builder_root_quoted=${q (q "${b.path}/${build.root}")}
        else
          echo "$name: builder "${q b.dest}" doesn't answer" >&2
        fi
      fi
    '') builders}
    if test -z "$builder"; then
      echo "$name: error: no builder answers: "${q (toString spec.builders)} >&2
      exit 1
    fi
    set -- $builder_state
    builder_load=$1 builder_cpus=$2 builder_mem=$3 builder_disk=$4
    builder_system=$5

    #
    # Evaluate here, with the sources mounted where the target has them, so
    # that it evaluates as on the target.  Keep the derivation for diff.
    #
    if ! test -d ${q target'.path}; then
      echo "$name: error: no "${q target'.path}" here to mount the sources at" >&2
      exit 1
    fi
    echo "$name: evaluating..." >&2
    drv=$(${pkgs.bubblewrap}/bin/bwrap \
        --dev-bind / / \
        --bind "$eval_dir" ${q target'.path} \
        ${lib.concatStrings (lib.mapAttrsToList (name: path:
          "--ro-bind ${q path} ${q "${target'.path}/${name}"} "
        ) mountSources)}\
        --setenv NIX_PATH ${q target'.path} \
        nix-instantiate \
            --show-trace \
            --add-root "$host_cache"/roots/${q build.root}.drv \
            --argstr buildSystem "$builder_system" \
            --attr nixosConfigurations."$name".${q build.attr} \
            '<hrm/legacy.nix>')
    # nix-instantiate prints the GC root, a link to the derivation here.
    drv=$(readlink -f -- "$drv")

    #
    # Build on the builder, into its store, with a GC root there for as
    # long as this script runs, so the system stays until it's copied.
    #
    echo "$name: building on $builder..." >&2
    build_start=$(date +%s)
    NIX_SSHOPTS=$builder_ssh_opts \
    ${nix} copy --no-check-sigs --derivation --to ssh-ng://"$builder" "$drv"
    trap 'ssh $builder_ssh_opts "$builder" "rm -f -- $builder_root_quoted"' EXIT
    trap 'exit 1' INT TERM
    system=$(ssh $builder_ssh_opts "$builder" "mkdir -p -- $builder_roots_quoted &&
        nix-store --realise $drv --add-root $builder_root_quoted >/dev/null &&
        readlink -- $builder_root_quoted")
    build_end=$(date +%s)

  '' + builtins.getAttr action rec {
    diff = deploy;
    bootimg = /* sh */ ''
      #
      # Fetch the boot image, a file, and keep it.  Not into this host's
      # store, which would want a signature, or a trusted user.
      #
      echo "$name: copying from $builder to this host..." >&2
      bootimg="$host_cache"/results/${q build.root}
      mkdir -p "$host_cache"/results
      ssh $builder_ssh_opts "$builder" "cat $system" > "$bootimg".tmp
      mv -f "$bootimg".tmp "$bootimg"
      echo "$bootimg"
    '';
    "fastboot.boot" = bootimg + /* sh */ ''
      ${pkgs.android-tools}/bin/fastboot boot "$bootimg"
    '';
    "fastboot.flash" = bootimg + /* sh */ ''
      ${pkgs.android-tools}/bin/fastboot flash boot "$bootimg"
      ${pkgs.android-tools}/bin/fastboot reboot ||
          echo "$name: flashed, but the reboot failed; reboot the device yourself" >&2
    '';
    deploy = /* sh */ ''
      #
      # Copy the system to the target.
      #
      copy_start=$(date +%s)
      ${if spec.copyVia == "deployer" then /* sh */ ''
        echo "$name: copying from $builder via this host..." >&2
        NIX_SSHOPTS=${q targetSSHOpts} \
        ${nix} copy --no-check-sigs \
            --from ssh-ng://"$builder" --to ${q targetURL} "$system"
      '' else /* sh */ ''
        if ! check=$(ssh $builder_ssh_opts "$builder" ${q /* sh */
            "ssh -o BatchMode=yes -o ConnectTimeout=10 ${targetSSHOpts} ${q targetDest} true"
            } 2>&1)
        then
          echo "$name: error: $builder can't log in to "${q targetDest}":" >&2
          printf '%s\n' "$check" >&2
          case $check in
            *'Host key verification failed'*)
              echo "$name: $builder doesn't know the target's host key; add it" \
                  "to $builder's known hosts (e.g. programs.ssh.knownHosts)." >&2
              ;;
            *'Permission denied'*)
              echo "$name: the target doesn't accept $builder's key; add it to" \
                  "the target's authorized keys:" >&2
              ssh $builder_ssh_opts "$builder" 'cat ~/.ssh/id_*.pub' >&2 || :
              ;;
            *)
              echo "$name: check the network between $builder and the target." >&2
              ;;
          esac
          exit 1
        fi
        echo "$name: copying from $builder..." >&2
        ssh $builder_ssh_opts "$builder" ${q /* sh */
            "NIX_SSHOPTS=${q targetSSHOpts} ${nix} copy --no-check-sigs --to ${q targetURL} "
            }"$system"
      ''}
      copy_end=$(date +%s)

      #
      # Note what happened, for choosing builders later.
      #
      closure_size=$(NIX_SSHOPTS=$builder_ssh_opts \
          ${nix} path-info --store ssh-ng://"$builder" -S "$system" | cut -f2)
      ${jq} -nc \
          --arg host "$name" --arg action ${q action} \
          --arg deployer "$(cat /etc/hostname)" --arg builder "$builder" \
          --arg system "$system" --arg via ${q spec.copyVia} \
          --argjson build_start "$build_start" --argjson build_end "$build_end" \
          --argjson copy_start "$copy_start" --argjson copy_end "$copy_end" \
          --argjson closure_size "$closure_size" \
          --argjson builder_load "$builder_load" --argjson builder_cpus "$builder_cpus" \
          --argjson builder_mem "$builder_mem" --argjson builder_disk "$builder_disk" \
          '$ARGS.named' >> "$portable_cache"/builds.jsonl

      ${builtins.getAttr action {
        deploy = let
          setAndSwitch = /* sh */ ''
            old_gen=$(readlink -f /nix/var/nix/profiles/system)
            new_gen=$(readlink -f "$system")
            if [ "x$old_gen" != "x$new_gen" ]; then
              nix-env -p /nix/var/nix/profiles/system --set "$system"
              systemd-run --pipe --wait --collect --quiet \
                  "$system"/bin/switch-to-configuration ${switch}
            else
              echo 'Configuration is already up to date' >&2
            fi
          '';
        in /* sh */ ''
          # Without prune: the rest of the target's /var/src stays.
          ${pkgs.populate { source = targetSource; target = target'; }}
          ${onTarget (builtins.getAttr switch {
            switch = setAndSwitch;
            boot = setAndSwitch;
            test = /* sh */ ''
              systemd-run --pipe --wait --collect --quiet \
                  "$system"/bin/switch-to-configuration test
            '';
          })}
        '';
        diff = /* sh */ ''
          old_drv=$(${onTarget /* sh */ ''
            nix-store --query --deriver "$(readlink -f /run/current-system)"
          ''})
          if nix-store --check-validity "$old_drv" 2>/dev/null; then
            ${pkgs.nix-diff}/bin/nix-diff --environment --skip-already-compared \
                "$old_drv" "$drv"
          else
            echo "$name: no nix-diff: the running system's derivation isn't" \
                "here ($old_drv)" >&2
          fi
          ${onTarget /* sh */ ''
            ${nix} store diff-closures /run/current-system "$system"
            "$system"/bin/switch-to-configuration dry-activate
          ''}
        '';
      }}
    '';
  };
}