1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6
7 b2s = x: if x then "true" else "false";
8
9 cfg = config.services.mongodb;
10
11 mongodb = cfg.package;
12
13 mongoCnf = pkgs.writeText "mongodb.conf"
14 ''
15 bind_ip = ${cfg.bind_ip}
16 ${optionalString cfg.quiet "quiet = true"}
17 dbpath = ${cfg.dbpath}
18 syslog = true
19 fork = true
20 pidfilepath = ${cfg.pidFile}
21 ${optionalString (cfg.replSetName != "") "replSet = ${cfg.replSetName}"}
22 ${cfg.extraConfig}
23 '';
24
25in
26
27{
28
29 ###### interface
30
31 options = {
32
33 services.mongodb = {
34
35 enable = mkOption {
36 default = false;
37 description = "
38 Whether to enable the MongoDB server.
39 ";
40 };
41
42 package = mkOption {
43 default = pkgs.mongodb;
44 type = types.package;
45 description = "
46 Which MongoDB derivation to use.
47 ";
48 };
49
50 user = mkOption {
51 default = "mongodb";
52 description = "User account under which MongoDB runs";
53 };
54
55 bind_ip = mkOption {
56 default = "127.0.0.1";
57 description = "IP to bind to";
58 };
59
60 quiet = mkOption {
61 default = false;
62 description = "quieter output";
63 };
64
65 dbpath = mkOption {
66 default = "/var/db/mongodb";
67 description = "Location where MongoDB stores its files";
68 };
69
70 pidFile = mkOption {
71 default = "/var/run/mongodb.pid";
72 description = "Location of MongoDB pid file";
73 };
74
75 replSetName = mkOption {
76 default = "";
77 description = ''
78 If this instance is part of a replica set, set its name here.
79 Otherwise, leave empty to run as single node.
80 '';
81 };
82
83 extraConfig = mkOption {
84 default = "";
85 example = ''
86 nojournal = true
87 '';
88 description = "MongoDB extra configuration";
89 };
90 };
91
92 };
93
94
95 ###### implementation
96
97 config = mkIf config.services.mongodb.enable {
98
99 users.extraUsers.mongodb = mkIf (cfg.user == "mongodb")
100 { name = "mongodb";
101 uid = config.ids.uids.mongodb;
102 description = "MongoDB server user";
103 };
104
105 environment.systemPackages = [ mongodb ];
106
107 systemd.services.mongodb =
108 { description = "MongoDB server";
109
110 wantedBy = [ "multi-user.target" ];
111 after = [ "network.target" ];
112
113 serviceConfig = {
114 ExecStart = "${mongodb}/bin/mongod --quiet --config ${mongoCnf}";
115 User = cfg.user;
116 PIDFile = cfg.pidFile;
117 Type = "forking";
118 TimeoutStartSec=120; # intial creating of journal can take some time
119 PermissionsStartOnly = true;
120 };
121
122 preStart = ''
123 rm ${cfg.dbpath}/mongod.lock || true
124 if ! test -e ${cfg.dbpath}; then
125 install -d -m0700 -o ${cfg.user} ${cfg.dbpath}
126 fi
127 if ! test -e ${cfg.pidFile}; then
128 install -D -o ${cfg.user} /dev/null ${cfg.pidFile}
129 fi
130 '';
131 };
132
133 };
134
135}