@@ -0,0 +1,221 @@
1+{ config, lib, pkgs, ... }:
2+
3+with lib;
4+
5+let
6+ cfg = config.services.cockroachdb;
7+ crdb = cfg.package;
8+
9+ escape = builtins.replaceStrings ["%"] ["%%"];
10+ ifNotNull = v: s: optionalString (!isNull v) s;
11+
12+ startupCommand = lib.concatStringsSep " "
13+ [ # Basic startup
14+ "${crdb}/bin/cockroach start"
15+ "--logtostderr"
16+ "--store=${cfg.dataDir}"
17+ (ifNotNull cfg.locality "--locality='${cfg.locality}'")
18+
19+ # WebUI settings
20+ "--http-addr='${cfg.http.address}:${toString cfg.http.port}'"
21+
22+ # Cluster listen address
23+ "--listen-addr='${cfg.listen.address}:${toString cfg.listen.port}'"
24+
25+ # Cluster configuration
26+ (ifNotNull cfg.join "--join=${cfg.join}")
27+
28+ # Cache and memory settings. Must be escaped.
29+ "--cache='${escape cfg.cache}'"
30+ "--max-sql-memory='${escape cfg.maxSqlMemory}'"
31+
32+ # Certificate/security settings.
33+ (if cfg.insecure then "--insecure" else "--certs-dir=${cfg.certsDir}")
34+ ];
35+
36+ addressOption = descr: defaultPort: {
37+ address = mkOption {
38+ type = types.str;
39+ default = "localhost";
40+ description = "Address to bind to for ${descr}";
41+ };
42+
43+ port = mkOption {
44+ type = types.int;
45+ default = defaultPort;
46+ description = "Port to bind to for ${descr}";
47+ };
48+ };
49+in
50+
51+{
52+ options = {
53+ services.cockroachdb = {
54+ enable = mkEnableOption "CockroachDB Server";
55+
56+ listen = addressOption "intra-cluster communication" 26257;
57+
58+ http = addressOption "http-based Admin UI" 8080;
59+
60+ locality = mkOption {
61+ type = types.nullOr types.str;
62+ default = null;
63+ description = ''
64+ An ordered, comma-separated list of key-value pairs that describe the
65+ topography of the machine. Topography might include country,
66+ datacenter or rack designations. Data is automatically replicated to
67+ maximize diversities of each tier. The order of tiers is used to
68+ determine the priority of the diversity, so the more inclusive
69+ localities like country should come before less inclusive localities
70+ like datacenter. The tiers and order must be the same on all nodes.
71+ Including more tiers is better than including fewer. For example:
72+
73+ country=us,region=us-west,datacenter=us-west-1b,rack=12
74+ country=ca,region=ca-east,datacenter=ca-east-2,rack=4
75+
76+ planet=earth,province=manitoba,colo=secondary,power=3
77+ '';
78+ };
79+
80+ join = mkOption {
81+ type = types.nullOr types.str;
82+ default = null;
83+ description = "The addresses for connecting the node to a cluster.";
84+ };
85+
86+ dataDir = mkOption {
87+ type = types.path;
88+ default = "/var/lib/cockroachdb";
89+ description = "Location where CockroachDB stores its table files";
90+ };
91+
92+ insecure = mkOption {
93+ type = types.bool;
94+ default = false;
95+ description = "Run in insecure mode.";
96+ };
97+
98+ certsDir = mkOption {
99+ type = types.nullOr types.path;
100+ default = null;
101+ description = "The path to the certificate directory.";
102+ };
103+
104+ user = mkOption {
105+ type = types.str;
106+ default = "cockroachdb";
107+ description = "User account under which CockroachDB runs";
108+ };
109+
110+ group = mkOption {
111+ type = types.str;
112+ default = "cockroachdb";
113+ description = "User account under which CockroachDB runs";
114+ };
115+
116+ openPorts = mkOption {
117+ type = types.bool;
118+ default = false;
119+ description = "Open firewall ports for cluster communication by default";
120+ };
121+
122+ cache = mkOption {
123+ type = types.str;
124+ default = "25%";
125+ description = ''
126+ The total size for caches.
127+
128+ This can be a percentage, expressed with a fraction sign or as a
129+ decimal-point number, or any bytes-based unit. For example, "25%",
130+ "0.25" both represent 25% of the available system memory. The values
131+ "1000000000" and "1GB" both represent 1 gigabyte of memory.
132+ '';
133+ };
134+
135+ maxSqlMemory = mkOption {
136+ type = types.str;
137+ default = "25%";
138+ description = ''
139+ The maximum in-memory storage capacity available to store temporary
140+ data for SQL queries.
141+
142+ This can be a percentage, expressed with a fraction sign or as a
143+ decimal-point number, or any bytes-based unit. For example, "25%",
144+ "0.25" both represent 25% of the available system memory. The values
145+ "1000000000" and "1GB" both represent 1 gigabyte of memory.
146+ '';
147+ };
148+
149+ package = mkOption {
150+ type = types.package;
151+ default = pkgs.cockroachdb;
152+ description = ''
153+ The CockroachDB derivation to use for running the service.
154+
155+ This would primarily be useful to enable Enterprise Edition features
156+ in your own custom CockroachDB build (Nixpkgs CockroachDB binaries
157+ only contain open source features and open source code).
158+ '';
159+ };
160+ };
161+ };
162+
163+ config = mkIf config.services.cockroachdb.enable {
164+ assertions = [
165+ { assertion = !cfg.insecure -> !(isNull cfg.certsDir);
166+ message = "CockroachDB must have a set of SSL certificates (.certsDir), or run in Insecure Mode (.insecure = true)";
167+ }
168+ ];
169+
170+ environment.systemPackages = [ crdb ];
171+
172+ users.users = optionalAttrs (cfg.user == "cockroachdb") (singleton
173+ { name = "cockroachdb";
174+ description = "CockroachDB Server User";
175+ uid = config.ids.uids.cockroachdb;
176+ group = cfg.group;
177+ });
178+
179+ users.groups = optionalAttrs (cfg.group == "cockroachdb") (singleton
180+ { name = "cockroachdb";
181+ gid = config.ids.gids.cockroachdb;
182+ });
183+
184+ networking.firewall.allowedTCPPorts = lib.optionals cfg.openPorts
185+ [ cfg.http.port cfg.listen.port ];
186+
187+ systemd.services.cockroachdb =
188+ { description = "CockroachDB Server";
189+ documentation = [ "man:cockroach(1)" "https://www.cockroachlabs.com" ];
190+
191+ after = [ "network.target" "time-sync.target" ];
192+ requires = [ "time-sync.target" ];
193+ wantedBy = [ "multi-user.target" ];
194+
195+ unitConfig.RequiresMountsFor = "${cfg.dataDir}";
196+
197+ preStart = ''
198+ if ! test -e ${cfg.dataDir}; then
199+ mkdir -m 0700 -p ${cfg.dataDir}
200+ chown -R ${cfg.user} ${cfg.dataDir}
201+ fi
202+ '';
203+
204+ serviceConfig =
205+ { ExecStart = startupCommand;
206+ Type = "notify";
207+ User = cfg.user;
208+ PermissionsStartOnly = true;
209+
210+ Restart = "always";
211+ TimeoutStopSec="60";
212+ RestartSec="10";
213+ StandardOutput="syslog";
214+ StandardError="syslog";
215+ SyslogIdentifier="cockroach";
216+ };
217+ };
218+ };
219+
220+ meta.maintainers = with lib.maintainers; [ thoughtpolice ];
221+}