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