Stack.hs 9.96 KB
Newer Older
1 2 3 4 5 6 7 8
{-# LANGUAGE ScopedTypeVariables,
  LambdaCase,
  RecordWildCards,
  OverloadedStrings,
  DataKinds,
  FlexibleInstances,
  TypeOperators,
  ApplicativeDo #-}
9 10 11 12 13 14 15 16 17 18 19

module Argo.Stack where

import           Data.Default
import           Turtle
import           Prelude                 hiding ( FilePath )

import           System.IO                      ( withFile )
import           Debug.Trace
import           Filesystem.Path                ( (</>) )
import           Control.Concurrent.Async
20
import           System.Console.ANSI
21 22 23 24 25
import           System.Console.ANSI.Types      ( Color )
import           Data.Text                     as Text
                                         hiding ( empty )
import           Data.Text.IO                  as Text
import           Argo.Utils
26 27
import           System.Process                as P
                                         hiding ( shell )
28
import           Options.Applicative           as OA
29
import           Control.Monad.Extra           as E
30 31

data StackArgs = StackArgs
32
  { app                  :: Text
33
  , containerName        :: Text
34 35 36 37 38 39 40 41 42
  , workingDirectory     :: FilePath
  , manifestDir          :: FilePath
  , manifestName         :: FilePath
  , cmd_out              :: FilePath
  , cmd_err              :: FilePath
  , daemon_out           :: FilePath
  , daemon_err           :: FilePath
  , nrm_log              :: FilePath
  , time_file            :: FilePath  }
43 44 45

instance Default StackArgs where
  def = StackArgs
46
    { app = "echo foobar"
47
    , containerName = "testContainer"
48 49 50
    , workingDirectory = "_output"
    , manifestDir = "manifests"
    , manifestName = "basic.json"
51 52 53 54 55 56 57 58
    , cmd_out = "cmd_out.log"
    , cmd_err = "cmd_err.log"
    , daemon_out = "daemon_out.log"
    , daemon_err = "daemon_err.log"
    , nrm_log = "nrm.log"
    , time_file = "time.log"
    }

59 60 61 62
parseExtendStackArgs :: StackArgs -> Parser StackArgs
parseExtendStackArgs StackArgs {..} = do
  app <- strOption
    (  long "application"
63
    <> metavar "APP"
64 65 66 67
    <> help "Target application call, sh+path valid"
    <> showDefault
    <> value app
    )
68 69 70 71 72 73 74
  containerName <- strOption
    (  long "container_name"
    <> metavar "ARGO_CONTAINER_UUID"
    <> help "Container name"
    <> showDefault
    <> value containerName
    )
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
  workingDirectory <- strOption
    (  long "output"
    <> metavar "FILE"
    <> help "Working directory."
    <> showDefault
    <> value workingDirectory
    )
  manifestDir <- strOption
    (  long "manifest_directory"
    <> metavar "FILE"
    <> help "Manifest lookup directory"
    <> showDefault
    <> value manifestDir
    )
  manifestName <- strOption
    (  long "manifest_name"
    <> metavar "FILE"
    <> help "Manifest basename"
    <> showDefault
    <> value manifestName
    )
  cmd_out <- strOption
    (  long "cmd_out"
    <> metavar "FILE"
    <> help "Output file, application stdout"
    <> showDefault
    <> value cmd_out
    )
  cmd_err <- strOption
    (  long "cmd_err"
    <> metavar "FILE"
    <> help "Output file, application stderr"
    <> showDefault
    <> value cmd_err
    )
  daemon_out <- strOption
    (  long "daemon_out"
    <> metavar "FILE"
    <> help "Output file, daemon stdout"
    <> showDefault
    <> value daemon_out
    )
  daemon_err <- strOption
    (  long "daemon_err"
    <> metavar "FILE"
    <> help "Output file, daemon stderr"
    <> showDefault
    <> value daemon_err
    )
  nrm_log <- strOption
    (  long "nrm_log"
    <> metavar "FILE"
    <> help "Output file, daemon log"
    <> showDefault
    <> value nrm_log
    )
  time_file <- strOption
    (  long "time_file"
    <> metavar "FILE"
    <> help "Output file, application runtime"
    <> showDefault
    <> value time_file
    )
  pure StackArgs {..}

140 141 142 143 144 145 146 147 148 149 150 151
cleanLeftoverProcesses :: Shell ()
cleanLeftoverProcesses = do
  printInfo "Cleaning leftover processes.\n"
  daemon <- myWhich "daemon"
  verboseShell (format ("pkill " % fp) daemon) empty
  cmd <- myWhich "cmd"
  void $ verboseShell (format ("pkill " % fp) cmd) empty
  daemon_wrapped <- myWhichMaybe ".daemon-wrapped"
  E.whenJust daemon_wrapped (\x -> void $ verboseShell "pkill .daemon-wrapped" empty)
  cmd_wrapped <- myWhichMaybe ".cmd-wrapped"
  void $ E.whenJust cmd_wrapped (\x -> void $ verboseShell "pkill .cmd-wrapped" empty)

152 153
cleanLeftovers :: StackArgs -> Shell ()
cleanLeftovers StackArgs {..} = do
154 155
  cleanLeftoverProcesses
  printInfo "Cleaning leftover files.\n"
156 157
  mapM_
    cleanLog
158 159 160 161 162 163 164 165
    [ workingDirectory </> daemon_out
    , workingDirectory </> daemon_err
    , workingDirectory </> cmd_out
    , workingDirectory </> cmd_err
    , workingDirectory </> time_file
    , workingDirectory </> nrm_log
    , workingDirectory </> ".argo_nodeos_config_exit_message"
    , workingDirectory </> "argo_nodeos_config"
166
    ]
167
  printInfo "Cleaning leftover sockets.\n"
168 169
  mapM_ cleanSocket ["/tmp/nrm-downstream-in", "/tmp/nrm-upstream-in"]

170 171 172 173 174 175 176 177 178 179
prepareDaemonShell :: StackArgs -> Shell (IO ())
prepareDaemonShell = prepareDaemonShellWithStoppingCriterion id

prepareDaemonShellWithStoppingCriterion
  :: (Shell (Either Line Line) -> Shell (Either Line Line))
  -> StackArgs
  -> Shell (IO ())
prepareDaemonShellWithStoppingCriterion waitCondition StackArgs {..} = do
  mktree workingDirectory
  cd workingDirectory
180
  myWhich "daemon"
181 182
  confPath <- myWhich "argo_nodeos_config"
  let confPath' = "./argo_nodeos_config"
183 184 185
  cp confPath confPath'
  printInfo $ format ("Copied the configurator to " % fp % "\n") confPath'
  printInfo $ format "Trying to sudo chown and chmod argo_nodeos_config\n"
186
  verboseShell (format ("sudo chown root:root " % fp) confPath') empty >>= \case
187 188 189
    ExitSuccess -> printInfo "Chowned argo_nodeos_config to root:root.\n"
    ExitFailure n ->
      die ("Failed to set argo_nodeos_config permissions " <> repr n)
190
  verboseShell (format ("sudo chmod u+sw " % fp) confPath') empty >>= \case
191 192 193 194
    ExitSuccess   -> printInfo "Set the suid bit.\n"
    ExitFailure n -> die ("Setting suid bit failed with exit code " <> repr n)

  --Cleaning the config, running the daemon
195 196
  verboseShell (format (fp % " --clean_config=kill_content:true") confPath')
               empty
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    >>= \case
          ExitSuccess   -> printInfo "Cleaned the argo config.\n"
          ExitFailure n -> do
            printError
              ("argo_nodeos_config failed with exit code :" <> repr n <> "\n")
            testfile ".argo_nodeos_config_exit_message" >>= \case
              True -> do
                printInfo "Contents of .argo_nodeos_config_exit_message: \n"
                view $ input "./argo_nodeos_config_exit_message"
              False -> die ("Clean config failed with exit code " <> repr n)
  printInfo $ format
    ( "Running the daemon, main log at "
    % fp
    % ", stdout at "
    % fp
    % ", stderr at "
    % fp
    % "\n"
    )
    nrm_log
    daemon_out
    daemon_err
  export "ARGO_NODEOS_CONFIG" (format fp confPath')
220
  return $ twoWayPrint daemon_out daemon_err $ waitCondition $ inprocWithErr
221
    "daemon"
222
    ["--nrm_log", Text.pack $ encodeString nrm_log]
223 224 225
    empty

-- | See at the bottom of this file for discussion of this function. (1)
226 227
cmdShell :: StackArgs -> Shell ()
cmdShell StackArgs {..} =
228 229 230
  verboseShell
      (format ("cmd run -u "%s%" " % fp % "  " % s % " > " % fp % " 2>" % fp)
              containerName
231
              (manifestDir </> manifestName)
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
              app
              cmd_out
              cmd_err
      )
      empty
    >>= \case
          ExitSuccess   -> printInfo "cmd has exited successfuly.\n"
          ExitFailure n -> die
            (  "cmd failed with exit code "
            <> repr n
            <> " . The application logs are at "
            <> repr cmd_out
            <> " "
            <> repr cmd_err
            )

twoWayPrint :: FilePath -> FilePath -> Shell (Either Line Line) -> IO ()
twoWayPrint outPath errPath s = sh $ do
  handleOut <- using (writeonly outPath)
  handleErr <- using (writeonly errPath)
  s >>= \case
    Left  out -> liftIO $ Text.hPutStrLn handleOut (lineToText out)
    Right err -> liftIO $ Text.hPutStrLn handleErr (lineToText err)

runSimpleStack :: StackArgs -> IO ()
257 258 259 260 261 262
runSimpleStack = runSimpleStackWithCriterion id

runSimpleStackWithCriterion
  :: (Shell (Either Line Line) -> Shell (Either Line Line))
  -> StackArgs
  -> IO ()
263
runSimpleStackWithCriterion stoppingCriteria a@StackArgs {..} = sh $ do
264
  cleanLeftovers a
265
  daemonShell <- prepareDaemonShellWithStoppingCriterion stoppingCriteria a
266 267
  liftIO $ withAsync daemonShell $ \daemon -> do
    kbInstallHandler $ cancel daemon
268 269 270 271 272
    withAsync (time $ sh $ cmdShell a) $ \cmd -> do
      kbInstallHandler $ cancel daemon >> cancel cmd
      waitEitherCancel daemon cmd >>= \case
        Left  _      -> die "Daemon died."
        Right (_, t) -> writeTextFile time_file (repr t)
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305

-- | (1)
--
-- | This version fucks up the environment variables. issue at
-- https://github.com/Gabriel439/Haskell-Turtle-Library/issues/338
{-cmdShell :: FilePath -> Text -> FilePath -> FilePath -> Shell ()-}
{-cmdShell manifest app cmd_out cmd_err = do-}
  {-manifestArg <- case toText manifest of-}
    {-Left m -> printWarning (format ("Manifest path malformed: " % fp) manifest)-}
      {->> return m-}
    {-Right m -> return m-}
  {-printInfo $ format-}
    {-("Running cmd. Stdout at " % fp % ", stderr at " % fp % "\n")-}
    {-cmd_out-}
    {-cmd_err-}
  {-liftIO $ twoWayPrint cmd_out cmd_err $ inprocWithErr-}
    {-"cmd"-}
    {-["run", "-u", "toto", manifestArg, app]-}
    {-empty-}

-- | Even this one fucks up, streamWithErr really cleans this `env` attribute.

  {-manifestArg <- case toText manifest of-}
    {-Left m -> printWarning (format ("Manifest path malformed: " % fp) manifest)-}
      {->> return m-}
    {-Right m -> return m-}
  {-printInfo $ format-}
    {-("Running cmd. Stdout at " % fp % ", stderr at " % fp % "\n")-}
    {-cmd_out-}
    {-cmd_err-}
  {-theEnv' <- liftIO $ Turtle.env-}
  {-let theEnv = Prelude.map (\(x,y)-> (Text.unpack x,Text.unpack y)) theEnv'-}
  {-void $ liftIO $  twoWayPrint cmd_out cmd_err $ streamWithErr ((P.proc (unpack "cmd") (Prelude.map unpack ["run", "-u", "toto", manifestArg, app])) {P.env=Just theEnv}) empty-}