cluster/services/consul: implement consul-ready

This commit is contained in:
Max Headroom 2024-07-17 16:30:21 +02:00
parent 725d71cd47
commit d2ab37f3b1
2 changed files with 55 additions and 0 deletions

View file

@ -15,6 +15,7 @@ in
nixos.agent = [ nixos.agent = [
./agent.nix ./agent.nix
./remote-api.nix ./remote-api.nix
./ready.nix
]; ];
}; };

View file

@ -0,0 +1,54 @@
{ config, lib, pkgs, ... }:
let
consulReady = pkgs.writers.writeHaskellBin "consul-ready" {
libraries = with pkgs.haskellPackages; [ aeson http-conduit watchdog ];
} ''
{-# LANGUAGE OverloadedStrings #-}
import Control.Watchdog
import Control.Exception
import System.IO
import Network.HTTP.Simple
import Data.Aeson
flushLogger :: WatchdogLogger String
flushLogger taskErr delay = do
defaultLogger taskErr delay
hFlush stdout
data ConsulHealth = ConsulHealth {
healthy :: Bool
}
instance FromJSON ConsulHealth where
parseJSON (Object v) = ConsulHealth <$> (v .: "Healthy")
handleException ex = case ex of
(SomeException _) -> return $ Left "Consul is not active"
main :: IO ()
main = watchdog $ do
setInitialDelay 300_000
setMaximumDelay 30_000_000
setLoggingAction flushLogger
watch $ handle handleException $ do
res <- httpJSON "${config.links.consulAgent.url}/v1/operator/autopilot/health"
case getResponseBody res of
ConsulHealth True -> return $ Right ()
ConsulHealth False -> return $ Left "Consul is unhealthy"
'';
in
{
systemd.services.consul-ready = {
description = "Wait for Consul";
requires = [ "consul.service" ];
after = [ "consul.service" ];
serviceConfig = {
ExecStart = lib.getExe consulReady;
DynamicUser = true;
TimeoutStartSec = "5m";
Type = "oneshot";
};
};
}