summaryrefslogtreecommitdiff
path: root/nix-modules/docker-nixos-modules.nix
blob: 47107a70ed540c47285ebafb165a9ee1f1214e8a (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
{ nixpkgsPath ? <nixpkgs>
, ociconfig
, name
, ...}:

let
  pkgs = import nixpkgsPath {};

  dummyOption = with pkgs.lib; mkOption {
    type = types.attrs;
    default = {};
  };

  systemModule = { lib, config, ... }: {
    options = {
      toplevel = lib.mkOption {
        type = lib.types.str;
      };

      systemd = with lib; {
        services = dummyOption;
        targets = dummyOption;
        timers = dummyOption;
      };

      environment = dummyOption;
      users.users = dummyOption;
      users.groups = dummyOption;
      meta = dummyOption;

      networking.enableIPv6 = lib.mkOption {
        type = lib.types.bool;
        default = false;
      };
    };

    config._module.args.pkgs = pkgs;
  };

  config = pkgs.lib.evalModules {
    modules = [
      systemModule
      ociconfig
      "${nixpkgsPath}/nixos/modules/misc/assertions.nix"
    ];
  };

in pkgs.dockerTools.buildImage {
  inherit name;

  contents = pkgs.coreutils;

  runAsRoot = (with pkgs.lib;
    strings.concatStrings
      (mapAttrsToList
        (n: u: if u ? createHome && u.createHome then ("mkdir -p ${u.home}\n") else "")
        config.config.users.users));

  config = with pkgs.lib; {
    Cmd = pkgs.writeShellScript "main-entrypoint"
      (strings.concatStrings
      (map (command: "${command}&")
      (mapAttrsToList
      (name: service:
        (pkgs.writeShellScript
          "systemd-script-${name}"
          ''
            #!${pkgs.dash.outPath}/bin/sh
            set -ueo pipefail
            ${if service ? preStart
              then ''
                echo ${escapeShellArg name}: running preStart script
                ${service.preStart}
              ''
              else ""}
            echo ${name}: starting ...
            ${if service ? serviceConfig && service.serviceConfig ? WorkingDirectory
              then "cd ${service.serviceConfig.WorkingDirectory}"
              else ""}
            ${if service ? environment
              then (strings.concatStrings
                    (mapAttrsToList
                      (n: k: "export ${n}=${escapeShellArg k}\n")
                        service.environment))
                   + service.script
              else ""}
          '').outPath)
        config.config.systemd.services)) + "\n wait");
  };
}