Stack.hs 8.05 KB
Newer Older
Valentin Reis's avatar
Style.  
Valentin Reis committed
1 2 3 4
{-# language TupleSections #-}
{-# language LambdaCase #-}
{-# language RecordWildCards #-}
{-# language OverloadedStrings #-}
Valentin Reis's avatar
Valentin Reis committed
5

Valentin Reis's avatar
Valentin Reis committed
6 7 8 9 10 11 12 13
{-|
Module      : Argo.Stack
Description : Argo stack library
Copyright   : (c) Valentin Reis, 2018
License     : MIT
Maintainer  : fre@freux.fr
-}

14 15 16 17 18 19 20
module Argo.Stack
  ( StackOutput(..)
  , cleanLeftovers
  , runStack
  )
where

21
import           Argo.Types
Valentin Reis's avatar
Valentin Reis committed
22

Valentin Reis's avatar
Valentin Reis committed
23
import           Data.Coerce                    ( coerce )
Valentin Reis's avatar
Valentin Reis committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
import           Turtle
import           Turtle.Shell
import           Prelude                 hiding ( FilePath )

import           Filesystem.Path                ( (</>) )

import           Control.Concurrent.Async

import           Data.Text                     as T
                                         hiding ( empty )
import           Argo.Utils
import           System.Process                as P
                                         hiding ( shell )
import           Control.Monad                 as CM
import           Data.Maybe
import           Control.Foldl                 as Fold
import           Text.Show.Pretty

Valentin Reis's avatar
Valentin Reis committed
42
cleanLeftovers :: WorkingDirectory -> Shell () --TODO
Valentin Reis's avatar
Valentin Reis committed
43 44
cleanLeftovers (WorkingDirectory wd) = do
  printInfo "Cleaning sockets."
Valentin Reis's avatar
Valentin Reis committed
45 46 47 48 49 50 51 52 53
  CM.mapM_
    cleanSocket
    [ "/tmp/nrm-downstream-in"
    , "/tmp/nrm-downstream-event"
    , "/tmp/nrm-upstream-in"
    , "/tmp/nrm-upstream-event"
    ]
  printInfo "Cleaning output directory."
  void $ shell (format ("rm -rf " % fp) wd) Turtle.empty
Valentin Reis's avatar
Valentin Reis committed
54 55

prepareDaemon
Valentin Reis's avatar
Valentin Reis committed
56 57 58 59
  :: StdOutLog
  -> StdErrLog
  -> Maybe TestText
  -> Verbosity
60
  -> PowerCap
Valentin Reis's avatar
Valentin Reis committed
61
  -> Shell Instrumentation
62
prepareDaemon out stdErr test v powercap = do
63
  daemonPath <- myWhich "daemon"
Valentin Reis's avatar
Valentin Reis committed
64
  let confPath' = "/tmp/argo_nodeos_config"
65
  cleanContainers confPath'
Valentin Reis's avatar
Valentin Reis committed
66
  export "ARGO_NODEOS_CONFIG" (format fp confPath')
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
  return $ case powercap of
    None -> Instrumentation
      (P.proc "daemon" (["--nrm_log", "./nrm_log"] ++ toOption v))
      out
      stdErr
      test
    _ -> Instrumentation
      (P.proc
        "sudo"
        (  [encodeString daemonPath, "--nrm_log", "./nrm_log"]
        ++ toOption v
        ++ toOption powercap
        )
      )
      out
      stdErr
      test
Valentin Reis's avatar
Valentin Reis committed
84 85 86 87 88 89 90 91
 where
  nodeOsFailure n = do
    printError ("argo_nodeos_config failed with exit code :" <> repr n)
    testfile ".argo_nodeos_config_exit_message" >>= \case
      True -> do
        printInfo "Contents of .argo_nodeos_config_exit_message: "
        view $ input ".argo_nodeos_config_exit_message"
      False -> die ("argo_nodeos_config failed with exit code " <> repr n)
92 93
  cleanContainers :: FilePath -> Shell ()
  cleanContainers argo_nodeos_config =
Valentin Reis's avatar
Valentin Reis committed
94
    verboseShell'
95 96 97 98 99 100
      (format ("sudo" % fp % " --clean_config=kill_content:true")
              argo_nodeos_config
      )
      empty >>= \case
        (ExitFailure n,_,_) -> nodeOsFailure n
        (ExitSuccess,_,_) -> return ()
Valentin Reis's avatar
Valentin Reis committed
101 102 103 104 105

cmdRunI
  :: AppName
  -> [AppArg]
  -> ContainerName
Valentin Reis's avatar
adding  
Valentin Reis committed
106
  -> ShareDir
Valentin Reis's avatar
Valentin Reis committed
107 108 109
  -> ManifestName
  -> ProcessBehavior
  -> Maybe (StackI, Instrumentation)
Valentin Reis's avatar
adding  
Valentin Reis committed
110
cmdRunI (AppName app) args (ContainerName cn) (ShareDir md) (ManifestName mn) pb
Valentin Reis's avatar
Valentin Reis committed
111 112 113
  = Just (Run, )
    <*> processBehaviorToI
          (  P.proc "cmd"
Valentin Reis's avatar
Valentin Reis committed
114 115 116 117 118 119
          $  [ "run"
             , "-u"
             , T.unpack cn
             , encodeString $ md <> "manifests" </> mn
             , T.unpack app
             ]
Valentin Reis's avatar
Valentin Reis committed
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
          ++ fmap (T.unpack . argToText) args
          )
          pb
  where argToText (AppArg a) = a

cmdListenI
  :: ContainerName -> ProcessBehavior -> Maybe (StackI, Instrumentation)
cmdListenI (ContainerName cn) pb =
  Just (Listen, )
    <*> processBehaviorToI (P.proc "cmd" ["listen", "-u", T.unpack cn]) pb

cmdListenProgressI
  :: ContainerName -> ProcessBehavior -> Maybe (StackI, Instrumentation)
cmdListenProgressI (ContainerName cn) pb =
  Just (Progress, )
    <*> processBehaviorToI
          (P.proc "cmd" ["listen", "-u", T.unpack cn, "--filter", "progress"])
          pb

cmdListenPerformanceI
  :: ContainerName -> ProcessBehavior -> Maybe (StackI, Instrumentation)
cmdListenPerformanceI (ContainerName cn) pb =
  Just (Performance, )
    <*> processBehaviorToI
          (P.proc "cmd" ["listen", "-u", T.unpack cn, "--filter", "performance"]
          )
          pb

cmdListenPowerI
  :: ContainerName -> ProcessBehavior -> Maybe (StackI, Instrumentation)
cmdListenPowerI (ContainerName cn) pb =
  Just (Power, )
    <*> processBehaviorToI
          (P.proc "cmd" ["listen", "-u", T.unpack cn, "--filter", "power"])
          pb

data StackOutput =
    FoundMessage Text
  | FoundTracebacks Tracebacks
  | Died StackI ExitCode TracebackScanOut TracebackScanErr Tracebacks deriving (Show)
type Tracebacks = [(StackI, Text, Text)]
newtype TracebackScanOut = TracebackScanOut TracebackScan deriving (Show)
newtype TracebackScanErr = TracebackScanErr TracebackScan deriving (Show)

data StackI = Daemon | Run | Listen | Progress | Power | Performance deriving (Eq)
instance Show StackI where
  show = \case
    Daemon -> "daemon"
    Run -> "cmd run"
    Listen -> "cmd listen -v"
    Progress -> "cmd listen -f progress"
    Power -> "cmd listen -f power"
    Performance -> "cmd listen -f performance"

runStack :: StackArgs -> Shell StackOutput
175
runStack sa@StackArgs {..} = do
Valentin Reis's avatar
Style.  
Valentin Reis committed
176
  when verbose $ liftIO $ pPrint sa
Valentin Reis's avatar
Valentin Reis committed
177

Valentin Reis's avatar
Valentin Reis committed
178
  cleanLeftovers workingDirectory
179
  CM.mapM_ ($ coerce workingDirectory) [mktree, cd]
Valentin Reis's avatar
Valentin Reis committed
180 181 182 183

  iDaemon <- case daemon of
    DontRun -> return Nothing
    JustRun stdOut stdErr ->
184 185
      (\i -> Just (Daemon, i))
        <$> prepareDaemon stdOut stdErr Nothing verbosity powercap
Valentin Reis's avatar
Valentin Reis committed
186
    Test t stdOut stdErr ->
187 188
      (\i -> Just (Daemon, i))
        <$> prepareDaemon stdOut stdErr (Just t) Verbose powercap
Valentin Reis's avatar
Valentin Reis committed
189 190 191

  let milist =
        [ iDaemon
Valentin Reis's avatar
adding  
Valentin Reis committed
192
        , cmdRunI app args containerName shareDir manifestName cmdrun
Valentin Reis's avatar
Valentin Reis committed
193 194 195 196 197 198 199
        , cmdListenI containerName cmdlisten
        , cmdListenPerformanceI containerName cmdlistenperformance
        , cmdListenProgressI containerName cmdlistenprogress
        , cmdListenPowerI containerName cmdlistenpower
        ]
      ilist = catMaybes milist

Valentin Reis's avatar
Valentin Reis committed
200
  _ <- shell (coerce preludeCommand :: Text) empty >>= \case
Valentin Reis's avatar
Style.  
Valentin Reis committed
201
    ExitSuccess -> when verbose
Valentin Reis's avatar
Valentin Reis committed
202 203 204
      $ printInfo ("Executed preludeCommand." <> repr preludeCommand)
    ExitFailure _ ->
      die ("failed to execute preludeCommand." <> repr preludeCommand)
Valentin Reis's avatar
Valentin Reis committed
205

Valentin Reis's avatar
Style.  
Valentin Reis committed
206 207 208
  when verbose $ do
    printInfo "Starting the following processes:"
    liftIO $ pPrint ilist
Valentin Reis's avatar
Valentin Reis committed
209 210 211 212

  asyncs <- liftIO $ mapM tupleToAsync ilist
  _      <- liftIO $ kbInstallHandler $ CM.mapM_ cancel asyncs

Valentin Reis's avatar
Style.  
Valentin Reis committed
213
  when verbose $ printInfo "Processes started."
Valentin Reis's avatar
Valentin Reis committed
214 215 216 217 218 219 220 221 222 223 224 225

  out <- liftIO $ waitAnyCancel asyncs

  printInfo
    (  "Processes cancelled due to termination of: "
    <> repr (fst $ snd out)
    <> " with exit information: "
    <> repr (snd $ snd out)
    )

  tracebackList <- procsWithTracebacks ilist

Valentin Reis's avatar
Valentin Reis committed
226
  r             <- case snd out of
Valentin Reis's avatar
Valentin Reis committed
227 228 229 230 231 232 233 234 235 236 237 238 239
    (_, Left (PatternMatched line)) -> case tracebackList of
      [] -> return $ FoundMessage line
      t  -> return $ FoundTracebacks t
    (stacki, Right (errmsg, tracebackOut, tracebackErr)) -> return $ Died
      stacki
      errmsg
      (TracebackScanOut tracebackOut)
      (TracebackScanErr tracebackErr)
      tracebackList

  cd "../"
  return r
 where
240
  verbose = verbosity == Verbose
Valentin Reis's avatar
Valentin Reis committed
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
  procsWithTracebacks
    :: [(StackI, Instrumentation)] -> Shell [(StackI, Text, Text)]
  procsWithTracebacks ilist = fmap showOutputs <$> filterM (checkI . snd) ilist

  showOutputs :: (StackI, Instrumentation) -> (StackI, Text, Text)
  showOutputs (si, Instrumentation _ (StdOutLog outlog) (StdErrLog errlog) _) =
    (si, outlog, errlog)

  checkI :: Instrumentation -> Shell Bool
  checkI (Instrumentation _ (StdOutLog outlog) (StdErrLog errlog) _) = do
    b <- liftIO $ Turtle.Shell.fold
      (grep (has "Traceback") (input $ fromText outlog))
      Fold.length
    c <- liftIO $ Turtle.Shell.fold
      (grep (has "Traceback") (input $ fromText errlog))
      Fold.length
    return $ (b > 0) || (c > 0)

  tupleToAsync
    :: (StackI, Instrumentation)
    -> IO
         ( Async
             ( StackI
             , Either
                 MonitoringResult
                 (ExitCode, TracebackScan, TracebackScan)
             )
         )
  tupleToAsync (stacki, instrum) = async $ (stacki, ) <$> runI instrum