summary refs log tree commit diff
path: root/modules/system/upstart/upstart.nix
blob: 368405badc7685258add023a7535087e5166c82b (plain) (blame)
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
{ config, pkgs, ... }:

with pkgs.lib;

let

  upstart = pkgs.upstart;


  # Path for Upstart jobs.  Should be quite minimal.
  upstartPath =
    [ pkgs.coreutils
      pkgs.findutils
      pkgs.gnugrep
      pkgs.gnused
      upstart
    ];

    
  # From a job description, generate an Upstart job file.
  makeJob = job:

    let
      hasMain = job.script != "" || job.exec != "";

      env = config.system.upstartEnvironment // job.environment;

      jobText =
        let log = "/var/log/upstart/${job.name}"; in
        ''
          # Upstart job `${job.name}'.  This is a generated file.  Do not edit.
        
          description "${job.description}"

          ${if isList job.startOn then
              "start on ${concatStringsSep " or " job.startOn}"
            else if job.startOn != "" then
              "start on ${job.startOn}"
            else ""
          }
          
          ${optionalString (job.stopOn != "") "stop on ${job.stopOn}"}

          env PATH=${makeSearchPath "bin" (job.path ++ upstartPath)}:${makeSearchPath "sbin" (job.path ++ upstartPath)}

          ${concatMapStrings (n: "env ${n}=\"${getAttr n env}\"\n") (attrNames env)}
          
          ${optionalString (job.preStart != "") ''
            pre-start script
              exec >> ${log} 2>&1
              ${job.preStart}
            end script
          ''}
          
          ${if job.script != "" && job.exec != "" then
              abort "Job ${job.name} has both a `script' and `exec' attribute."
            else if job.script != "" then
              ''
                script
                  exec >> ${log} 2>&1
                  ${job.script}
                end script
              ''
            else if job.exec != "" then
              ''
                script
                  exec >> ${log} 2>&1
                  exec ${job.exec}
                end script
              ''
            else ""
          }

          ${optionalString (job.postStart != "") ''
            post-start script
              exec >> ${log} 2>&1
              ${job.postStart}
            end script
          ''}
          
          ${optionalString job.task "task"}
          ${optionalString (!job.task && job.respawn) "respawn"}

          ${ # preStop is run only if there is exec or script.
             # (upstart 0.6.5, job.c:562)
            optionalString (job.preStop != "") (assert hasMain; ''
            pre-stop script
              exec >> ${log} 2>&1
              ${job.preStop}
            end script
          '')}

          ${optionalString (job.postStop != "") ''
            post-stop script
              exec >> ${log} 2>&1
              ${job.postStop}
            end script
          ''}

          ${optionalString (!job.task) (
             if job.daemonType == "fork" then "expect fork" else
             if job.daemonType == "daemon" then "expect daemon" else
             if job.daemonType == "stop" then "expect stop" else
             if job.daemonType == "none" then "" else
             throw "invalid daemon type `${job.daemonType}'"
          )}

          ${job.extraConfig}
        '';

    in
      pkgs.runCommand ("upstart-" + job.name + ".conf")
        { inherit (job) buildHook; inherit jobText; }
        ''
          eval "$buildHook"
          echo "$jobText" > $out
        '';

        
  jobOptions = {

    name = mkOption {
      # !!! The type should ensure that this could be a filename.
      type = types.string;
      example = "sshd";
      description = ''
        Name of the Upstart job.
      '';
    };

    buildHook = mkOption {
      type = types.string;
      default = "true";
      description = ''
        Command run while building the Upstart job.  Can be used
        to perform simple regression tests (e.g., the Apache
        Upstart job uses it to check the syntax of the generated
        <filename>httpd.conf</filename>.
      '';
    };

    description = mkOption {
      type = types.string;
      default = "(no description given)";
      description = ''
        A short description of this job.
      '';
    };

    startOn = mkOption {
      # !!! Re-enable this once we're on Upstart >= 0.6.
      #type = types.string; 
      default = "";
      description = ''
        The Upstart event that triggers this job to be started.
        If empty, the job will not start automatically.
      '';
    };

    stopOn = mkOption {
      type = types.string;
      default = "starting shutdown";
      description = ''
        The Upstart event that triggers this job to be stopped.
      '';
    };

    preStart = mkOption {
      type = types.string;
      default = "";
      description = ''
        Shell commands executed before the job is started
        (i.e. before the job's main process is started).
      '';
    };

    postStart = mkOption {
      type = types.string;
      default = "";
      description = ''
        Shell commands executed after the job is started (i.e. after
        the job's main process is started), but before the job is
        considered “running”.
      '';
    };

    preStop = mkOption {
      type = types.string;
      default = "";
      description = ''
        Shell commands executed before the job is stopped
        (i.e. before Upstart kills the job's main process).  This can
        be used to cleanly shut down a daemon.
      '';
    };

    postStop = mkOption {
      type = types.string;
      default = "";
      description = ''
        Shell commands executed after the job has stopped
        (i.e. after the job's main process has terminated).
      '';
    };

    exec = mkOption {
      type = types.string;
      default = "";
      description = ''
        Command to start the job's main process.  If empty, the
        job has no main process, but can still have pre/post-start
        and pre/post-stop scripts, and is considered “running”
        until it is stopped.
      '';
    };

    script = mkOption {
      type = types.string;
      default = "";
      description = ''
        Shell commands executed as the job's main process.  Can be
        specified instead of the <varname>exec</varname> attribute.
      '';
    };

    respawn = mkOption {
      type = types.bool;
      default = true;
      description = ''
        Whether to restart the job automatically if its process
        ends unexpectedly.
      '';
    };

    task = mkOption {
      type = types.bool;
      default = false;
      description = ''
        Whether this job is a task rather than a service.  Tasks
        are executed only once, while services are restarted when
        they exit.
      '';
    };

    environment = mkOption {
      type = types.attrs;
      default = {};
      example = { PATH = "/foo/bar/bin"; LANG = "nl_NL.UTF-8"; };
      description = ''
        Environment variables passed to the job's processes.
      '';
    };

    daemonType = mkOption {
      type = types.string;
      default = "none";
      description = ''
        Determines how Upstart detects when a daemon should be
        considered “running”.  The value <literal>none</literal> means
        that the daemon is considered ready immediately.  The value
        <literal>fork</literal> means that the daemon will fork once.
        The value <literal>daemon</literal> means that the daemon will
        fork twice.  The value <literal>stop</literal> means that the
        daemon will raise the SIGSTOP signal to indicate readiness.
      '';
    };

    extraConfig = mkOption {
      type = types.string;
      default = "";
      example = "limit nofile 4096 4096";
      description = ''
        Additional Upstart stanzas not otherwise supported.
      '';
    };

    path = mkOption {
      default = [ ];
      description = ''
        Packages added to the job's <envar>PATH</envar> environment variable.
        Both the <filename>bin</filename> and <filename>sbin</filename> 
        subdirectories of each package are added.
      '';
    };

  };

  
  upstartJob = {name, config, ...}: {
  
    options = {
      jobDrv = mkOption {
        default = makeJob config;
        type = types.uniq types.package;
        description = ''
          Derivation that builds the Upstart job file.  The default
          value is generated from other options.
        '';
      };
    };

    config = {
      # The default name is the name extracted from the attribute path.
      name = mkDefaultValue (
        replaceChars ["<" ">" "*"] ["_" "_" "_name_"] name
      );
    };
    
  };

in
  
{

  ###### interface
  
  options = {

    jobs = mkOption {
      default = {};
      description = ''
        This option defines the system jobs started and managed by the
        Upstart daemon.
      '';
      type = types.loaOf types.optionSet;
      options = [ jobOptions upstartJob ];
    };
  
    tests.upstartJobs = mkOption {
      internal = true;
      default = {};
      description = ''
        Make it easier to build individual Upstart jobs. (e.g.,
        <command>nix-build /etc/nixos/nixos -A
        tests.upstartJobs.xserver</command>).
      '';
    };
    
    system.upstartEnvironment = mkOption {
      type = types.attrs;
      default = {};
      example = { TZ = "CET"; };
      description = ''
        Environment variables passed to <emphasis>all</emphasis> Upstart jobs.
      '';
    };

  };


  ###### implementation
  
  config = {

    system.build.upstart = upstart;

    environment.etc =
      flip map (attrValues config.jobs) (job:
        { source = job.jobDrv;
          target = "init/${job.name}.conf";
        } );

    # Upstart can listen on the system bus, allowing normal users to
    # do status queries.
    services.dbus.packages = [ upstart ];

  };

}