-- SPDX-FileCopyrightText: 2026 Alexandra de Wit
--
-- SPDX-License-Identifier: MIT

-- | Linux cgroup v2 limits and memory observations, independent of GHC runtime planning.
module Ecluse.Rts.Cgroup (
    CgroupLimits (..),
    readCgroupLimits,
    parseCpuMax,
    parseMemoryMax,
    parseInactiveFile,
    readIfExists,
    usePermille,
    cgroupMemoryUse,
) where

import Data.Text qualified as T
import System.IO.Error (isDoesNotExistError)
import UnliftIO (tryIO, tryJust)

-- | The cgroup v2 grant per axis: CPU quota in cores, @memory.max@ in bytes, 'Nothing' when absent or @max@.
data CgroupLimits = CgroupLimits
    { CgroupLimits -> Maybe Double
cgCpuCores :: Maybe Double
    , CgroupLimits -> Maybe Int
cgMemoryMaxBytes :: Maybe Int
    }
    deriving stock (CgroupLimits -> CgroupLimits -> Bool
(CgroupLimits -> CgroupLimits -> Bool)
-> (CgroupLimits -> CgroupLimits -> Bool) -> Eq CgroupLimits
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: CgroupLimits -> CgroupLimits -> Bool
== :: CgroupLimits -> CgroupLimits -> Bool
$c/= :: CgroupLimits -> CgroupLimits -> Bool
/= :: CgroupLimits -> CgroupLimits -> Bool
Eq, Int -> CgroupLimits -> ShowS
[CgroupLimits] -> ShowS
CgroupLimits -> FilePath
(Int -> CgroupLimits -> ShowS)
-> (CgroupLimits -> FilePath)
-> ([CgroupLimits] -> ShowS)
-> Show CgroupLimits
forall a.
(Int -> a -> ShowS) -> (a -> FilePath) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> CgroupLimits -> ShowS
showsPrec :: Int -> CgroupLimits -> ShowS
$cshow :: CgroupLimits -> FilePath
show :: CgroupLimits -> FilePath
$cshowList :: [CgroupLimits] -> ShowS
showList :: [CgroupLimits] -> ShowS
Show)

-- | Parse a cgroup v2 @cpu.max@ body into granted cores. The @max@ sentinel or a malformed body yields 'Nothing'.
parseCpuMax :: Text -> Maybe Double
parseCpuMax :: Text -> Maybe Double
parseCpuMax Text
body = case Text -> [Text]
T.words (Text -> Text
T.strip Text
body) of
    [Text
quota, Text
period] -> do
        q <- FilePath -> Maybe Double
forall a. Read a => FilePath -> Maybe a
readMaybe (Text -> FilePath
forall a. ToString a => a -> FilePath
toString Text
quota) :: Maybe Double
        p <- readMaybe (toString period) :: Maybe Double
        guard (q > 0 && p > 0)
        pure (q / p)
    [Text]
_ -> Maybe Double
forall a. Maybe a
Nothing

-- | Parse a cgroup v2 @memory.max@ body into bytes. The @max@ sentinel or a malformed body yields 'Nothing'.
parseMemoryMax :: Text -> Maybe Int
parseMemoryMax :: Text -> Maybe Int
parseMemoryMax Text
body = do
    n <- FilePath -> Maybe Int
forall a. Read a => FilePath -> Maybe a
readMaybe (Text -> FilePath
forall a. ToString a => a -> FilePath
toString (Text -> Text
T.strip Text
body)) :: Maybe Int
    guard (n > 0)
    pure n

-- | The @inactive_file@ bytes in a cgroup-v2 @memory.stat@ body: page cache the kernel reclaims first.
parseInactiveFile :: Text -> Maybe Int
parseInactiveFile :: Text -> Maybe Int
parseInactiveFile Text
body =
    [Int] -> Maybe Int
forall a. [a] -> Maybe a
listToMaybe
        [ Int
n
        | Text
line <- Text -> [Text]
forall t. IsText t "lines" => t -> [t]
lines Text
body
        , [Text
"inactive_file", Text
value] <- [Text -> [Text]
T.words Text
line]
        , Just Int
n <- [FilePath -> Maybe Int
forall a. Read a => FilePath -> Maybe a
readMaybe (Text -> FilePath
forall a. ToString a => a -> FilePath
toString Text
value)]
        ]

-- | A reader for cgroup memory use less inactive file pages, in thousandths of the tightest @memory.max@, else 'Nothing'.
cgroupMemoryUse :: IO (IO (Maybe Int))
cgroupMemoryUse :: IO (IO (Maybe Int))
cgroupMemoryUse = do
    dirs <- IO [FilePath]
cgroupDirectories
    limits <- traverse (\FilePath
dir -> (Int -> (FilePath, Int)) -> Maybe Int -> Maybe (FilePath, Int)
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (FilePath
dir,) (Maybe Int -> Maybe (FilePath, Int))
-> IO (Maybe Int) -> IO (Maybe (FilePath, Int))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Text -> Maybe Int) -> FilePath -> FilePath -> IO (Maybe Int)
forall a. (Text -> Maybe a) -> FilePath -> FilePath -> IO (Maybe a)
limitAt Text -> Maybe Int
parseMemoryMax FilePath
"/memory.max" FilePath
dir) dirs
    pure $ case sortOn snd (catMaybes limits) of
        [] -> Maybe Int -> IO (Maybe Int)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe Int
forall a. Maybe a
Nothing
        (FilePath
dir, Int
limit) : [(FilePath, Int)]
_ -> FilePath -> Int -> IO (Maybe Int)
readUse FilePath
dir Int
limit

readUse :: FilePath -> Int -> IO (Maybe Int)
readUse :: FilePath -> Int -> IO (Maybe Int)
readUse FilePath
dir Int
limit = do
    current <- Maybe Int -> Either IOError (Maybe Int) -> Maybe Int
forall b a. b -> Either a b -> b
fromRight Maybe Int
forall a. Maybe a
Nothing (Either IOError (Maybe Int) -> Maybe Int)
-> IO (Either IOError (Maybe Int)) -> IO (Maybe Int)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO (Maybe Int) -> IO (Either IOError (Maybe Int))
forall (m :: * -> *) a.
MonadUnliftIO m =>
m a -> m (Either IOError a)
tryIO ((Text -> Maybe Int) -> FilePath -> FilePath -> IO (Maybe Int)
forall a. (Text -> Maybe a) -> FilePath -> FilePath -> IO (Maybe a)
limitAt Text -> Maybe Int
parseMemoryMax FilePath
"/memory.current" FilePath
dir)
    inactive <- fromRight Nothing <$> tryIO ((>>= parseInactiveFile) <$> readIfExists (dir <> "/memory.stat"))
    pure (usePermille limit inactive <$> current)

-- | Memory in use less reclaimable page cache, in thousandths of the limit, from a cgroup's readings.
usePermille :: Int -> Maybe Int -> Int -> Int
usePermille :: Int -> Maybe Int -> Int -> Int
usePermille Int
limit Maybe Int
inactive Int
current = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
0 (Int
current Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int -> Maybe Int -> Int
forall a. a -> Maybe a -> a
fromMaybe Int
0 Maybe Int
inactive) Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
1000 Int -> Int -> Int
forall a. Integral a => a -> a -> a
`div` Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
1 Int
limit

-- | Read the tightest CPU and memory limits across the process cgroup and its ancestors.
readCgroupLimits :: IO CgroupLimits
readCgroupLimits :: IO CgroupLimits
readCgroupLimits = do
    dirs <- IO [FilePath]
cgroupDirectories
    cpus <- traverse (limitAt parseCpuMax "/cpu.max") dirs
    memories <- traverse (limitAt parseMemoryMax "/memory.max") dirs
    pure
        CgroupLimits
            { cgCpuCores = tightest cpus
            , cgMemoryMaxBytes = tightest memories
            }

cgroupDirectories :: IO [FilePath]
cgroupDirectories :: IO [FilePath]
cgroupDirectories = do
    selfCgroup <- FilePath -> IO (Maybe Text)
readIfExists FilePath
"/proc/self/cgroup"
    let relative = Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe Text
"/" (Maybe Text
selfCgroup Maybe Text -> (Text -> Maybe Text) -> Maybe Text
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Text -> Maybe Text
parseCgroupSelfPath)
    pure [cgroupRoot <> toString suffix | suffix <- ancestorPaths relative]

cgroupRoot :: FilePath
cgroupRoot :: FilePath
cgroupRoot = FilePath
"/sys/fs/cgroup"

limitAt :: (Text -> Maybe a) -> String -> FilePath -> IO (Maybe a)
limitAt :: forall a. (Text -> Maybe a) -> FilePath -> FilePath -> IO (Maybe a)
limitAt Text -> Maybe a
parse FilePath
file FilePath
dir = (Maybe Text -> (Text -> Maybe a) -> Maybe a
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Text -> Maybe a
parse) (Maybe Text -> Maybe a) -> IO (Maybe Text) -> IO (Maybe a)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> FilePath -> IO (Maybe Text)
readIfExists (FilePath
dir FilePath -> ShowS
forall a. Semigroup a => a -> a -> a
<> FilePath
file)

tightest :: (Ord a) => [Maybe a] -> Maybe a
tightest :: forall a. Ord a => [Maybe a] -> Maybe a
tightest [Maybe a]
found = case [Maybe a] -> [a]
forall a. [Maybe a] -> [a]
catMaybes [Maybe a]
found of
    [] -> Maybe a
forall a. Maybe a
Nothing
    (a
x : [a]
xs) -> a -> Maybe a
forall a. a -> Maybe a
Just ((a -> a -> a) -> a -> [a] -> a
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' a -> a -> a
forall a. Ord a => a -> a -> a
min a
x [a]
xs)

-- | Read a file that may be absent, as off a cgroup-v2 host. Every other IO error propagates.
readIfExists :: FilePath -> IO (Maybe Text)
readIfExists :: FilePath -> IO (Maybe Text)
readIfExists FilePath
path =
    Either () Text -> Maybe Text
forall l r. Either l r -> Maybe r
rightToMaybe (Either () Text -> Maybe Text)
-> IO (Either () Text) -> IO (Maybe Text)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (IOError -> Maybe ()) -> IO Text -> IO (Either () Text)
forall (m :: * -> *) e b a.
(MonadUnliftIO m, Exception e) =>
(e -> Maybe b) -> m a -> m (Either b a)
tryJust (Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Maybe ()) -> (IOError -> Bool) -> IOError -> Maybe ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. IOError -> Bool
isDoesNotExistError) (ByteString -> Text
forall a b. ConvertUtf8 a b => b -> a
decodeUtf8 (ByteString -> Text) -> IO ByteString -> IO Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> FilePath -> IO ByteString
forall (m :: * -> *). MonadIO m => FilePath -> m ByteString
readFileBS FilePath
path)

-- The cgroup v2 path on the @0::@ line of @\/proc\/self\/cgroup@. 'Nothing' on a pure cgroup v1 host.
parseCgroupSelfPath :: Text -> Maybe Text
parseCgroupSelfPath :: Text -> Maybe Text
parseCgroupSelfPath Text
body =
    [Text] -> Maybe Text
forall a. [a] -> Maybe a
listToMaybe ((Text -> Maybe Text) -> [Text] -> [Text]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (Text -> Text -> Maybe Text
T.stripPrefix Text
"0::") (Text -> [Text]
forall t. IsText t "lines" => t -> [t]
lines (Text -> Text
T.strip Text
body)))

-- A cgroup path and its ancestors, leaf first: @"\/a\/b"@ yields @["\/a\/b", "\/a", ""]@.
ancestorPaths :: Text -> [Text]
ancestorPaths :: Text -> [Text]
ancestorPaths Text
path = case (Text -> Bool) -> [Text] -> [Text]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Text -> Bool) -> Text -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Bool
T.null) (HasCallStack => Text -> Text -> [Text]
Text -> Text -> [Text]
T.splitOn Text
"/" (Text -> Text
T.strip Text
path)) of
    [] -> [Text
""]
    [Text]
segments ->
        [[Text] -> Text
T.concat [Text
"/" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
seg | Text
seg <- Int -> [Text] -> [Text]
forall a. Int -> [a] -> [a]
take Int
n [Text]
segments] | Int
n <- [[Text] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Text]
segments, [Text] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Text]
segments Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1 .. Int
1]] [Text] -> [Text] -> [Text]
forall a. Semigroup a => a -> a -> a
<> [Text
""]