packages feed

encapsule-0.6.1: src/Main.hs

-- SPDX-License-Identifier: Apache-2.0

module Main (main) where

import Control.Exception (IOException, try)
import Control.Monad.Extra (unless, when)
import Data.List.Extra (dropPrefix, isInfixOf)
import Data.Maybe (fromMaybe)
import qualified Data.Set as Set
import Options.Applicative (completer, listIOCompleter, metavar, strArgument, strOption)
import SimpleCmd (cmd_, cmdBool, cmdFull, cmdLines, cmdN, warning, (+-+))
import SimpleCmdArgs
import System.IO (BufferMode(NoBuffering), hSetBuffering, stdout)
import System.Exit (ExitCode(..))
import System.FilePath (takeFileName)
import System.Process (readProcessWithExitCode)

import Backup
import Config
import Error
import Paths_encapsule (version)
import qualified Run
import Run hiding (RunOpts(..))

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  simpleCmdArgs (Just version)
    progname
    ("Run a toolbox image in an isolated podman container" +-+
     "https://github.com/juhp/encapsule#readme") $
    subcommands
    [ Subcommand "list" "List encapsule images and containers" $
      pure listCmd
    , Subcommand "list-caps" "List available capabilities" $
      pure listCapsCmd
    , Subcommand "pull" "Pull a container image with podman" $
      pullCmd <$> strArg "IMAGE"
    , Subcommand "rm" "Remove an encapsule container" $
      removeCmd
      <$> switchLongWith "delete" "Do container removal"
      <*> strArg "TOOLBOX"
      <*> optional projectNameOpt
    , Subcommand "rmi" "Remove an encapsule image" $
      removeImageCmd
      <$> dryrunOpt
      <*> strArg "TOOLBOX"
    , Subcommand "stop" "Stop an encapsule container" $
      stopCmd
      <$> strArg "TOOLBOX"
      <*> optional projectNameOpt
    , Subcommand "backup" "Create a tarball backup of a directory" $
      backupCmd
      <$> dryrunOpt
      <*> switchWith 'y' "yes" "Don't prompt for large directories"
      <*> optional (strOptionWith 'o' "output" "FILE" "Output tarball (default: DIR-<timestamp>.tar.gz)")
      <*> strArg "DIR"
    , Subcommand "commit" "Commit an encapsule image from a container" $
      commitCmd
      <$> dryrunOpt
      <*> optional (strOptionWith 'n' "name" "NAME" "Optional image name (prefix with '^' to skip 'encapsule-' prefix)")
      <*> strArg "TOOLBOX"
    , Subcommand "create" "Create an encapsule container" $
      runCmd <$> runOpts True False
    , Subcommand "enter" "Connect to an encapsule container" $
      enterCmd
      <$> dryrunOpt
      <*> debugOpt
      <*> pure True
      <*> optional (strArg "TOOLBOX")
      <*> optional projectNameOpt
      <*> optional userNameOpt
      <*> many (strArg "[--] CMD")
    , Subcommand "run" "Run a temporary encapsule container" $
      runCmd <$> runOpts False True
    ]
  where
    dryrunOpt = switchLongWith "dryrun" "Print the podman command instead of running it"

    projectOpt = strOptionWith 'p' "project" "DIR[:opts]"

    nameOpt = strOptionWith 'n' "name" "NAME" "Optional container name (prefix with '^' prefix to skip 'encapsule-' prefix)"

    projectNameOpt = Project <$> projectOpt "Project name or path" <|>
                     Name <$> nameOpt

    dirOptBackup s l m h =
      let pair fs sn = (fs,sn) in
        pair
        <$> strOptionWith s l m h
        <*> switchLongWith ("backup-" ++ l) ("Tarball" +-+ l +-+ "directory before starting")

    debugOpt = switchLongWith "debug" "Show debug output"

    userNameOpt =
      flagLongWith' "root" "root" "Run as root (shorthand for --user root)" <|>
      strOptionLongWith "user" "USER" "Override container user [default: host/image user with host UID]"

    capOpt = strOption $
      optionMods 'c' "cap" "NAME" "Enable a config capability" <>
      completer (listIOCompleter listCaps)

    runOpts keep unique =
      Run.RunOpts
      <$> strArgument (metavar "IMAGE" <> completer (listIOCompleter listImages))
      <*> many (strOptionWith 'v' "volume" "HOST:CONTAINER[:opts]" "Bind mount (user's files default to selinux :z)")
      <*> many (strOptionWith 'e' "env" "KEY[=VALUE]" "Set or pass through an environment variable")
      <*> many (strOptionLongWith "path" "DIR" "Prepend a directory to PATH inside the container")
      <*> many (strOptionWith 'i' "init" "CMD" "A bash snippet run when creating the encapsule container")
      <*> many capOpt
      <*> switchLongWith "pull" "Pull newer container image"
      <*> optional userNameOpt
      <*> optional (dirOptBackup 'H' "home" "DIR[:opts]" "Mount a directory as a writable home (created if missing; use DIR:O to overlay)")
      <*> optional (dirOptBackup 'p' "project" "DIR[:opts]" "Mount a (project) directory as workdir (use DIR:O to overlay)")
      <*> optional nameOpt
      <*> pure keep
      <*> switchLongWith "readonly" "Make the encapsule container filesystem read-only"
      <*> optional
          (flagLongWith' NetNone "no-network" "Disable network access" <|>
           flagLongWith' NetHost "network-host" "Share the host network (including localhost ports)")
      <*> switchLongWith "sudo" "Set up passwordless sudo for the container user"
      <*> switchLongWith "no-skel" "Don't copy /etc/skel into an empty home"
      <*> pure unique
      <*> many (strOptionLongWith "podman-opt" "OPTION" "Pass an option directly to podman")
      <*> debugOpt
      <*> dryrunOpt
      <*> many (strArg "[--] CMD")

-- Completion should stay quiet when Podman is absent or its storage is unavailable.
listImages :: IO [String]
listImages = do
  result <- try (readProcessWithExitCode "podman"
                 ["images", "--format", "{{.Repository}}:{{.Tag}}"] "")
            :: IO (Either IOException (ExitCode, String, String))
  return $ case result of
    Right (ExitSuccess, out, _) ->
      Set.toAscList $ Set.fromList
        [shortName name | name <- lines out, not (null name), not ("<none>" `isInfixOf` name)]
    _ -> []
  where
    shortName = dropPrefix (progname ++ "-") . takeFileName

listCmd :: IO ()
listCmd = do
  needPodman
  cmd_ "podman" ["images",
                 "--filter", "reference=" ++ progname ++ "-*",
                 "--format", "{{.Repository}}:{{.Tag}}  {{.Size}}  {{.Created}}"]
  putChar '\n'
  cmd_ "podman" ["ps", "-a",
                 "--filter", "name=^" ++ progname +=+ "",
                 "--format", "{{.Names}}  {{.Status}}"]

removeCmd :: Bool -> String -> Maybe ProjectName -> IO ()
removeCmd delete toolbox mprojectname = do
  containerName <- mkContainerName toolbox mprojectname
  needPodman
  exists <- cmdBool "podman" ["container", "exists", containerName]
  if exists
    then do
      (_, out, _) <- cmdFull "podman"
        ["container", "inspect", "-f", "{{.State.Running}}", containerName] ""
      when (take 4 out == "true") $ do
        putStr "stopping "
        cmd_ "podman" ["stop", containerName]
      if delete
        then do
        putStr "rm "
        cmd_ "podman" ["rm", containerName]
        else putStrLn "use --delete to actually remove"
    else warning $ "container" +-+ containerName +-+ "not found"

-- FIXME check image exists?
removeImageCmd :: Bool -> String -> IO ()
removeImageCmd dryrun name =
  let image = progname +=+ name in
    if dryrun
    then putStrLn $ "would rmi" +-+ image
    else do
      needPodman
      putStr "rmi "
      cmd_ "podman" ["rmi", image]

-- FIXME dryrun
stopCmd :: String -> Maybe ProjectName -> IO ()
stopCmd name mprojectname = do
  containerName <- mkContainerName name mprojectname
  needPodman
  exists <- cmdBool "podman" ["container", "exists", containerName]
  if exists
    then do
      putStr "stop "
      cmd_ "podman" ["stop", containerName]
    else warning $ "container" +-+ containerName +-+ "not found"

enterCmd :: Bool -> Bool -> Bool -> Maybe String -> Maybe ProjectName
         -> Maybe String
         -> [String] -> IO ()
enterCmd dryrun debug running mbase mprojectname muser command = do
  regexp <-
    case mprojectname of
      Nothing -> return $ progname +=+ fromMaybe ".*" mbase
      Just (Name ('^':n)) -> return n
      Just (Name n) -> return $ progname ++ '-' : n
      Just (Project p) -> do
        projectDir <- resolveProject p
        return $ progname ++ '-' : fromMaybe ".*" mbase ++ '-' : workProjectName projectDir
  needPodman
  ps <- cmdLines "podman" $ "ps" :
        ["-a" | not running] ++
        ["--filter", "name=" ++ '^' : regexp ++ "$",
         "--format", "{{.Names}}"]
  case ps of
    [] ->
      if running
      then enterCmd dryrun debug False mbase mprojectname muser command
      else error' "encapsule container not found"
    [c] -> do
      when (debug && not running) $
        warning "no running encapsule container found"
      enterContainer dryrun debug running muser c command
    _ -> error' $ "multiple" +-+ (if running then  "running" else "") +-+ "containers match:\n" ++ unlines ps

-- image management

pullCmd :: String -> IO ()
pullCmd image = do
  needPodman
  cmd_ "podman" ["pull", image]

commitCmd :: Bool -> Maybe String -> String -> IO ()
commitCmd dryrun mname toolbox = do
  needPodman
  containerExists <- cmdBool "podman" ["container", "exists", toolbox]
  unless containerExists $
    error' $ "container '" ++ toolbox ++ "' not found"
  let image =
        -- FIXME or fallback if no encapsule container
        let encapsuleName ('^':n) = n
            encapsuleName n = progname +=+ n
        in maybe (progname +=+ toolbox) encapsuleName mname
  imageExists <- cmdBool "podman" ["image", "exists", image]
  unless imageExists $
    putStrLn $ "creating new image:" +-+ image
  let commit_args = ["commit", toolbox, image]
  unless dryrun $
    putStr "writing image "
  (if dryrun then cmdN else cmd_) "podman" commit_args