1{ config, lib, pkgs, ...}:
2
3with lib;
4
5let
6 cfg = config.services.varnish;
7
8 commandLine = "-f ${pkgs.writeText "default.vcl" cfg.config}" +
9 optionalString (cfg.extraModules != []) " -p vmod_path='${makeSearchPathOutput "lib" "lib/varnish/vmods" ([pkgs.varnish] ++ cfg.extraModules)}' -r vmod_path";
10in
11{
12 options = {
13 services.varnish = {
14 enable = mkEnableOption "Varnish Server";
15
16 http_address = mkOption {
17 type = types.str;
18 default = "*:6081";
19 description = "
20 HTTP listen address and port.
21 ";
22 };
23
24 config = mkOption {
25 type = types.lines;
26 description = "
27 Verbatim default.vcl configuration.
28 ";
29 };
30
31 stateDir = mkOption {
32 type = types.path;
33 default = "/var/spool/varnish/${config.networking.hostName}";
34 description = "
35 Directory holding all state for Varnish to run.
36 ";
37 };
38
39 extraModules = mkOption {
40 type = types.listOf types.package;
41 default = [];
42 example = literalExample "[ pkgs.varnish-geoip ]";
43 description = "
44 Varnish modules (except 'std').
45 ";
46 };
47
48 extraCommandLine = mkOption {
49 type = types.str;
50 default = "";
51 example = "-s malloc,256M";
52 description = "
53 Command line switches for varnishd (run 'varnishd -?' to get list of options)
54 ";
55 };
56 };
57
58 };
59
60 config = mkIf cfg.enable {
61
62 systemd.services.varnish = {
63 description = "Varnish";
64 wantedBy = [ "multi-user.target" ];
65 after = [ "network.target" ];
66 preStart = ''
67 mkdir -p ${cfg.stateDir}
68 chown -R varnish:varnish ${cfg.stateDir}
69 '';
70 postStop = ''
71 rm -rf ${cfg.stateDir}
72 '';
73 serviceConfig = {
74 Type = "simple";
75 PermissionsStartOnly = true;
76 ExecStart = "${pkgs.varnish}/sbin/varnishd -a ${cfg.http_address} -n ${cfg.stateDir} -F ${cfg.extraCommandLine} ${commandLine}";
77 Restart = "always";
78 RestartSec = "5s";
79 User = "varnish";
80 Group = "varnish";
81 AmbientCapabilities = "cap_net_bind_service";
82 NoNewPrivileges = true;
83 LimitNOFILE = 131072;
84 };
85 };
86
87 environment.systemPackages = [ pkgs.varnish ];
88
89 # check .vcl syntax at compile time (e.g. before nixops deployment)
90 system.extraDependencies = [
91 (pkgs.stdenv.mkDerivation {
92 name = "check-varnish-syntax";
93 buildCommand = "${pkgs.varnish}/sbin/varnishd -C ${commandLine} 2> $out";
94 })
95 ];
96
97 users.extraUsers.varnish = {
98 group = "varnish";
99 uid = config.ids.uids.varnish;
100 };
101
102 users.extraGroups.varnish.gid = config.ids.uids.varnish;
103 };
104}