at 22.05-pre 15 kB view raw
1{ config, lib, pkgs, ... }: 2 3with lib; 4 5let 6 cfg = config.services.home-assistant; 7 8 # cfg.config != null can be assumed here 9 configJSON = pkgs.writeText "configuration.json" 10 (builtins.toJSON (if cfg.applyDefaultConfig then 11 (recursiveUpdate defaultConfig cfg.config) else cfg.config)); 12 configFile = pkgs.runCommand "configuration.yaml" { preferLocalBuild = true; } '' 13 ${pkgs.remarshal}/bin/json2yaml -i ${configJSON} -o $out 14 # Hack to support custom yaml objects, 15 # i.e. secrets: https://www.home-assistant.io/docs/configuration/secrets/ 16 sed -i -e "s/'\!\([a-z_]\+\) \(.*\)'/\!\1 \2/;s/^\!\!/\!/;" $out 17 ''; 18 19 lovelaceConfigJSON = pkgs.writeText "ui-lovelace.json" 20 (builtins.toJSON cfg.lovelaceConfig); 21 lovelaceConfigFile = pkgs.runCommand "ui-lovelace.yaml" { preferLocalBuild = true; } '' 22 ${pkgs.remarshal}/bin/json2yaml -i ${lovelaceConfigJSON} -o $out 23 ''; 24 25 availableComponents = cfg.package.availableComponents; 26 27 usedPlatforms = config: 28 if isAttrs config then 29 optional (config ? platform) config.platform 30 ++ concatMap usedPlatforms (attrValues config) 31 else if isList config then 32 concatMap usedPlatforms config 33 else [ ]; 34 35 # Given a component "platform", looks up whether it is used in the config 36 # as `platform = "platform";`. 37 # 38 # For example, the component mqtt.sensor is used as follows: 39 # config.sensor = [ { 40 # platform = "mqtt"; 41 # ... 42 # } ]; 43 useComponentPlatform = component: elem component (usedPlatforms cfg.config); 44 45 # Returns whether component is used in config 46 useComponent = component: 47 hasAttrByPath (splitString "." component) cfg.config 48 || useComponentPlatform component; 49 50 # List of components used in config 51 extraComponents = filter useComponent availableComponents; 52 53 package = if (cfg.autoExtraComponents && cfg.config != null) 54 then (cfg.package.override { inherit extraComponents; }) 55 else cfg.package; 56 57 # If you are changing this, please update the description in applyDefaultConfig 58 defaultConfig = { 59 homeassistant.time_zone = config.time.timeZone; 60 http.server_port = cfg.port; 61 } // optionalAttrs (cfg.lovelaceConfig != null) { 62 lovelace.mode = "yaml"; 63 }; 64 65in { 66 meta.maintainers = teams.home-assistant.members; 67 68 options.services.home-assistant = { 69 # Running home-assistant on NixOS is considered an installation method that is unsupported by the upstream project. 70 # https://github.com/home-assistant/architecture/blob/master/adr/0012-define-supported-installation-method.md#decision 71 enable = mkEnableOption "Home Assistant. Please note that this installation method is unsupported upstream"; 72 73 configDir = mkOption { 74 default = "/var/lib/hass"; 75 type = types.path; 76 description = "The config directory, where your <filename>configuration.yaml</filename> is located."; 77 }; 78 79 port = mkOption { 80 default = 8123; 81 type = types.port; 82 description = "The port on which to listen."; 83 }; 84 85 applyDefaultConfig = mkOption { 86 default = true; 87 type = types.bool; 88 description = '' 89 Setting this option enables a few configuration options for HA based on NixOS configuration (such as time zone) to avoid having to manually specify configuration we already have. 90 </para> 91 <para> 92 Currently one side effect of enabling this is that the <literal>http</literal> component will be enabled. 93 </para> 94 <para> 95 This only takes effect if <literal>config != null</literal> in order to ensure that a manually managed <filename>configuration.yaml</filename> is not overwritten. 96 ''; 97 }; 98 99 config = mkOption { 100 default = null; 101 # Migrate to new option types later: https://github.com/NixOS/nixpkgs/pull/75584 102 type = with lib.types; let 103 valueType = nullOr (oneOf [ 104 bool 105 int 106 float 107 str 108 (lazyAttrsOf valueType) 109 (listOf valueType) 110 ]) // { 111 description = "Yaml value"; 112 emptyValue.value = {}; 113 }; 114 in valueType; 115 example = literalExpression '' 116 { 117 homeassistant = { 118 name = "Home"; 119 latitude = "!secret latitude"; 120 longitude = "!secret longitude"; 121 elevation = "!secret elevation"; 122 unit_system = "metric"; 123 time_zone = "UTC"; 124 }; 125 frontend = { 126 themes = "!include_dir_merge_named themes"; 127 }; 128 http = { }; 129 feedreader.urls = [ "https://nixos.org/blogs.xml" ]; 130 } 131 ''; 132 description = '' 133 Your <filename>configuration.yaml</filename> as a Nix attribute set. 134 Beware that setting this option will delete your previous <filename>configuration.yaml</filename>. 135 <link xlink:href="https://www.home-assistant.io/docs/configuration/secrets/">Secrets</link> 136 are encoded as strings as shown in the example. 137 ''; 138 }; 139 140 configWritable = mkOption { 141 default = false; 142 type = types.bool; 143 description = '' 144 Whether to make <filename>configuration.yaml</filename> writable. 145 This only has an effect if <option>config</option> is set. 146 This will allow you to edit it from Home Assistant's web interface. 147 However, bear in mind that it will be overwritten at every start of the service. 148 ''; 149 }; 150 151 lovelaceConfig = mkOption { 152 default = null; 153 type = with types; nullOr attrs; 154 # from https://www.home-assistant.io/lovelace/yaml-mode/ 155 example = literalExpression '' 156 { 157 title = "My Awesome Home"; 158 views = [ { 159 title = "Example"; 160 cards = [ { 161 type = "markdown"; 162 title = "Lovelace"; 163 content = "Welcome to your **Lovelace UI**."; 164 } ]; 165 } ]; 166 } 167 ''; 168 description = '' 169 Your <filename>ui-lovelace.yaml</filename> as a Nix attribute set. 170 Setting this option will automatically add 171 <literal>lovelace.mode = "yaml";</literal> to your <option>config</option>. 172 Beware that setting this option will delete your previous <filename>ui-lovelace.yaml</filename> 173 ''; 174 }; 175 176 lovelaceConfigWritable = mkOption { 177 default = false; 178 type = types.bool; 179 description = '' 180 Whether to make <filename>ui-lovelace.yaml</filename> writable. 181 This only has an effect if <option>lovelaceConfig</option> is set. 182 This will allow you to edit it from Home Assistant's web interface. 183 However, bear in mind that it will be overwritten at every start of the service. 184 ''; 185 }; 186 187 package = mkOption { 188 default = pkgs.home-assistant.overrideAttrs (oldAttrs: { 189 doInstallCheck = false; 190 }); 191 defaultText = literalExpression '' 192 pkgs.home-assistant.overrideAttrs (oldAttrs: { 193 doInstallCheck = false; 194 }) 195 ''; 196 type = types.package; 197 example = literalExpression '' 198 pkgs.home-assistant.override { 199 extraPackages = ps: with ps; [ colorlog ]; 200 } 201 ''; 202 description = '' 203 Home Assistant package to use. By default the tests are disabled, as they take a considerable amout of time to complete. 204 Override <literal>extraPackages</literal> or <literal>extraComponents</literal> in order to add additional dependencies. 205 If you specify <option>config</option> and do not set <option>autoExtraComponents</option> 206 to <literal>false</literal>, overriding <literal>extraComponents</literal> will have no effect. 207 Avoid <literal>home-assistant.overridePythonAttrs</literal> if you use <literal>autoExtraComponents</literal>. 208 ''; 209 }; 210 211 autoExtraComponents = mkOption { 212 default = true; 213 type = types.bool; 214 description = '' 215 If set to <literal>true</literal>, the components used in <literal>config</literal> 216 are set as the specified package's <literal>extraComponents</literal>. 217 This in turn adds all packaged dependencies to the derivation. 218 You might still see import errors in your log. 219 In this case, you will need to package the necessary dependencies yourself 220 or ask for someone else to package them. 221 If a dependency is packaged but not automatically added to this list, 222 you might need to specify it in <literal>extraPackages</literal>. 223 ''; 224 }; 225 226 openFirewall = mkOption { 227 default = false; 228 type = types.bool; 229 description = "Whether to open the firewall for the specified port."; 230 }; 231 }; 232 233 config = mkIf cfg.enable { 234 networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ cfg.port ]; 235 236 systemd.services.home-assistant = { 237 description = "Home Assistant"; 238 after = [ "network.target" ]; 239 preStart = optionalString (cfg.config != null) (if cfg.configWritable then '' 240 cp --no-preserve=mode ${configFile} "${cfg.configDir}/configuration.yaml" 241 '' else '' 242 rm -f "${cfg.configDir}/configuration.yaml" 243 ln -s ${configFile} "${cfg.configDir}/configuration.yaml" 244 '') + optionalString (cfg.lovelaceConfig != null) (if cfg.lovelaceConfigWritable then '' 245 cp --no-preserve=mode ${lovelaceConfigFile} "${cfg.configDir}/ui-lovelace.yaml" 246 '' else '' 247 rm -f "${cfg.configDir}/ui-lovelace.yaml" 248 ln -s ${lovelaceConfigFile} "${cfg.configDir}/ui-lovelace.yaml" 249 ''); 250 serviceConfig = let 251 # List of capabilities to equip home-assistant with, depending on configured components 252 capabilities = [ 253 # Empty string first, so we will never accidentally have an empty capability bounding set 254 # https://github.com/NixOS/nixpkgs/issues/120617#issuecomment-830685115 255 "" 256 ] ++ (unique (optionals (useComponent "bluetooth_tracker" || useComponent "bluetooth_le_tracker") [ 257 # Required for interaction with hci devices and bluetooth sockets 258 # https://www.home-assistant.io/integrations/bluetooth_le_tracker/#rootless-setup-on-core-installs 259 "CAP_NET_ADMIN" 260 "CAP_NET_RAW" 261 ] ++ lib.optionals (useComponent "emulated_hue") [ 262 # Alexa looks for the service on port 80 263 # https://www.home-assistant.io/integrations/emulated_hue 264 "CAP_NET_BIND_SERVICE" 265 ] ++ lib.optionals (useComponent "nmap_tracker") [ 266 # https://www.home-assistant.io/integrations/nmap_tracker#linux-capabilities 267 "CAP_NET_ADMIN" 268 "CAP_NET_BIND_SERVICE" 269 "CAP_NET_RAW" 270 ])); 271 componentsUsingBluetooth = [ 272 # Components that require the AF_BLUETOOTH address family 273 "bluetooth_tracker" 274 "bluetooth_le_tracker" 275 ]; 276 componentsUsingSerialDevices = [ 277 # Components that require access to serial devices (/dev/tty*) 278 # List generated from home-assistant documentation: 279 # git clone https://github.com/home-assistant/home-assistant.io/ 280 # cd source/_integrations 281 # rg "/dev/tty" -l | cut -d'/' -f3 | cut -d'.' -f1 | sort 282 # And then extended by references found in the source code, these 283 # mostly the ones using config flows already. 284 "acer_projector" 285 "alarmdecoder" 286 "arduino" 287 "blackbird" 288 "deconz" 289 "dsmr" 290 "edl21" 291 "elkm1" 292 "elv" 293 "enocean" 294 "firmata" 295 "flexit" 296 "gpsd" 297 "insteon" 298 "kwb" 299 "lacrosse" 300 "mhz19" 301 "modbus" 302 "modem_callerid" 303 "mysensors" 304 "nad" 305 "numato" 306 "rflink" 307 "rfxtrx" 308 "scsgate" 309 "serial" 310 "serial_pm" 311 "sms" 312 "upb" 313 "usb" 314 "velbus" 315 "w800rf32" 316 "xbee" 317 "zha" 318 "zwave" 319 "zwave_js" 320 ]; 321 in { 322 ExecStart = "${package}/bin/hass --runner --config '${cfg.configDir}'"; 323 ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID"; 324 User = "hass"; 325 Group = "hass"; 326 Restart = "on-failure"; 327 RestartForceExitStatus = "100"; 328 SuccessExitStatus = "100"; 329 KillSignal = "SIGINT"; 330 331 # Hardening 332 AmbientCapabilities = capabilities; 333 CapabilityBoundingSet = capabilities; 334 DeviceAllow = (optionals (any useComponent componentsUsingSerialDevices) [ 335 "char-ttyACM rw" 336 "char-ttyAMA rw" 337 "char-ttyUSB rw" 338 ]); 339 DevicePolicy = "closed"; 340 LockPersonality = true; 341 MemoryDenyWriteExecute = true; 342 NoNewPrivileges = true; 343 PrivateTmp = true; 344 PrivateUsers = false; # prevents gaining capabilities in the host namespace 345 ProtectClock = true; 346 ProtectControlGroups = true; 347 ProtectHome = true; 348 ProtectHostname = true; 349 ProtectKernelLogs = true; 350 ProtectKernelModules = true; 351 ProtectKernelTunables = true; 352 ProtectProc = "invisible"; 353 ProcSubset = "all"; 354 ProtectSystem = "strict"; 355 RemoveIPC = true; 356 ReadWritePaths = let 357 # Allow rw access to explicitly configured paths 358 cfgPath = [ "config" "homeassistant" "allowlist_external_dirs" ]; 359 value = attrByPath cfgPath [] cfg; 360 allowPaths = if isList value then value else singleton value; 361 in [ "${cfg.configDir}" ] ++ allowPaths; 362 RestrictAddressFamilies = [ 363 "AF_INET" 364 "AF_INET6" 365 "AF_NETLINK" 366 "AF_UNIX" 367 ] ++ optionals (any useComponent componentsUsingBluetooth) [ 368 "AF_BLUETOOTH" 369 ]; 370 RestrictNamespaces = true; 371 RestrictRealtime = true; 372 RestrictSUIDSGID = true; 373 SupplementaryGroups = optionals (any useComponent componentsUsingSerialDevices) [ 374 "dialout" 375 ]; 376 SystemCallArchitectures = "native"; 377 SystemCallFilter = [ 378 "@system-service" 379 "~@privileged" 380 ]; 381 UMask = "0077"; 382 }; 383 path = [ 384 "/run/wrappers" # needed for ping 385 ]; 386 }; 387 388 systemd.targets.home-assistant = rec { 389 description = "Home Assistant"; 390 wantedBy = [ "multi-user.target" ]; 391 wants = [ "home-assistant.service" ]; 392 after = wants; 393 }; 394 395 users.users.hass = { 396 home = cfg.configDir; 397 createHome = true; 398 group = "hass"; 399 uid = config.ids.uids.hass; 400 }; 401 402 users.groups.hass.gid = config.ids.gids.hass; 403 }; 404}