Stack.hs 9.13 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
module Argo.Stack
15 16 17 18 19 20 21 22 23 24 25 26
  ( cleanLeftovers
  , prepareDaemon
  , cmdRunI
  , cmdListenI
  , cmdListenProgressI
  , cmdListenPerformanceI
  , cmdListenPowerI
  , StackOutput(..)
  , Tracebacks
  , TracebackScanOut(..)
  , TracebackScanErr(..)
  , StackI(..)
27 28 29 30
  , runStack
  )
where

31
import           Argo.Types
Valentin Reis's avatar
Valentin Reis committed
32

Valentin Reis's avatar
Valentin Reis committed
33
import           Data.Coerce                    ( coerce )
34
import           Prelude                 hiding ( FilePath )
Valentin Reis's avatar
Valentin Reis committed
35 36 37 38 39 40 41 42
import           Turtle
import           Turtle.Shell

import           Filesystem.Path                ( (</>) )

import           Control.Concurrent.Async

import           Argo.Utils
43 44
import           Control.Foldl                 as Fold
                                                ( length )
Valentin Reis's avatar
Valentin Reis committed
45 46 47 48
import           Control.Monad                  ( mapM_
                                                , filterM
                                                )
import           Data.Foldable                  ( for_ )
Valentin Reis's avatar
Valentin Reis committed
49
import           Data.Maybe
50 51 52 53 54
import           Data.Text                     as T
                                         hiding ( empty )
import           Data.Traversable               ( for )
import           System.Process                as P
                                         hiding ( shell )
Valentin Reis's avatar
Valentin Reis committed
55 56
import           Text.Show.Pretty

Valentin Reis's avatar
Valentin Reis committed
57
cleanLeftovers :: WorkingDirectory -> Shell () --TODO
Valentin Reis's avatar
Valentin Reis committed
58 59
cleanLeftovers (WorkingDirectory wd) = do
  printInfo "Cleaning sockets."
Valentin Reis's avatar
Valentin Reis committed
60 61 62 63 64
  for_ socklist cleanSocket
  printInfo "Cleaning output directory."
  void $ shell (format ("rm -rf " % fp) wd) Turtle.empty
 where
  socklist =
Valentin Reis's avatar
Valentin Reis committed
65 66 67 68 69
    [ "/tmp/nrm-downstream-in"
    , "/tmp/nrm-downstream-event"
    , "/tmp/nrm-upstream-in"
    , "/tmp/nrm-upstream-event"
    ]
Valentin Reis's avatar
Valentin Reis committed
70 71

prepareDaemon
Valentin Reis's avatar
Valentin Reis committed
72 73 74 75
  :: StdOutLog
  -> StdErrLog
  -> Maybe TestText
  -> Verbosity
76
  -> PowerCap
Valentin Reis's avatar
Valentin Reis committed
77
  -> Shell Instrumentation
78
prepareDaemon out stdErr test v powercap = do
Valentin Reis's avatar
Valentin Reis committed
79
  let confPath' = "/tmp/argo_nodeos_config"
80
  cleanContainers confPath'
Valentin Reis's avatar
Valentin Reis committed
81
  export "ARGO_NODEOS_CONFIG" (format fp confPath')
82 83 84 85 86 87 88
  return $ Instrumentation
    (P.proc "daemon"
            (["--nrm_log", "./nrm_log"] ++ toOption v ++ toOption powercap)
    )
    out
    stdErr
    test
Valentin Reis's avatar
Valentin Reis committed
89 90 91 92 93 94 95 96
 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)
97 98
  cleanContainers :: FilePath -> Shell ()
  cleanContainers argo_nodeos_config =
Valentin Reis's avatar
Valentin Reis committed
99
    verboseShell'
100 101 102 103 104 105 106
        (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
107 108 109 110 111

cmdRunI
  :: AppName
  -> [AppArg]
  -> ContainerName
Valentin Reis's avatar
adding  
Valentin Reis committed
112
  -> ShareDir
Valentin Reis's avatar
Valentin Reis committed
113
  -> ManifestName
114
  -> [(EnvVar, Text)]
Valentin Reis's avatar
Valentin Reis committed
115 116
  -> ProcessBehavior
  -> Maybe (StackI, Instrumentation)
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
cmdRunI (AppName app) args (ContainerName cn) (ShareDir md) (ManifestName mn) vars pb
  = Just (Run, ) <*> processBehaviorToI (pp { P.env = Just $ cast <$> vars }) pb
 where
  argToText (AppArg a) = a
  cast :: (EnvVar, Text) -> (String, String)
  cast (EnvVar v, y) = (T.unpack v, T.unpack y)
  pp =
    P.proc "cmd"
      $  [ "run"
         , "-u"
         , T.unpack cn
         , encodeString $ md <> "manifests" </> mn
         , T.unpack app
         ]
      ++ fmap (T.unpack . argToText) args
Valentin Reis's avatar
Valentin Reis committed
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 175 176 177 178 179 180 181 182

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
183
runStack sa@StackArgs {..} = do
Valentin Reis's avatar
Style.  
Valentin Reis committed
184
  when verbose $ liftIO $ pPrint sa
Valentin Reis's avatar
Valentin Reis committed
185

186 187
  when (powercap /= None) $ do
    user <- lineToText <$> single (inproc "whoami" [] empty)
Valentin Reis's avatar
Valentin Reis committed
188 189 190 191
    chownPowercapFiles user
                       "/sys/devices/virtual/powercap/intel-rapl/intel-rapl:0"
    chownPowercapFiles user
                       "/sys/devices/virtual/powercap/intel-rapl/intel-rapl:1"
192

Valentin Reis's avatar
Valentin Reis committed
193
  cleanLeftovers workingDirectory
Valentin Reis's avatar
Valentin Reis committed
194
  mapM_ ($ coerce workingDirectory) [mktree, cd]
Valentin Reis's avatar
Valentin Reis committed
195 196 197 198

  iDaemon <- case daemon of
    DontRun -> return Nothing
    JustRun stdOut stdErr ->
199 200
      (\i -> Just (Daemon, i))
        <$> prepareDaemon stdOut stdErr Nothing verbosity powercap
Valentin Reis's avatar
Valentin Reis committed
201
    Test t stdOut stdErr ->
202 203
      (\i -> Just (Daemon, i))
        <$> prepareDaemon stdOut stdErr (Just t) Verbose powercap
Valentin Reis's avatar
Valentin Reis committed
204 205 206

  let milist =
        [ iDaemon
207
        , cmdRunI app args containerName shareDir manifestName vars cmdrun
Valentin Reis's avatar
Valentin Reis committed
208 209 210 211 212 213 214
        , cmdListenI containerName cmdlisten
        , cmdListenPerformanceI containerName cmdlistenperformance
        , cmdListenProgressI containerName cmdlistenprogress
        , cmdListenPowerI containerName cmdlistenpower
        ]
      ilist = catMaybes milist

Valentin Reis's avatar
Valentin Reis committed
215
  _ <- shell (coerce preludeCommand :: Text) empty >>= \case
Valentin Reis's avatar
Style.  
Valentin Reis committed
216
    ExitSuccess -> when verbose
Valentin Reis's avatar
Valentin Reis committed
217 218 219
      $ printInfo ("Executed preludeCommand." <> repr preludeCommand)
    ExitFailure _ ->
      die ("failed to execute preludeCommand." <> repr preludeCommand)
Valentin Reis's avatar
Valentin Reis committed
220

Valentin Reis's avatar
Style.  
Valentin Reis committed
221 222 223
  when verbose $ do
    printInfo "Starting the following processes:"
    liftIO $ pPrint ilist
Valentin Reis's avatar
Valentin Reis committed
224

Valentin Reis's avatar
Valentin Reis committed
225 226
  asyncs <- liftIO $ for ilist tupleToAsync
  _      <- liftIO $ kbInstallHandler $ for_ asyncs cancel
Valentin Reis's avatar
Valentin Reis committed
227

Valentin Reis's avatar
Style.  
Valentin Reis committed
228
  when verbose $ printInfo "Processes started."
Valentin Reis's avatar
Valentin Reis committed
229 230 231 232 233 234 235 236 237 238 239 240

  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
241
  r             <- case snd out of
Valentin Reis's avatar
Valentin Reis committed
242 243 244 245 246 247 248 249 250 251 252 253 254
    (_, 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
255 256 257
  chownPowercap user fn =
    shell (format ("sudo chown " % s % ":" % s % " " % s) user user fn) empty
      >>= \case
Valentin Reis's avatar
Valentin Reis committed
258 259
            ExitSuccess   -> printWarning $ "changed ownership on " <> fn
            ExitFailure _ -> die $ "Couldn't change ownership on " <> fn
260 261 262 263 264

  chownPowercapFiles user p =
    chownPowercap user (p <> "/constraint_1_power_limit_uw")
      <> chownPowercap user (p <> "/constraint_0_power_limit_uw")

265
  verbose = verbosity == Verbose
Valentin Reis's avatar
Valentin Reis committed
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
  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