# enstate on NixOS (docs/design.md, 5.3): the schema from options, the receptor run at # boot and after each switch, and the check before a switch. # # enstate.enable = true; # enstate.channels.secrets.slots."retiolum.key" = { # type = "application/x-openssh-private-key; algorithm=ed25519"; # secret = true; # reactions.restart = [ "tincr-retiolum.service" ]; # unless it restarts itself # }; # enstate.channels.fleet.slots.hosts.type = "application/x-enstate-hosts+json"; # enstate.views.ssh-known-hosts = { # from = [ "fleet/hosts" ]; # renderer = ./render-known-hosts; # }; # # systemd.services.tincr-retiolum.serviceConfig.LoadCredential = # "retiolum.key:${config.enstate.channels.secrets.slots."retiolum.key".path}"; # # Every slot is its own view, `CHANNEL.SLOT`, unless it says `view = false`; its file # is the slot's `path`, `/run/enstate/views/CHANNEL.SLOT/SLOT`. Services read views # as they like; one whose `LoadCredential=` reads a view is ordered after the unit that # puts the views in place, by itself. { config, lib, pkgs, ... }: let inherit (lib) mkOption types; cfg = config.enstate; reactions = { restart = mkOption { type = types.listOf types.str; default = [ ]; description = "Units to restart when the view changes (`foo.service`)."; }; reload = mkOption { type = types.listOf types.str; default = [ ]; description = "Units to reload (or restart, if they can't reload) when the view changes."; }; }; slot = channel: types.submodule ( { name, config, ... }: { options = { type = mkOption { type = types.str; description = "What the slot holds, as a media type."; example = "application/x-openssh-private-key; algorithm=ed25519"; }; required = mkOption { type = types.bool; default = true; description = "Whether a submission, or a switch, that leaves the slot unfilled is refused."; }; secret = mkOption { type = types.bool; default = false; description = "Whether the slot's views are readable by root only."; }; renamedFrom = mkOption { type = types.nullOr types.str; default = null; description = "The slot's name in an earlier generation, so its entry carries over, both ways."; }; view = mkOption { type = types.bool; default = true; description = "Whether the slot is its own view, `CHANNEL.SLOT`."; }; source = mkOption { type = types.nullOr types.raw; default = null; description = '' Where a deployment gets the slot's entry, on the deploying host: a source in enstate's syntax (`cmd:…`, `{ command = [ … ]; }`, …), or `{ location = NAME; VAR = …; }`, a location with its variables. Not part of the system: the deploying host reads it from `sourceLists`. Commands and paths only, never a secret itself. ''; example = lib.literalExpression ''{ location = "secrets"; key = "retiolum.ed25519_key.priv"; }''; }; path = mkOption { type = types.nullOr types.str; readOnly = true; default = if config.view then "${cfg.runDir}/views/${channel}.${name}/${name}" else null; defaultText = lib.literalExpression ''"''${config.enstate.runDir}/views/CHANNEL.SLOT/SLOT"''; description = "Where the slot's own view puts its entry, if it has one, for services to read."; }; inherit reactions; }; } ); # The views of slots that are their own. slotViews = lib.concatMapAttrs ( channel: channelCfg: lib.concatMapAttrs ( name: slotCfg: lib.optionalAttrs slotCfg.view { "${channel}.${name}" = { from = [ "${channel}/${name}" ]; inherit (slotCfg) reactions; }; } ) channelCfg.slots ) cfg.channels; nonNull = lib.filterAttrs (_: value: value != null); schema = { schema = 1; types = lib.mapAttrs ( _: typeCfg: nonNull { validator = lib.mapNullable toString typeCfg.validator; } ) cfg.types; channels = lib.mapAttrs (_: channelCfg: { slots = lib.mapAttrs ( _: slotCfg: nonNull { inherit (slotCfg) type required secret renamedFrom ; } ) channelCfg.slots; }) cfg.channels; validators = lib.mapAttrs (_: validatorCfg: { inherit (validatorCfg) slots; program = toString validatorCfg.program; }) cfg.validators; views = slotViews // lib.mapAttrs ( _: viewCfg: nonNull { inherit (viewCfg) from secret; renderer = lib.mapNullable toString viewCfg.renderer; reactions = { inherit (viewCfg.reactions) restart reload; }; } ) cfg.views; }; schemaFile = pkgs.writers.writeJSON "enstate-schema.json" schema; settings = pkgs.writers.writeJSON "enstate-config.json" { state-dir = cfg.stateDir; run-dir = cfg.runDir; # Started again by --apply if it failed (for want of the state, at boot). unit = "enstate.service"; # Validators and renderers run in it. sandbox = "${pkgs.bubblewrap}/bin/bwrap"; }; enstate = lib.getExe cfg.package; # Whether a `LoadCredential=` (`ID:PATH`) reads a view. readsView = credential: let parts = lib.splitString ":" credential; in lib.length parts > 1 && lib.hasPrefix "${cfg.runDir}/views/" (lib.concatStringsSep ":" (lib.tail parts)); in { options.enstate = { enable = lib.mkEnableOption "enstate, state next to the Nix store"; package = mkOption { type = types.package; default = pkgs.callPackage ./package.nix { }; defaultText = lib.literalExpression "pkgs.callPackage ./package.nix { }"; description = "enstate, the program."; }; stateDir = mkOption { type = types.str; default = "/var/lib/enstate"; description = "Where the snapshots are kept."; }; runDir = mkOption { type = types.str; default = "/run/enstate"; description = "Where the views are put."; }; types = mkOption { type = types.attrsOf ( types.submodule { options.validator = mkOption { type = types.nullOr types.path; default = null; description = "The type's validator (docs/design.md, 5.2)."; }; } ); default = { }; description = "Types, by media type, and their validators."; }; channels = mkOption { type = types.attrsOf ( types.submodule ( { name, ... }: { options.slots = mkOption { type = types.attrsOf (slot name); default = { }; description = "The channel's slots."; }; } ) ); default = { }; description = "Channels, and the slots this generation offers in them."; }; validators = mkOption { type = types.attrsOf ( types.submodule { options = { slots = mkOption { type = types.listOf types.str; description = "The slots it is given (`CHANNEL/SLOT`)."; }; program = mkOption { type = types.path; description = "The validator (docs/design.md, 5.2)."; }; }; } ); default = { }; description = "Validators across slots."; }; views = mkOption { type = types.attrsOf ( types.submodule ( { name, ... }: { options = { from = mkOption { type = types.listOf types.str; description = "The slots it is made from (`CHANNEL/SLOT`)."; }; renderer = mkOption { type = types.nullOr types.path; default = null; description = "The renderer (docs/design.md, 5.2); none for a view of one entry."; }; secret = mkOption { type = types.nullOr types.bool; default = null; description = "Whether it is readable by root only; by default, if a slot it is made from is secret."; }; path = mkOption { type = types.str; readOnly = true; default = "${cfg.runDir}/views/${name}"; defaultText = lib.literalExpression ''"''${config.enstate.runDir}/views/NAME"''; description = "The directory the view's files are in, for services to read."; }; inherit reactions; }; } ) ); default = { }; description = "Views made by renderers."; }; locations = mkOption { type = types.attrsOf types.raw; default = { }; description = '' Locations for every source list (`sourceLists`): sources declared once, which slots' `source` use by name, with variables. A deployment may add its own (a location that names the deploying host's tools, say). A source list is packed on the deploying host, so `$(env:…)` there are its: write the host's own name in by Nix (`config.networking.hostName`), or as a variable. ''; example = lib.literalExpression '' { secrets.source.command = [ "secrets" config.networking.hostName "show" "$(var:key)" ]; } ''; }; sourceLists = mkOption { type = types.attrsOf types.raw; readOnly = true; description = '' A source list for `enstate --pack` per channel, from the slots that have a `source`, complete if every slot of the channel has one, with `locations`. For the deploying host to evaluate (and to write as JSON, e.g. with `pkgs.writers.writeJSON`): not part of the system. ''; default = lib.mapAttrs ( channel: channelCfg: let sourced = lib.filterAttrs (_: slotCfg: slotCfg.source != null) channelCfg.slots; in { inherit channel; complete = lib.attrNames sourced == lib.attrNames channelCfg.slots; items = lib.mapAttrs ( _: slotCfg: if lib.isAttrs slotCfg.source && slotCfg.source ? location then slotCfg.source else { inherit (slotCfg) source; } ) sourced; } // lib.optionalAttrs (cfg.locations != { }) { inherit (cfg) locations; } ) (lib.filterAttrs (_: channelCfg: lib.any (slotCfg: slotCfg.source != null) (lib.attrValues channelCfg.slots)) cfg.channels); defaultText = lib.literalExpression "a source list per channel with sources"; }; incomingDir = mkOption { type = types.str; readOnly = true; default = "${cfg.stateDir}/incoming"; defaultText = lib.literalExpression ''"''${config.enstate.stateDir}/incoming"''; description = '' Where submissions wait for the next switch, each a directory of its own, taken in the order of their names: planned against the new generation's schema before switching, which a refused one refuses, and applied by the switch. Names starting with a dot are skipped: copy a submission under one, then rename it, within this directory, so that it is never seen half copied. ''; }; checkBeforeSwitch = mkOption { type = types.bool; default = true; description = '' Whether a switch to a generation whose required slots the state can't fill, even by migrating and with the submissions waiting in `incomingDir`, or for which a waiting submission is refused, is refused before switching. Also for `boot`: a generation that can't be served doesn't become the next boot's default (tools like Clan run `boot` before `switch`); a submission for it can wait in `incomingDir`. Not checked for `dry-activate`. ''; }; }; # A service whose `LoadCredential=` reads a view is ordered after the unit that puts # the views in place, and wants it: without saying so itself. options.systemd.services = mkOption { type = types.attrsOf ( types.submodule ( { config, ... }: let credentials = lib.concatMap (option: lib.toList (config.serviceConfig.${option} or [ ])) [ "LoadCredential" "LoadCredentialEncrypted" ]; in { config = lib.mkIf (cfg.enable && lib.any readsView credentials) { after = [ "enstate.service" ]; wants = [ "enstate.service" ]; }; } ) ); }; config = lib.mkIf cfg.enable { assertions = [ { assertion = lib.intersectLists (lib.attrNames slotViews) (lib.attrNames cfg.views) == [ ]; message = "enstate.views: ${toString (lib.intersectLists (lib.attrNames slotViews) (lib.attrNames cfg.views))} is also a slot's own view"; } ]; environment.systemPackages = [ cfg.package ]; environment.etc."enstate/schema.json".source = schemaFile; environment.etc."enstate/config.json".source = settings; # Root's, whatever creates it first (a deploy copying into incomingDir, say). systemd.tmpfiles.rules = [ "d ${cfg.stateDir} 0700 root root -" ]; # At boot, and after a switch that changes the schema: the views of this # generation, from the snapshots, and the reactions of those that changed. systemd.services.enstate = { description = "enstate: the views of this generation"; wantedBy = [ "multi-user.target" ]; after = [ "local-fs.target" ]; restartTriggers = [ schemaFile ]; serviceConfig = { Type = "oneshot"; RemainAfterExit = true; ExecStart = "${enstate} --migrate"; }; }; # After a switch whose schema didn't change, with a submission waiting in # incomingDir or staged (--stage leaves a marker, which --migrate removes): # switch-to-configuration restarts sysinit-reactivation.target on every switch, # which starts this, and the conditions keep it from running otherwise. After a # switch whose schema changed, enstate.service has taken them already. systemd.services.enstate-switch = { description = "enstate: what waits for the switch"; wantedBy = [ "sysinit-reactivation.target" ]; after = [ "local-fs.target" ]; before = [ "sysinit-reactivation.target" "shutdown.target" ]; conflicts = [ "shutdown.target" ]; unitConfig = { DefaultDependencies = false; # Either ("|"). ConditionDirectoryNotEmpty = "|${cfg.incomingDir}"; ConditionPathExists = "|${cfg.stateDir}/migrate-due"; }; serviceConfig = { Type = "oneshot"; ExecStart = "${enstate} --migrate"; }; }; # With the new generation's enstate, schema and configuration, also for `boot`, # and on a host without enstate yet: its first switch needs its state, which can # wait in incomingDir. system.preSwitchChecks = lib.mkIf cfg.checkBeforeSwitch { enstate = '' case "''${2-}" in dry-activate) exit 0 ;; esac ${enstate} --migrate --dry-run --schema "$1/etc/enstate/schema.json" --config "$1/etc/enstate/config.json" ''; }; }; }