diff --git a/nix/services/mongodb.nix b/nix/services/mongodb.nix index e28ca140..8e73767a 100644 --- a/nix/services/mongodb.nix +++ b/nix/services/mongodb.nix @@ -48,86 +48,144 @@ in default = ""; description = "Additional text to be appended to `mongodb.conf`."; }; + + replicaSetName = lib.mkOption { + type = types.nullOr types.str; + default = null; + description = "The name of the replica set to configure."; + example = "rs0"; + }; + + ulimit = lib.mkOption { + type = types.nullOr types.ints.unsigned; + default = null; + description = "The maximum number of open file descriptors for mongod."; + }; }; - config = { - outputs = { - settings = { - processes = { - "${name}" = - let - mongoConfig = pkgs.writeText "mongodb.conf" '' - net.port: ${toString config.port} - net.bindIp: ${config.bind} - storage.dbPath: ${config.dataDir} - ${config.extraConfig} - ''; - - startScript = pkgs.writeShellApplication { - name = "start-mongodb"; - runtimeInputs = [ pkgs.coreutils config.package ]; - text = '' - export MONGODATA="${config.dataDir}" - - if [[ ! -d "$MONGODATA" ]]; then - mkdir -p "$MONGODATA" - fi + config.outputs.settings.processes = + let + mongoshArgs = + (lib.optional (lib.elem config.bind [ null "0.0.0.0" "::" ]) "--host=${config.bind}") + ++ + [ + "--port=${toString config.port}" + ]; + mongoshCommand = "${lib.getExe pkgs.mongosh} ${lib.escapeShellArgs mongoshArgs}"; + in + { + "${name}" = + let + mongoConfig = pkgs.writeText "mongodb.conf" '' + net.port: ${toString config.port} + net.bindIp: ${config.bind} + storage.dbPath: ${config.dataDir} + ${lib.optionalString (config.replicaSetName != null) '' + replication: + replSetName: "${config.replicaSetName}" + ''} + ${config.extraConfig} + ''; + + startScript = pkgs.writeShellApplication { + name = "start-mongodb"; + runtimeInputs = [ pkgs.coreutils config.package ]; + text = '' + export MONGODATA="${config.dataDir}" + + if [[ ! -d "$MONGODATA" ]]; then + mkdir -p "$MONGODATA" + fi + + ${if config.ulimit != null then "ulimit -n ${toString config.ulimit}" else ""} - exec mongod --config "${mongoConfig}" - ''; - }; - in - { - command = startScript; - - readiness_probe = { - exec.command = "${pkgs.mongosh}/bin/mongosh --eval \"db.version()\" > /dev/null 2>&1"; - initial_delay_seconds = 2; - period_seconds = 10; - timeout_seconds = 4; - success_threshold = 1; - failure_threshold = 5; - }; - - # https://github.com/F1bonacc1/process-compose#-auto-restart-if-not-healthy - availability = { - restart = "on_failure"; - max_restarts = 5; - }; - }; - "${name}-configure" = - let - configScript = pkgs.writeShellApplication { - name = "configure-mongo"; - text = '' - if ! test -e "${config.dataDir}/.auth_configured"; then - ${pkgs.mongosh}/bin/mongosh <