Argonix.hs 13.3 KB
Newer Older
Valentin Reis's avatar
Valentin Reis committed
1 2
{-# language RecordWildCards #-}
{-# language ApplicativeDo #-}
Valentin Reis's avatar
Valentin Reis committed
3
{-# language LambdaCase #-}
Valentin Reis's avatar
Valentin Reis committed
4 5
{-# language OverloadedStrings #-}

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

Valentin Reis's avatar
Valentin Reis committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26
module Main where

import           Data.Default
import           Turtle                  hiding ( header
                                                , text
                                                , arguments
                                                )
import           Options.Applicative
import           Data.Maybe
import           Prelude                 hiding ( FilePath )

import           Data.Text                      ( pack
                                                , unpack
                                                )
Valentin Reis's avatar
Valentin Reis committed
27 28 29 30
import           System.Console.ANSI
import           System.Console.ANSI.Types      ( Color )
import           Turtle.Shell
import           Control.Foldl
Valentin Reis's avatar
Valentin Reis committed
31 32
import           System.Posix.Process

Valentin Reis's avatar
Valentin Reis committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
-- | Miscellaneous printing utilities
colorShell :: Color -> Shell () -> Shell ()
colorShell color she = setC color *> she *> setC White
  where setC c = liftIO $ setSGR [SetColor Foreground Dull c]
verboseShell :: Text -> Shell Line -> Shell ExitCode
verboseShell c i = printCommand c >> shell c i
printInfo :: Text -> Shell ()
printCommand :: Text -> Shell ()
printError :: Text -> Shell ()
printWarning :: Text -> Shell ()
printSuccess :: Text -> Shell ()
printTest :: Text -> Shell ()
dieRed :: Text -> Shell ()

printInfo = printf ("Info: " % s % "\n")
printCommand = printf ("Running: " % s % "\n")
printWarning = colorShell Yellow . printf ("Warning: " % s % "\n")
printError = colorShell Red . printf ("Error: " % s % "\n")
printSuccess = colorShell Green . printf ("Success: " % s % "\n")
printTest = colorShell Green . printf ("RUNNING TEST: " % s % "\n")
dieRed strw =
  colorShell Red (printf ("Failure: " % s) strw) >> exit (ExitFailure 1)
Valentin Reis's avatar
Valentin Reis committed
55

56 57 58 59 60 61
checkFsAttributes :: FilePath -> Shell ()
checkFsAttributes workingDirectory = do
  let dir = case toText workingDirectory of
        Left  di -> di
        Right di -> di
  let findmnt = inproc "findmnt" ["-T", dir, "-o", "OPTIONS"] empty
Valentin Reis's avatar
Valentin Reis committed
62 63
  b <- liftIO
    $ Turtle.Shell.fold (grep (has "nosuid") findmnt) Control.Foldl.length
64 65 66 67 68 69 70 71 72 73 74
  when (b > 0) $ die $ format
    ("The output directory, " % fp % ", must not mounted with \"nosuid\"")
    workingDirectory

main :: IO ()
main = join $ execParser (info (opts <**> helper) idm)
 where
  opts :: Parser (IO ())
  opts = hsubparser
    (  command
        "build"
Valentin Reis's avatar
Valentin Reis committed
75
        (info (wrap NixBuild <$> targetParser <*> executorParser)
76 77 78
              (progDesc "Run an argo-compatible nix-build.")
        )
    <> command
Valentin Reis's avatar
Valentin Reis committed
79
         "shell"
Valentin Reis's avatar
Valentin Reis committed
80
         (info (wrap NixShell <$> targetParser <*> executorParser)
Valentin Reis's avatar
Valentin Reis committed
81
               (progDesc "Enter an argo-compatable nix-shell")
82 83 84 85
         )
    <> help "Type of operation to run."
    )

Valentin Reis's avatar
Valentin Reis committed
86
data StackArgs = StackArgs
Valentin Reis's avatar
Valentin Reis committed
87 88 89
  {
    argopkgs      :: Text
   , verbosity     :: Verbosity
Valentin Reis's avatar
Valentin Reis committed
90 91 92 93 94 95
   , enableApps    :: Bool
   , remoteBuild   :: Bool
   , targetMachine :: Maybe Text
   , retreive      :: Maybe Text
   , retreiveAs    :: Maybe Text
   , run           :: Maybe Text
Valentin Reis's avatar
Valentin Reis committed
96
   , overrides     :: [(String, String)]
Valentin Reis's avatar
Valentin Reis committed
97 98 99 100 101
  } deriving (Show)
data Verbosity = Verbose | Normal deriving (Show)

instance Default StackArgs where
  def = StackArgs
Valentin Reis's avatar
Valentin Reis committed
102 103
    { verbosity = Normal,
      argopkgs = "<argopkgs>",
Valentin Reis's avatar
Valentin Reis committed
104 105 106 107 108 109 110 111 112
      enableApps = False,
      remoteBuild = False,
      run = Nothing,
      targetMachine = Nothing,
      retreive = Nothing,
      retreiveAs = Nothing,
      overrides = []
    }

113 114 115 116
targetParser :: Parser String
targetParser =
  strArgument (metavar "TARGET" <> showDefault <> help "The build target.")

Valentin Reis's avatar
Valentin Reis committed
117 118
executorParser :: Parser StackArgs
executorParser = do
Valentin Reis's avatar
Valentin Reis committed
119 120 121 122 123 124 125
  argopkgs <- strOption
    (  long "argopkgs"
    <> metavar "ARGOPKGS"
    <> showDefault
    <> value (argopkgs def)
    <> help "Nix expression that produces the argopkgs source path."
    )
Valentin Reis's avatar
Valentin Reis committed
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
  verbosity <- flag
    Normal
    Verbose
    (long "verbose" <> short 'v' <> help "Enable verbose mode")
  enableApps <- flag
    False
    True
    (long "provision_apps" <> short 'a' <> help
      "Build and provision applications."
    )
  remoteBuild <- flag
    False
    True
    (long "remote_build" <> short 'r' <> help
      "Build on the remote rather than locally."
    )
  retreive <- optional $ strOption
    (long "retreive" <> metavar "RELATIVE_PATH" <> help
      "File/Folder to retreive from the remote machine."
    )
  retreiveAs <- optional $ strOption
    (long "retreiveAs" <> metavar "LOCAL_PATH" <> help
      "File/Folder to save retreived data as (locally)."
    )
  targetMachine <- optional $ strOption
    (long "target_machine" <> metavar "USER@HOST" <> help
      "Target machine. defaults to localhost via forking."
    )
Valentin Reis's avatar
Valentin Reis committed
154
  overrides <- catMaybes <$> targets
Valentin Reis's avatar
Valentin Reis committed
155 156 157 158 159 160
  run       <- optional $ strOption
    (long "run" <> metavar "COMMAND" <> help
      "Command to run the environment instead of an interactive shell"
    )
  pure StackArgs {..}
 where
Valentin Reis's avatar
Valentin Reis committed
161 162
  targets :: Parser [Maybe (String, String)]
  targets = traverse
Valentin Reis's avatar
Valentin Reis committed
163
    optSrc
Valentin Reis's avatar
Valentin Reis committed
164 165
    [ "aml"
    , "libnrm"
Valentin Reis's avatar
Valentin Reis committed
166 167
    , "nrm"
    , "containers"
Valentin Reis's avatar
Valentin Reis committed
168
    , "argotk"
Valentin Reis's avatar
Valentin Reis committed
169 170 171 172
    , "amg"
    , "lammps"
    , "qmcpack"
    , "stream"
Valentin Reis's avatar
Valentin Reis committed
173
    , "openmc"
Valentin Reis's avatar
Valentin Reis committed
174
    ]
Valentin Reis's avatar
Valentin Reis committed
175
  optSrc :: String -> Parser (Maybe (String, String))
Valentin Reis's avatar
Valentin Reis committed
176 177 178 179 180 181
  optSrc longform = do
    parsed <- optional $ strOption
      (long longform <> metavar "PATH" <> help
        (longform <> " source folder override.")
      )
    pure $ mapT longform parsed
Valentin Reis's avatar
Valentin Reis committed
182
  mapT :: String -> Maybe String -> Maybe (String, String)
Valentin Reis's avatar
Valentin Reis committed
183 184 185 186
  mapT longform thePath = case thePath of
    Nothing -> Nothing
    Just p  -> Just (longform, p)

Valentin Reis's avatar
Valentin Reis committed
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
sudoRemoveFile :: (Text -> Shell ()) -> Text -> FilePath -> Shell ()
sudoRemoveFile printer desc filePath = do
  foundSocket <- testfile filePath
  when foundSocket $ go False
  printInfo $ format ("OK: " % s % " " % fp) desc filePath
 where
  go useSudo = do
    printer $ format ("found file " % s % " at " % fp % ".. ") desc filePath
    shell
        (format ((if useSudo then "sudo " else "") % "rm -rf " % fp) filePath)
        Turtle.empty
      >>= \case
            ExitSuccess -> colorShell Green $ printf " Successfully removed.\n"
            ExitFailure _ -> if useSudo
              then printer $ format
                ("Failed to remove file " % s % ", even with sudo.")
                desc
              else do
                printer $ format
                  ("Failed to remove file " % s % ". Trying sudo..\n")
                  desc
                go True

cleanSocket :: FilePath -> Shell ()
cleanSocket = sudoRemoveFile printWarning "socket"
212

Valentin Reis's avatar
Valentin Reis committed
213 214
setupSystem :: StackArgs -> Shell ()
setupSystem sa = do
Valentin Reis's avatar
Valentin Reis committed
215 216 217 218 219 220 221 222 223 224 225 226
  printInfo "Setting the nix-build environment up."
  printInfo "Cleaning sockets."
  Prelude.mapM_
    cleanSocket
    [ "/tmp/nrm-downstream-in"
    , "/tmp/nrm-downstream-event"
    , "/tmp/nrm-upstream-in"
    , "/tmp/nrm-upstream-event"
    ]
  printInfo "Setting up a cache directory:"
  cachedir <- single
    $ inproc "mktemp" ["-d", "/tmp/deletable-nix-cache-XXXX"] empty
227
  export "XDG_CACHE_HOME" $ lineToText cachedir
Valentin Reis's avatar
Valentin Reis committed
228 229
  printInfo $ lineToText cachedir <> " exported to XDG_CACHE_HOME"
  printInfo "running nix-build for the containers attribute."
Valentin Reis's avatar
Valentin Reis committed
230
  printCommand $ "nix-build " <> pack (unwords (nixArguments "containers" sa))
Valentin Reis's avatar
Valentin Reis committed
231 232 233
  nodeos_config <- single
    $ inproc "nix-build" (fmap pack (nixArguments "containers" sa)) empty
  printInfo "Checking filesystem attributes on /tmp"
234
  checkFsAttributes "/tmp"
Valentin Reis's avatar
Valentin Reis committed
235 236 237 238 239 240 241 242 243 244 245 246 247
  verboseShell "sudo rm -rf /tmp/argo_nodeos_config" empty
  verboseShell
    (format ("cp " % s % "/bin/argo_nodeos_config /tmp/argo_nodeos_config")
            (lineToText nodeos_config)
    )
    empty
  verboseShell "sudo chown root:root /tmp/argo_nodeos_config" empty >>= \case
    ExitSuccess -> return ()
    ExitFailure n ->
      die ("Failed to set argo_nodeos_config permissions " <> repr n)
  verboseShell "sudo chmod u+sw /tmp/argo_nodeos_config" empty >>= \case
    ExitSuccess   -> return ()
    ExitFailure n -> die ("Setting suid bit failed with exit code " <> repr n)
Valentin Reis's avatar
Valentin Reis committed
248 249
  verboseShell "sudo /tmp/argo_nodeos_config --clean_config=kill_content:true"
               empty
Valentin Reis's avatar
Valentin Reis committed
250
  void $ printInfo "Done setting the environment for nix-build up."
251 252 253

nixArguments :: String -> StackArgs -> [String]
nixArguments target StackArgs {..} = [unpack argopkgs, "-A", target] ++ concat
Valentin Reis's avatar
Valentin Reis committed
254
  [ ["--arg", longform <> "-src", p] | (longform, p) <- overrides ]
255

Valentin Reis's avatar
Valentin Reis committed
256 257 258 259 260 261 262
data NixCommand = NixBuild | NixShell
toCommand :: IsString p => NixCommand -> p
toCommand NixBuild = "nix-build"
toCommand NixShell = "nix-shell"

wrap :: NixCommand -> String -> StackArgs -> IO ()
wrap nixCommand target sa@StackArgs {..} = sh $ do
Valentin Reis's avatar
Valentin Reis committed
263
  _ <- setupSystem sa
Valentin Reis's avatar
Valentin Reis committed
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
  printCommand $ pack nixc <> " " <> pack (unwords arglist)
  liftIO (executeFile nixc True arglist Nothing)
 where
  nixc = toCommand nixCommand
-- Sources of impurity for this build are: "/tmp/ /etc/argo/ /var/run/
-- /var/lock/. Moreover, sandboxing is disabled, in particular because of:
-- /tmp/nrm-* sockets, /etc/argo, /var/run/, /var/lock/ which all need read
-- access.  until these components are patched to allow for alternative paths,
-- no sandbox use is possible. If sandbox paths were read only we could add:
   {-, "--option"-}
   {-, "build-use-sandbox"-}
   {-, "--option"-}
   {-, "extra-sandbox-paths"-}
   {-, "/tmp/ /etc/argo/ /var/run/ /var/lock/"-}
  arglist =
    nixArguments target sa
      ++ [ "--pure"
         , "--allow-new-privileges"
         , "-K"
         , "--option"
         , "build-use-sandbox"
         , "false"
         ]
287

Valentin Reis's avatar
Valentin Reis committed
288 289
{-nixshell :: IO ()-}
{-nixshell = undefined-}
Valentin Reis's avatar
Valentin Reis committed
290
  {-StackArgs {..} <- liftIO $ execParser opts-}
Valentin Reis's avatar
Valentin Reis committed
291

Valentin Reis's avatar
Valentin Reis committed
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
  {--- building nixArguments (pure stuff) and shellArguments (impure stuff)-}
  {-let nixArguments = ["-A", if enableApps then "expe" else "test"] ++ concat-}
        {-[ ["--arg", longform <> "-src", encodeString p]-}
        {-| (longform, p) <- overrides-}
        {-]-}
  {-sudo <- which "sudo" >>= \case-}
    {-(Just sudo) -> printf ("Found sudo at " % fp % "\n") sudo >> return sudo-}
    {-Nothing     -> die "sudo not in $PATH."-}
  {-export "SUDO" $ pack $ encodeString sudo-}
  {-let shellArguments =-}
        {-[unpack argopkgs]-}
          {-++ [ "--keep"-}
             {-, "SUDO"-}
             {-, "--pure"-}
             {-, "--allow-new-privileges"-}
             {-, "--option"-}
             {-, "build-extra-sandbox-paths"-}
             {-, encodeString (directory sudo)-}
             {-]-}
          {-++ nixArguments-}
          {-++ (case run of-}
               {-Just cmd -> ["--run", unpack ("\"exec " <> cmd <> "\"")]-}
               {-Nothing  -> []-}
             {-)-}
Valentin Reis's avatar
Valentin Reis committed
316

Valentin Reis's avatar
Valentin Reis committed
317 318 319 320 321 322 323 324 325 326 327 328 329
  {-cachedir <- single $ inproc-}
    {-"mktemp"-}
    {-["-d", "--suffix=nixcache", "/tmp/deletable-nix-cache-XXXX"]-}
    {-empty-}
  {-export "XDG_CACHE_HOME" $ lineToText cachedir-}
  {-case targetMachine of-}
    {-Nothing -> do-}
      {-printf s "Running nix-shell with the following arguments: \n"-}
      {-liftIO $ print shellArguments-}
      {-liftIO $ executeFile "nix-shell" True shellArguments Nothing-}
    {-Just host -> do-}
      {-export "NIX_SSHOPTS" "source .profile; source .bash_profile;"-}
      {-printf s "argonix: creating a derivation in the local store:\n"-}
Valentin Reis's avatar
Valentin Reis committed
330

Valentin Reis's avatar
Valentin Reis committed
331 332 333 334
      {-drv <- single $ inproc-}
        {-"nix-instantiate"-}
        {-(["--quiet", argopkgs, "-A", "test"] ++ fmap pack nixArguments)-}
        {-empty-}
Valentin Reis's avatar
Valentin Reis committed
335

Valentin Reis's avatar
Valentin Reis committed
336
      {-printf (s % "\n") $ lineToText drv-}
Valentin Reis's avatar
Valentin Reis committed
337

Valentin Reis's avatar
Valentin Reis committed
338 339 340 341 342 343 344 345 346
      {-if remoteBuild-}
        {-then do-}
          {-printf-}
            {-s-}
            {-"argonix: copying the derivation's closure (without build output).\n"-}
          {-proc "nix-copy-closure" ["--to", host, lineToText drv] empty-}
        {-else do-}
          {-printf s "argonix: building the derivation's output:\n"-}
          {-proc "nix-store" ["--realize", lineToText drv, "--quiet"] empty-}
Valentin Reis's avatar
Valentin Reis committed
347

Valentin Reis's avatar
Valentin Reis committed
348 349 350 351 352 353
          {-printf-}
            {-s-}
            {-"argonix: copying the derivation's closure (with build output).\n"-}
          {-proc "nix-copy-closure"-}
               {-["--include-outputs", "--to", host, lineToText drv]-}
               {-empty-}
Valentin Reis's avatar
Valentin Reis committed
354

Valentin Reis's avatar
Valentin Reis committed
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
      {-case run of-}
        {-Just cmd -> do-}
          {-_ <- proc-}
            {-"ssh"-}
            {-[ "-t"-}
            {-, host-}
            {-, "source .profile; source .bash_profile; SUDO=$(which sudo) exec nix-shell --keep SUDO --pure --allow-new-privileges --option build-extra-sandbox-paths $(which sudo | xargs dirname) "-}
            {-<> lineToText drv-}
            {-<> " --run "-}
            {-<> "\""-}
            {-<> cmd-}
            {-<> "\""-}
            {-]-}
            {-empty-}
          {-Prelude.mapM_-}
            {-(\r -> proc "scp"-}
                        {-["-r", host <> ":" <> r, fromMaybe "." retreiveAs]-}
                        {-empty-}
            {-)-}
            {-retreive-}
        {-Nothing -> liftIO $ executeFile-}
          {-"ssh"-}
          {-True-}
          {-[ "-t"-}
          {-, unpack host-}
          {-, unpack-}
            {-("source .profile; source .bash_profile; SUDO=$(which sudo) exec nix-shell --keep SUDO --pure --allow-new-privileges --option build-extra-sandbox-paths $(which sudo | xargs dirname) "-}
            {-<> lineToText drv-}
            {-)-}
          {-]-}
          {-Nothing-}
 {-where-}
  {-opts = info-}
    {-(executorParser <**> helper)-}
    {-(  fullDesc-}
    {-<> progDesc "Argo environment provisioning/deployment/execution."-}
    {-<> header "argonix"-}
    {-)-}