From d4aa51a54fa23b1639a22cdc8dd17ab58c3085a0 Mon Sep 17 00:00:00 2001 From: vuko Date: Fri, 27 Nov 2020 17:32:14 +0100 Subject: [PATCH] add service --- service.nix | 94 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 service.nix diff --git a/service.nix b/service.nix new file mode 100644 index 0000000..c8b5915 --- /dev/null +++ b/service.nix @@ -0,0 +1,94 @@ +{ config, lib, pkgs, ... }: + +with lib; +let + cfg = config.services.ulogd; + settingsFormat = pkgs.formats.yaml { }; + settingsFile = settingsFormat.generate "lights-web-config.yaml" cfg.settings; +in { + options = { + services.ulogd = { + enable = mkEnableOption "lights-web"; + + settings = mkOption { + type = settingsFormat.type; + default = {}; + }; + + domain = mkOption { + type = str; + default = "lights.waw.hackerspace.pl"; + }; + }; + }; + + config = let + paho = pkgs.fetchFromGitHub { + owner = "eclipse"; + repo = "paho.mqtt.javascript"; + rev = "v1.1.0"; + sha256 = "1yihw5pab5s6l9zds9n566iai63zy3zhdlw70735fj504zdqjxv6"; + }; + + name = "lights-web"; + user = name; + python = pkgs.python3.withPackages (pp:[ lights-web pp.gunicorn ]); + socket_dir = "/run/${name}/"; + secrets_dir = "/run/secrets/${name}/"; + + cleanup-script = pkgs.writeShellScript "${name}-cleanup" '' + rm -rf "${secrets_dir}" + rm -rf "${socket_dir}" + ''; + + prepare-script = pkgs.writeShellScript "${name}-prepare" '' + ${cleanup-script} + + ${pkgs.coreutils}/bin/install --owner=${user} --mode=500 --directory ${secrets_dir} + ${pkgs.coreutils}/bin/install --owner=${user} --mode=400 -t ${secrets_dir} \ + /etc/nixos/secrets/${name}/secrets.yaml \ + + ${pkgs.coreutils}/bin/install --owner=${user} --mode=500 --directory /run/${socket_dir} + ${pkgs.acl}/bin/setfacl -m "u:nginx:rx" ${socket_dir} + ''; + in mkIf cfg.enable { + systemd.services."${name}" = { + description = "Web interface for switching HS lights"; + wantedBy = [ "multi-user.target" ]; + + environment = { + LIGHTS_WEB_SECRETS="${secrets_dir}/secrets.yaml"; + LIGHTS_WEB_CONFIG=settingsFile; + }; + + serviceConfig = { + User = "${user}"; + Type = "simple"; + ExecStart = "${python}/bin/gunicorn -b unix:${socket_dir}/web.sock lights_web:app()"; + ExecStartPre = ''!${prepare-script}''; + ExecStopPost = ''!${cleanup-script}''; + }; + }; + + services.nginx.virtualHosts."${cfg.domain}" = + { + locations."/static/" = { + alias = "${repo}/lights_web/static/"; + }; + locations."/index.html" = { + alias = "${repo}/lights_web/static/index.html"; + }; + locations."/" = { + proxyPass = "http://unix://${socket_dir}/web.sock"; + extraConfig = '' + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Host $host:$server_port; + proxy_set_header X-Forwarded-Server $host; + proxy_set_header X-Forwarded-Proto $scheme; + ''; + }; + }; + }; +}