summaryrefslogtreecommitdiffstats
path: root/krebs/3modules/ci.nix
blob: 822dbab612b208722994d7c984282f5a2548bef3 (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
{ config, lib, pkgs, ... }:

with import <stockholm/lib>;

let
  cfg = config.krebs.ci;

  out = {
    options.krebs.ci = api;
    config = lib.mkIf cfg.enable imp;
  };

  api = {
    enable = mkEnableOption "Enable krebs ci service";
    repos = mkOption {
      type = types.attrsOf (types.submodule ({ config, ...}: {
        options = {
          urls = mkOption {
            type = types.listOf types.str;
            default = [ "git@localhost:${config._module.args.name}" ];
          };
        };
      }));
    };
  };

  hostname = config.networking.hostName;
  getJobs = pkgs.writeDash "get_jobs" ''
    set -efu
    ${pkgs.nix}/bin/nix-build --no-out-link --quiet --show-trace -Q ./ci.nix >&2
    json="$(${pkgs.nix}/bin/nix-instantiate --quiet -Q --eval --strict --json ./ci.nix)"
    echo "$json" | ${pkgs.jq}/bin/jq -r 'to_entries[] | [.key, .value] | @tsv' \
      | while read -r host builder; do
        gcroot=${shell.escape profileRoot}/$host-builder
        ${pkgs.nix}/bin/nix-env -p "$gcroot" --set "$builder"
      done
    echo "$json"
  '';

  profileRoot = "/nix/var/nix/profiles/ci";

  bcfg = config.services.buildbot-master;

  imp = {
    services.buildbot-master = {
      workers = [ "worker.Worker('testworker', 'pass')" ];

      changeSource = mapAttrsToList (name: repo:
        concatMapStringsSep "," (url: ''
          changes.GitPoller(
              "${url}",
              workdir='${name}-${elemAt(splitString "." url) 1}', branches=True,
              project='${name}',
              pollinterval=100
          )
        '') repo.urls
      ) cfg.repos;

      schedulers = mapAttrsToList (name: repo: ''
        schedulers.SingleBranchScheduler(
            change_filter=util.ChangeFilter(
                branch_re=".*",
                project='${name}',
            ),
            treeStableTimer=60,
            name="${name}-all-branches",
            builderNames=[
                "${name}",
            ]
        ),
        schedulers.ForceScheduler(
            name="${name}",
            builderNames=[
                "${name}",
            ]
        )
      '') cfg.repos;

      builders = [];

      extraConfig = ''
        # https://docs.buildbot.net/latest/manual/configuration/buildfactories.html
        from buildbot.plugins import util, steps
        from buildbot.process import buildstep, logobserver
        from twisted.internet import defer
        import json

        class GenerateStagesCommand(buildstep.ShellMixin, steps.BuildStep):
            def __init__(self, **kwargs):
                kwargs = self.setupShellMixin(kwargs)
                super().__init__(**kwargs)
                self.observer = logobserver.BufferLogObserver()
                self.addLogObserver('stdio', self.observer)

            def extract_stages(self, stdout):
                stages = json.loads(stdout)
                return stages

            @defer.inlineCallbacks
            def run(self):
                # run nix-instanstiate to generate the dict of stages
                cmd = yield self.makeRemoteShellCommand()
                yield self.runCommand(cmd)

                # if the command passes extract the list of stages
                result = cmd.results()
                if result == util.SUCCESS:
                    # create a ShellCommand for each stage and add them to the build
                    stages = self.extract_stages(self.observer.getStdout())
                    self.build.addStepsAfterCurrentStep([
                        steps.ShellCommand(
                          name=stage,
                          env=dict(
                            build_name = stage,
                            build_script = stages[stage],
                          ),
                          command="${pkgs.writeDash "build.sh" ''
                            set -xefu
                            profile=${shell.escape profileRoot}/$build_name
                            result=$("$build_script")
                            if [ -n "$result" ]; then
                              ${pkgs.nix}/bin/nix-env -p "$profile" --set "$result"
                            fi
                          ''}",
                        ) for stage in stages
                    ])

                return result


        ${concatStringsSep "\n" (mapAttrsToList (name: repo: ''
          factory_${name} = util.BuildFactory()
          factory_${name}.addStep(steps.Git(
              repourl=util.Property('repository', '${head repo.urls}'),
              method='clobber',
              mode='full',
              submodules=True,
          ))

          factory_${name}.addStep(GenerateStagesCommand(
              env={
                  "NIX_REMOTE": "daemon",
                  "NIX_PATH": "secrets=/var/src/stockholm/null:/var/src",
              },
              name="Generate build stages",
              command=[
                  "${getJobs}"
              ],
              haltOnFailure=True,
          ))

          c['builders'].append(
              util.BuilderConfig(
                  name="${name}",
                  workernames=['testworker'],
                  factory=factory_${name}
              )
          )
        '') cfg.repos)}
      '';

      enable = true;
      reporters = [''
        reporters.IRC(
          host = "irc.r",
          nick = "buildbot|${hostname}",
          notify_events = [ 'started', 'finished', 'failure', 'success', 'exception', 'problem' ],
          channels = [{"channel": "#xxx"}],
        )
      ''];

      buildbotUrl = "http://build.${hostname}.r/";
    };

    services.buildbot-worker = {
      enable = true;
      workerUser = "testworker";
      workerPass = "pass";
      packages = with pkgs; [ git gnutar gzip jq nix populate ];
    };

    system.activationScripts.buildbots-nix-profile = ''
      ${pkgs.coreutils}/bin/mkdir -p ${shell.escape profileRoot}
      ${pkgs.coreutils}/bin/chmod 0770 ${shell.escape profileRoot}
      ${pkgs.coreutils}/bin/chgrp buildbots ${shell.escape profileRoot}
    '';

    users = {
      groups.buildbots.gid = genid "buildbots";
      users = {
        buildbot.extraGroups = [ "buildbots" ];
        bbworker.extraGroups = [ "buildbots" ];
      };
    };
  };

in out