summaryrefslogtreecommitdiff
path: root/openwrt/default.nix
blob: 4bd00fb193cf0dec6766dcdc5cd5fcc27ca7b7ae (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
{ config, lib, pkgs, ... }:

let
  cfg = config.openwrt;

  devType = lib.types.submoduleWith {
    specialArgs.pkgs = pkgs;
    modules = [({ name, config, ... }: {
      options = {
        deploy = {
          host = lib.mkOption {
            type = lib.types.str;
            default = name;
          };

          user = lib.mkOption {
            type = lib.types.str;
            default = "root";
            visible = false;
            description = ''
              User name for SSH connections. Doesn't currently to anything useful considering
              that we don't have any kind of `useSudo` option.
            '';
          };

          sshConfig = lib.mkOption {
            type = with lib.types; attrsOf (oneOf [ str int bool path ]);
            default = {};
            description = ''
              SSH options to apply to connections, see {manpage}`ssh_config(5)`.
              Notably these are *not* command-line arguments, although they *will*
              be passed as `-o...` arguments.
            '';
          };

          rebootAllowance = lib.mkOption {
            type = lib.types.ints.unsigned;
            default = 60;
            description = ''
              How long to wait (in seconds) for the device to come back up.
              The timer runs on the deploying host and starts when the device reboots.
            '';
          };

          rollbackTimeout = lib.mkOption {
            type = lib.types.ints.unsigned;
            default = 60;
            description = ''
              How long to wait (in seconds) before rolling back to the old configuration.
              The timer runs on the device and starts once the device has completed its boot cycle.

              ::: {.warning}
              Values under `20` will very likely cause spurious rollbacks.
              :::
            '';
          };
        };

        build = lib.mkOption {
          type = lib.types.attrsOf lib.types.unspecified;
          internal = true;
        };

        deploySteps = lib.mkOption {
          type = lib.types.attrsOf (lib.types.submodule ({ name, ... }: {
            options = {
              name = lib.mkOption { type = lib.types.str; default = name; };
              priority = lib.mkOption { type = lib.types.int; };

              prepare = lib.mkOption { type = lib.types.lines; default = ""; };
              copy = lib.mkOption { type = lib.types.lines; default = ""; };
              apply = lib.mkOption { type = lib.types.lines; };
            };
          }));
          internal = true;
          default = {};
        };
      };

      imports = [
        ./etc.nix
        ./packages.nix
        ./uci.nix
        ./users.nix
      ];

      config = {
        build.deploy =
          let
            steps = lib.sort (a: b: a.priority < b.priority) (lib.attrValues config.deploySteps);
            prepare = lib.concatMapStringsSep "\n\n" (s: "# prepare ${s.name}\n${s.prepare}") steps;
            copy = lib.concatMapStringsSep "\n\n" (s: "# copy ${s.name}\n${s.copy}") steps;
            config_generation = pkgs.runCommand "config_generation.sh" {
                src = ./config_generation.sh;
                deploy_steps = ''
                  ${lib.concatMapStrings
                    (s: ''
                      # apply ${s.name}
                      log "running ${s.name} ..."
                      ${s.apply}
                    '')
                    steps}

                  log 'rebooting device ...'
                '';
                rollback_timeout = config.deploy.rollbackTimeout;
            } ''
              substitute "$src" "$out" \
                --subst-var deploy_steps \
                --subst-var rollback_timeout
              chmod +x "$out"
            '';
            timeout = config.deploy.rollbackTimeout + config.deploy.rebootAllowance;
            sshOpts =
              ''-o ControlPath="$TMP/cm" ''
              + lib.escapeShellArgs
                (lib.mapAttrsToList
                  (arg: val: "-o${arg}=${
                    if val == true then "yes"
                    else if val == false then "no"
                    else toString val
                  }")
                  ({
                    ControlMaster = "auto";
                    User = config.deploy.user;
                    Hostname = config.deploy.host;
                  } // config.deploy.sshConfig)
                );
          in
            pkgs.writeShellScriptBin "deploy-${name}" ''
              set -euo pipefail
              shopt -s inherit_errexit

              BOLD='\e[1m'
              PURP='\e[35m'
              CYAN='\e[36m'
              RED='\e[31m'
              NORMAL='\e[0m'

              log() {
                printf "$BOLD$PURP> %s$NORMAL\n" "$*"
              }
              log_err() {
                printf "$BOLD$RED> %s$NORMAL\n" "$*"
              }

              # generate a (reasonably) unique logger tag. mustn't be too long,
              # or it'll be truncated and matching will fail.
              TAG="apply_config_$$_$RANDOM"

              ssh() {
                command ssh ${sshOpts} device "$@"
              }

              scp() {
                command scp -Op ${sshOpts} "$@"
              }

              main() {
                export TMP="$(umask 0077; mktemp -d)"

                trap '
                  [ -e "$TMP/cm" ] && ssh -O exit 2>/dev/null || true
                  rm -rf "$TMP"
                ' EXIT

                log 'preparing files'
                ${prepare}

                log 'copying files'
                scp ${config_generation} device:/etc/init.d/config_generation
                ${copy}

                # apply the new config and wait for the box to go down via ssh connection
                # timeout.
                log 'applying config'
                ssh '
                  export LOG_FMT="'"$CYAN"'>> %s'"$NORMAL"'"
                  /etc/init.d/config_generation apply </dev/null 2>&1 \
                    | logger -t '"$TAG" &
                ssh 'logread -l9999 -f' | awk -v FS="$TAG: " '$2 { print $2 }' || true

                log 'waiting for device to return'
                __DO_WAIT=1 timeout --foreground ${toString timeout}s "$0" || {
                  log_err 'configuration change failed, device will roll back and reboot'
                  exit 1
                }

                log 'new configuration applied'
              }

              _wait() {
                while ! ssh -oConnectTimeout=5 '/etc/init.d/config_generation commit'; do
                  sleep 1
                done
              }

              case "''${__DO_WAIT:-}" in
                "") main ;;
                *) _wait ;;
              esac
            '';
      };
    })];
  };

in

{
  options.openwrt = lib.mkOption {
    type = lib.types.attrsOf devType;
    default = {};
  };
}