summaryrefslogtreecommitdiffstats
path: root/nixos/modules/services/scheduling/prefect.nix
blob: c68d5bed3cc0caf9e674aaccf7742c2f067a603a (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
{
  lib,
  pkgs,
  config,
  ...
}:

let
  cfg = config.services.prefect;
  inherit (lib.types)
    bool
    str
    enum
    path
    attrsOf
    nullOr
    submodule
    port
    ;

  # `host` is a bind address, and 0.0.0.0 means "every interface" to bind(2)
  # but nothing at all to connect(2). Workers run beside the server, so they
  # dial it directly rather than going back out through `baseUrl` - a reverse
  # proxy that may terminate TLS, require auth, or simply not be up yet.
  localHost = if cfg.host == "0.0.0.0" then "127.0.0.1" else cfg.host;

  # Prefect builds the SQLAlchemy URL itself from these discrete settings, so
  # the password never has to be interpolated into a string that would land in
  # the store. It arrives separately as PREFECT_SERVER_DATABASE_PASSWORD, from
  # `databasePasswordFile`.
  postgresEnvironment = [
    "PREFECT_SERVER_DATABASE_DRIVER=postgresql+asyncpg"
    "PREFECT_SERVER_DATABASE_HOST=${cfg.databaseHost}"
    "PREFECT_SERVER_DATABASE_PORT=${cfg.databasePort}"
    "PREFECT_SERVER_DATABASE_NAME=${cfg.databaseName}"
    "PREFECT_SERVER_DATABASE_USER=${cfg.databaseUser}"
  ];

  # Identical for the server and every worker, so it is written once.
  hardening = {
    DynamicUser = true;
    ProtectSystem = "strict";
    ProtectHome = true;
    PrivateTmp = true;
    NoNewPrivileges = true;
    MemoryDenyWriteExecute = true;
    LockPersonality = true;
    CapabilityBoundingSet = [ ];
    AmbientCapabilities = [ ];
    RestrictSUIDSGID = true;
    RestrictAddressFamilies = [
      "AF_INET"
      "AF_INET6"
      "AF_UNIX"
    ];
    ProtectKernelTunables = true;
    ProtectKernelModules = true;
    ProtectKernelLogs = true;
    ProtectControlGroups = true;
    MemoryAccounting = true;
  };
in
{
  options.services.prefect = {
    enable = lib.mkOption {
      type = bool;
      default = false;
      description = "enable prefect server and worker services";
    };

    package = lib.mkPackageOption pkgs "prefect" { };

    host = lib.mkOption {
      type = str;
      default = "127.0.0.1";
      example = "0.0.0.0";
      description = "Prefect server host";
    };

    port = lib.mkOption {
      type = port;
      default = 4200;
      description = "Prefect server port";
    };

    dataDir = lib.mkOption {
      type = path;
      default = "/var/lib/prefect-server";
      description = ''
        Working directory for the server. Note that Prefect's own state -
        including the SQLite database - lives in the unit's `StateDirectory`
        rather than here, since the service runs as a `DynamicUser`.
      '';
    };

    database = lib.mkOption {
      type = enum [
        "sqlite"
        "postgres"
      ];
      default = "sqlite";
      description = "which database to use for prefect server: sqlite or postgres";
    };

    databaseHost = lib.mkOption {
      type = str;
      default = "localhost";
      description = "database host for postgres only";
    };

    databasePort = lib.mkOption {
      type = str;
      default = "5432";
      description = "database port for postgres only";
    };

    databaseName = lib.mkOption {
      type = str;
      default = "prefect";
      description = "database name for postgres only";
    };

    databaseUser = lib.mkOption {
      type = str;
      default = "postgres";
      description = "database user for postgres only";
    };

    databasePasswordFile = lib.mkOption {
      type = nullOr str;
      default = null;
      example = "/run/secrets/prefect-database-password";
      description = ''
        Path to a file containing the postgres password as an environment
        variable assignment:

        ```
        PREFECT_SERVER_DATABASE_PASSWORD=supersecret
        ```

        Stored outside the nix store, read by systemd as an `EnvironmentFile`.

        Leave `null` when postgres authenticates the server some other way,
        such as peer authentication over a unix socket.
      '';
    };

    # now define workerPools as an attribute set of submodules,
    # each key is the pool name, and the submodule has an installPolicy
    workerPools = lib.mkOption {
      type = attrsOf (submodule {
        options = {
          installPolicy = lib.mkOption {
            type = enum [
              "always"
              "if-not-present"
              "never"
              "prompt"
            ];
            default = "always";
            description = "install policy for the worker (always, if-not-present, never, prompt)";
          };
        };
      });
      default = { };
      description = ''
        define a set of worker pools with submodule config. example:
        workerPools.my-pool = {
          installPolicy = "never";
        };
      '';
    };

    baseUrl = lib.mkOption {
      type = str;
      default = "http://${localHost}:${toString cfg.port}";
      defaultText = lib.literalExpression ''"http://''${host}:''${toString port}"'';
      example = "https://example.com/prefect";
      description = ''
        External url the UI is reached at, when served by a reverse proxy.
        Defaults to the address the server itself binds, which is what you
        want when there is no proxy in front of it.
      '';
    };
  };

  config = lib.mkIf cfg.enable {
    # define systemd.services as the server plus any worker definitions
    systemd.services = {
      "prefect-server" = {
        description = "prefect server";
        wantedBy = [ "multi-user.target" ];
        after = [ "network.target" ];

        serviceConfig = hardening // {
          StateDirectory = "prefect-server";
          Environment = [
            "PREFECT_HOME=%S/prefect-server"
            "PREFECT_UI_STATIC_DIRECTORY=%S/prefect-server"
            "PREFECT_SERVER_ANALYTICS_ENABLED=off"
            "PREFECT_UI_API_URL=${cfg.baseUrl}/api"
            "PREFECT_UI_URL=${cfg.baseUrl}"
          ]
          ++ lib.optionals (cfg.database == "postgres") postgresEnvironment;

          EnvironmentFile = lib.optional (
            cfg.database == "postgres" && cfg.databasePasswordFile != null
          ) cfg.databasePasswordFile;

          ExecStart = "${lib.getExe cfg.package} server start --host ${cfg.host} --port ${toString cfg.port}";
          Restart = "always";
          WorkingDirectory = cfg.dataDir;
        };
      };
    }
    // lib.concatMapAttrs (poolName: poolCfg: {
      # return a partial attr set with one key: "prefect-worker-..."
      "prefect-worker-${poolName}" = {
        description = "prefect worker for pool '${poolName}'";
        wantedBy = [ "multi-user.target" ];
        after = [
          "network.target"
          "prefect-server.service"
        ];

        # A process worker shells out to prefect for every flow run it picks
        # up, so the package has to be on its PATH and not merely in ExecStart.
        path = [ cfg.package ];

        serviceConfig = hardening // {
          StateDirectory = "prefect-worker-${poolName}";
          Environment = [
            "PREFECT_HOME=%S/prefect-worker-${poolName}"
            "PREFECT_API_URL=http://${localHost}:${toString cfg.port}/api"
          ];
          ExecStart = ''
            ${lib.getExe cfg.package} worker start \
              --pool ${poolName} \
              --type process \
              --install-policy ${poolCfg.installPolicy}
          '';
          Restart = "always";
        };
      };
    }) cfg.workerPools;
  };

  meta.maintainers = with lib.maintainers; [ happysalada ];
}