{-# LANGUAGE CPP #-}

module Hydra.Network.EtcdBinarySpec where

import Hydra.Prelude

import Data.ByteString.Lazy.Char8 qualified as LBS
#ifdef linux_HOST_OS
import Foreign.C.Error (Errno (Errno), eTXTBSY, errnoToIOError)
import GHC.IO.Exception (ioe_errno)
import System.IO (hClose, withBinaryFile)
#endif
import Hydra.Network (WhichEtcd (EmbeddedEtcd))
import Hydra.Network.EtcdBinary (getEtcdBinary, retryOnBusyExecutable)
import System.FilePath ((</>))
import System.IO.Error (isDoesNotExistError)
import System.Process.Typed (proc, readProcessStdout_, runProcess_)
import Test.Hydra.Prelude

spec :: Spec
spec :: Spec
spec = do
  [Char] -> IO () -> SpecWith (Arg (IO ()))
forall a.
(HasCallStack, Example a) =>
[Char] -> a -> SpecWith (Arg a)
it [Char]
"installs and runs embedded etcd from a path containing spaces, including after restart" (IO () -> SpecWith (Arg (IO ())))
-> IO () -> SpecWith (Arg (IO ()))
forall a b. (a -> b) -> a -> b
$
    [Char] -> ([Char] -> IO ()) -> IO ()
forall (m :: * -> *) r.
(MonadIO m, MonadMask m) =>
[Char] -> ([Char] -> m r) -> m r
withTempDir [Char]
"embedded-etcd" (([Char] -> IO ()) -> IO ()) -> ([Char] -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \[Char]
tmp ->
      -- Exercise installation while unrelated children fork and execute.
      ([Char], IO Any) -> (Async IO Any -> IO ()) -> IO ()
forall (m :: * -> *) a b.
MonadAsync m =>
([Char], m a) -> (Async m a -> m b) -> m b
withAsyncLabelled ([Char]
"unrelated-child", IO () -> IO Any
forall (f :: * -> *) a b. Applicative f => f a -> f b
forever (IO () -> IO Any) -> IO () -> IO Any
forall a b. (a -> b) -> a -> b
$ ProcessConfig () () () -> IO ()
forall (m :: * -> *) stdin stdout stderr.
MonadIO m =>
ProcessConfig stdin stdout stderr -> m ()
runProcess_ (ProcessConfig () () () -> IO ())
-> ProcessConfig () () () -> IO ()
forall a b. (a -> b) -> a -> b
$ [Char] -> [[Char]] -> ProcessConfig () () ()
proc [Char]
"sleep" [[Char]
"0.05"]) ((Async IO Any -> IO ()) -> IO ())
-> (Async IO Any -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \Async IO Any
_ -> do
        let persistenceDir :: [Char]
persistenceDir = [Char]
tmp [Char] -> [Char] -> [Char]
</> [Char]
"node state with spaces"
            checkExecutable :: IO ()
checkExecutable =
              NominalDiffTime -> IO () -> IO ()
forall (m :: * -> *) a.
(HasCallStack, MonadTimer m, MonadThrow m) =>
NominalDiffTime -> m a -> m a
failAfter NominalDiffTime
10 (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
                [Char]
executable <- [Char] -> WhichEtcd -> IO [Char]
getEtcdBinary [Char]
persistenceDir WhichEtcd
EmbeddedEtcd
                ByteString
output <- IO ByteString -> IO ByteString
forall a. IO a -> IO a
retryOnBusyExecutable (IO ByteString -> IO ByteString) -> IO ByteString -> IO ByteString
forall a b. (a -> b) -> a -> b
$ ProcessConfig () () () -> IO ByteString
forall (m :: * -> *) stdin stdoutIgnored stderr.
MonadIO m =>
ProcessConfig stdin stdoutIgnored stderr -> m ByteString
readProcessStdout_ (ProcessConfig () () () -> IO ByteString)
-> ProcessConfig () () () -> IO ByteString
forall a b. (a -> b) -> a -> b
$ [Char] -> [[Char]] -> ProcessConfig () () ()
proc [Char]
executable [[Char]
"--version"]
                ByteString -> [Char]
LBS.unpack ByteString
output [Char] -> [Char] -> IO ()
forall a. (HasCallStack, Show a, Eq a) => [a] -> [a] -> IO ()
`shouldContain` [Char]
"etcd Version:"
        Int -> IO () -> IO ()
forall (m :: * -> *) a. Applicative m => Int -> m a -> m ()
replicateM_ Int
50 IO ()
checkExecutable

  [Char] -> IO () -> SpecWith (Arg (IO ()))
forall a.
(HasCallStack, Example a) =>
[Char] -> a -> SpecWith (Arg a)
it [Char]
"does not retry a missing executable" (IO () -> SpecWith (Arg (IO ())))
-> IO () -> SpecWith (Arg (IO ()))
forall a b. (a -> b) -> a -> b
$
    NominalDiffTime -> IO () -> IO ()
forall (m :: * -> *) a.
(HasCallStack, MonadTimer m, MonadThrow m) =>
NominalDiffTime -> m a -> m a
failAfter NominalDiffTime
10 (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
      [Char] -> ([Char] -> IO ()) -> IO ()
forall (m :: * -> *) r.
(MonadIO m, MonadMask m) =>
[Char] -> ([Char] -> m r) -> m r
withTempDir [Char]
"embedded-etcd-missing" (([Char] -> IO ()) -> IO ()) -> ([Char] -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \[Char]
tmp -> do
        IORef Int
attempts <- Int -> IO (IORef Int)
forall (m :: * -> *) a. MonadIO m => a -> m (IORef a)
newIORef (Int
0 :: Int)
        IO () -> IO ()
forall a. IO a -> IO a
retryOnBusyExecutable
          ( do
              IORef Int -> (Int -> Int) -> IO ()
forall (m :: * -> *) a. MonadIO m => IORef a -> (a -> a) -> m ()
modifyIORef' IORef Int
attempts (Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)
              ProcessConfig () () () -> IO ()
forall (m :: * -> *) stdin stdout stderr.
MonadIO m =>
ProcessConfig stdin stdout stderr -> m ()
runProcess_ (ProcessConfig () () () -> IO ())
-> ProcessConfig () () () -> IO ()
forall a b. (a -> b) -> a -> b
$ [Char] -> [[Char]] -> ProcessConfig () () ()
proc ([Char]
tmp [Char] -> [Char] -> [Char]
</> [Char]
"missing") []
          )
          IO () -> Selector IOException -> IO ()
forall e a.
(HasCallStack, Exception e) =>
IO a -> Selector e -> IO ()
`shouldThrow` Selector IOException
isDoesNotExistError
        IORef Int -> IO Int
forall (m :: * -> *) a. MonadIO m => IORef a -> m a
readIORef IORef Int
attempts IO Int -> Int -> IO ()
forall a. (HasCallStack, Show a, Eq a) => IO a -> a -> IO ()
`shouldReturn` Int
1

  Spec
busyExecutableSpec

busyExecutableSpec :: Spec
#ifdef linux_HOST_OS
busyExecutableSpec :: Spec
busyExecutableSpec = do
  [Char] -> IO () -> SpecWith (Arg (IO ()))
forall a.
(HasCallStack, Example a) =>
[Char] -> a -> SpecWith (Arg a)
it [Char]
"retries a busy executable after the writable descriptor closes" (IO () -> SpecWith (Arg (IO ())))
-> IO () -> SpecWith (Arg (IO ()))
forall a b. (a -> b) -> a -> b
$
    NominalDiffTime -> IO () -> IO ()
forall (m :: * -> *) a.
(HasCallStack, MonadTimer m, MonadThrow m) =>
NominalDiffTime -> m a -> m a
failAfter NominalDiffTime
10 (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
      [Char] -> ([Char] -> IO ()) -> IO ()
forall (m :: * -> *) r.
(MonadIO m, MonadMask m) =>
[Char] -> ([Char] -> m r) -> m r
withTempDir [Char]
"embedded-etcd-busy" (([Char] -> IO ()) -> IO ()) -> ([Char] -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \[Char]
tmp -> do
        [Char]
executable <- [Char] -> WhichEtcd -> IO [Char]
getEtcdBinary [Char]
tmp WhichEtcd
EmbeddedEtcd
        IORef Int
attempts <- Int -> IO (IORef Int)
forall (m :: * -> *) a. MonadIO m => a -> m (IORef a)
newIORef (Int
0 :: Int)
        [Char] -> IOMode -> (Handle -> IO ()) -> IO ()
forall r. [Char] -> IOMode -> (Handle -> IO r) -> IO r
withBinaryFile [Char]
executable IOMode
ReadWriteMode ((Handle -> IO ()) -> IO ()) -> (Handle -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \Handle
writer -> do
          -- The first exec fails deterministically; releasing the descriptor
          -- then models the unrelated child's close-on-exec cleanup.
          ByteString
output <- IO ByteString -> IO ByteString
forall a. IO a -> IO a
retryOnBusyExecutable (IO ByteString -> IO ByteString) -> IO ByteString -> IO ByteString
forall a b. (a -> b) -> a -> b
$ do
            IORef Int -> (Int -> Int) -> IO ()
forall (m :: * -> *) a. MonadIO m => IORef a -> (a -> a) -> m ()
modifyIORef' IORef Int
attempts (Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)
            ProcessConfig () () () -> IO ByteString
forall (m :: * -> *) stdin stdoutIgnored stderr.
MonadIO m =>
ProcessConfig stdin stdoutIgnored stderr -> m ByteString
readProcessStdout_ ([Char] -> [[Char]] -> ProcessConfig () () ()
proc [Char]
executable [[Char]
"--version"])
              IO ByteString -> IO () -> IO ByteString
forall a b. IO a -> IO b -> IO a
forall (m :: * -> *) a b. MonadCatch m => m a -> m b -> m a
`onException` Handle -> IO ()
hClose Handle
writer
          ByteString -> [Char]
LBS.unpack ByteString
output [Char] -> [Char] -> IO ()
forall a. (HasCallStack, Show a, Eq a) => [a] -> [a] -> IO ()
`shouldContain` [Char]
"etcd Version:"
        IORef Int -> IO Int
forall (m :: * -> *) a. MonadIO m => IORef a -> m a
readIORef IORef Int
attempts IO Int -> (Int -> IO ()) -> IO ()
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (Int -> (Int -> Bool) -> IO ()
forall a. (HasCallStack, Show a) => a -> (a -> Bool) -> IO ()
`shouldSatisfy` (Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1))

  [Char] -> IO () -> SpecWith (Arg (IO ()))
forall a.
(HasCallStack, Example a) =>
[Char] -> a -> SpecWith (Arg a)
it [Char]
"stops retrying a persistent busy-executable error" (IO () -> SpecWith (Arg (IO ())))
-> IO () -> SpecWith (Arg (IO ()))
forall a b. (a -> b) -> a -> b
$
    NominalDiffTime -> IO () -> IO ()
forall (m :: * -> *) a.
(HasCallStack, MonadTimer m, MonadThrow m) =>
NominalDiffTime -> m a -> m a
failAfter NominalDiffTime
30 (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
      -- Use a fixed ETXTBSY error to exercise retry exhaustion with constant
      -- work per attempt.
      let busyException :: IOException
busyException = [Char] -> Errno -> Maybe Handle -> Maybe [Char] -> IOException
errnoToIOError [Char]
"startProcess" Errno
eTXTBSY Maybe Handle
forall a. Maybe a
Nothing Maybe [Char]
forall a. Maybe a
Nothing
      IORef Int
attempts <- Int -> IO (IORef Int)
forall (m :: * -> *) a. MonadIO m => a -> m (IORef a)
newIORef (Int
0 :: Int)
      IO Any -> IO Any
forall a. IO a -> IO a
retryOnBusyExecutable
        ( do
            IORef Int -> (Int -> Int) -> IO ()
forall (m :: * -> *) a. MonadIO m => IORef a -> (a -> a) -> m ()
modifyIORef' IORef Int
attempts (Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)
            IOException -> IO Any
forall e a. Exception e => e -> IO a
forall (m :: * -> *) e a. (MonadThrow m, Exception e) => e -> m a
throwIO IOException
busyException
        )
        IO Any -> Selector IOException -> IO ()
forall e a.
(HasCallStack, Exception e) =>
IO a -> Selector e -> IO ()
`shouldThrow` \IOException
exception -> (CInt -> Errno
Errno (CInt -> Errno) -> Maybe CInt -> Maybe Errno
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IOException -> Maybe CInt
ioe_errno IOException
exception) Maybe Errno -> Maybe Errno -> Bool
forall a. Eq a => a -> a -> Bool
== Errno -> Maybe Errno
forall a. a -> Maybe a
Just Errno
eTXTBSY
      IORef Int -> IO Int
forall (m :: * -> *) a. MonadIO m => IORef a -> m a
readIORef IORef Int
attempts IO Int -> Int -> IO ()
forall a. (HasCallStack, Show a, Eq a) => IO a -> a -> IO ()
`shouldReturn` Int
21
#else
busyExecutableSpec = pure ()
#endif