{-# LANGUAGE OverloadedStrings #-} module HomeAssistant.Runtime.Metrics ( DsType (..) , DsSpec (..) , dsTypeOf , sanitizeName , buildSchema , buildCreateArgs , buildUpdateArgs , parseInfoDs , schemaMatches , AppMetrics (..) , registerAppMetrics , ensureRrd , sampleAndUpdate , metricsAction ) where import Control.Concurrent (threadDelay) import Control.Monad (forever, unless) import Data.Char (ord) import Data.Int (Int64) import Data.List (intercalate, sort, sortBy, stripPrefix) import Data.Maybe (mapMaybe) import Data.Ord (comparing) import Data.Text (Text) import Data.Time (defaultTimeLocale, formatTime, getCurrentTime) import Data.Void (Void) import Numeric (showHex) import qualified Data.Text as T import qualified Data.HashMap.Strict as HM import qualified System.Metrics as M (Value (..), Sample, Store, createCounter, sampleAll) import System.Metrics.Counter (Counter) import System.Directory (doesFileExist, renameFile) import System.Exit (ExitCode (..)) import System.Process (callProcess, readProcessWithExitCode) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Exception.Annotated (checkpointCallStack) import Control.Monad.Catch (MonadCatch) data DsType = Derive | Gauge deriving (Eq, Ord, Show) data DsSpec = DsSpec { dsEkgName :: Text , dsName :: String , dsType :: DsType } deriving (Eq, Show) dsTypeOf :: M.Value -> Maybe DsType dsTypeOf (M.Counter _) = Just Derive dsTypeOf (M.Gauge _) = Just Gauge dsTypeOf _ = Nothing -- | Maps an ekg metric label to a valid rrd DS name (≤19 chars, [A-Za-z0-9_]). -- Long names keep the first 15 chars plus a 3-hex hash suffix for uniqueness. sanitizeName :: Text -> String sanitizeName name | length sanitized <= 19 = sanitized | otherwise = take 15 sanitized ++ "_" ++ paddedHash where sanitized = T.unpack (T.replace "." "_" name) paddedHash = let h = showHex (sum (map ord sanitized) `mod` 4096) "" in replicate (3 - length h) '0' ++ h buildSchema :: M.Sample -> [DsSpec] buildSchema sample = sortBy (comparing dsName) [ DsSpec ekgName (sanitizeName ekgName) dt | (ekgName, val) <- HM.toList sample , Just dt <- [dsTypeOf val] ] data AppMetrics = AppMetrics { amTriggersIn :: Counter , amServicesOut :: Counter } registerAppMetrics :: M.Store -> IO AppMetrics registerAppMetrics store = AppMetrics <$> M.createCounter "hass.trigger.in" store <*> M.createCounter "hass.service.out" store buildCreateArgs :: FilePath -> Int -> [(String, DsType)] -> [String] buildCreateArgs path step specs = ["create", path, "--step", show step] ++ concatMap dsArg specs ++ rras where dsArg (name, Derive) = ["DS:" ++ name ++ ":DERIVE:20:0:U"] dsArg (name, Gauge) = ["DS:" ++ name ++ ":GAUGE:20:0:U"] rras = [ "RRA:AVERAGE:0.5:1:6000" , "RRA:MAX:0.5:1:6000" , "RRA:AVERAGE:0.5:360:1680" , "RRA:MAX:0.5:360:1680" ] buildUpdateArgs :: FilePath -> [String] -> [Maybe Int64] -> [String] buildUpdateArgs path names values = [ "update" , path , "--template" , intercalate ":" names , "N:" ++ intercalate ":" (map renderValue values) ] where renderValue Nothing = "U" renderValue (Just n) = show n dsTypeFromString :: String -> Maybe DsType dsTypeFromString "DERIVE" = Just Derive dsTypeFromString "GAUGE" = Just Gauge dsTypeFromString _ = Nothing parseInfoDs :: String -> [(String, DsType)] parseInfoDs = mapMaybe parseLine . lines where parseLine line = do rest0 <- stripPrefix "ds[" line let (name, rest1) = break (== ']') rest0 rest2 <- stripPrefix "].type = \"" rest1 let (ty, _) = break (== '"') rest2 dt <- dsTypeFromString ty pure (name, dt) schemaMatches :: [DsSpec] -> [(String, DsType)] -> Bool schemaMatches schema existing = sort (map (\s -> (dsName s, dsType s)) schema) == sort existing lookupValue :: M.Sample -> Text -> Maybe Int64 lookupValue sample name = case HM.lookup name sample of Just (M.Counter n) -> Just n Just (M.Gauge n) -> Just n _ -> Nothing readExistingDs :: (MonadCatch m, MonadIO m) => FilePath -> FilePath -> m [(String, DsType)] readExistingDs rrdtool rrdPath = checkpointCallStack $ do (code, out, _) <- liftIO $ readProcessWithExitCode rrdtool ["info", rrdPath] "" pure $ case code of ExitSuccess -> parseInfoDs out _ -> [] backupPath :: MonadIO m => FilePath -> m FilePath backupPath path = liftIO $ do now <- getCurrentTime pure $ path ++ ".bak-" ++ formatTime defaultTimeLocale "%Y%m%dT%H%M%S" now ensureRrd :: (MonadCatch m, MonadIO m) => FilePath -> FilePath -> [DsSpec] -> m () ensureRrd rrdtool rrdPath schema = checkpointCallStack $ do exists <- liftIO $ doesFileExist rrdPath if not exists then create else do current <- readExistingDs rrdtool rrdPath unless (schemaMatches schema current) $ do backup <- backupPath rrdPath liftIO $ renameFile rrdPath backup create where create = liftIO $ callProcess rrdtool (buildCreateArgs rrdPath 10 (map toPair schema)) toPair s = (dsName s, dsType s) sampleAndUpdate :: (MonadCatch m, MonadIO m) => M.Store -> FilePath -> FilePath -> [DsSpec] -> m () sampleAndUpdate store rrdtool rrdPath schema = checkpointCallStack $ do sample <- liftIO $ M.sampleAll store let names = map dsName schema values = map (lookupValue sample . dsEkgName) schema liftIO $ callProcess rrdtool (buildUpdateArgs rrdPath names values) metricsAction :: (MonadCatch m, MonadIO m) => M.Store -> FilePath -> FilePath -> m Void metricsAction store rrdPath rrdtool = checkpointCallStack $ do schema <- buildSchema <$> liftIO (M.sampleAll store) ensureRrd rrdtool rrdPath schema forever $ do sampleAndUpdate store rrdtool rrdPath schema liftIO $ threadDelay 10000000