{-# LANGUAGE ScopedTypeVariables #-}
{-|
Module      : Instana.SDK.Internal.AgentConnection.SchedFile
Description : Parses the content of the sched file.
-}
module Instana.SDK.Internal.AgentConnection.SchedFile
    ( parsePidFromSchedFile
    ) where


import qualified Text.Regex.Base.RegexLike as RegexBase
import qualified Text.Regex.TDFA           as Regex
import           Text.Regex.TDFA.String    (Regex)
import qualified Text.Regex.TDFA.String    as RegexString


-- |Parses a /proc/{pid}/sched file to get the PID in the parent namespace.
parsePidFromSchedFile :: String -> Maybe String
parsePidFromSchedFile :: String -> Maybe String
parsePidFromSchedFile schedFileContent :: String
schedFileContent =
  let
    allMatches :: [[String]]
    allMatches :: [[String]]
allMatches = Regex -> String -> [[String]]
forall regex source target.
RegexContext regex source target =>
regex -> source -> target
RegexBase.match Regex
schedFilePidPattern String
schedFileContent
  in
  if [[String]] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [[String]]
allMatches then
    Maybe String
forall a. Maybe a
Nothing
  else do
    let
      ([String]
firstMatchWithCaptures :: [String]) = [[String]] -> [String]
forall a. [a] -> a
head [[String]]
allMatches
    if ([String] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [String]
firstMatchWithCaptures) Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< 2 then
      Maybe String
forall a. Maybe a
Nothing
    else
      String -> Maybe String
forall a. a -> Maybe a
Just (String -> Maybe String) -> String -> Maybe String
forall a b. (a -> b) -> a -> b
$ [String] -> String
forall a. [a] -> a
head ([String] -> String) -> [String] -> String
forall a b. (a -> b) -> a -> b
$ [String] -> [String]
forall a. [a] -> [a]
tail ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ [String]
firstMatchWithCaptures


schedFilePidPattern :: Regex
schedFilePidPattern :: Regex
schedFilePidPattern =
  let
    compiledPattern :: Either String Regex
compiledPattern =
      CompOption -> ExecOption -> String -> Either String Regex
RegexString.compile
        (CompOption
forall regex compOpt execOpt.
RegexOptions regex compOpt execOpt =>
compOpt
Regex.defaultCompOpt
          { caseSensitive :: Bool
Regex.caseSensitive = Bool
False
          , multiline :: Bool
Regex.multiline = Bool
True
          }
        )
        ExecOption
forall regex compOpt execOpt.
RegexOptions regex compOpt execOpt =>
execOpt
Regex.defaultExecOpt
        "^[^(]+\\(([0-9]+),"
    Right pattern :: Regex
pattern = Either String Regex
compiledPattern
  in
  Regex
pattern