packages feed

podman-test (empty) → 0.1.0

raw patch · 10 files changed

+2094/−0 lines, 10 filesdep +asyncdep +basedep +bytestring

Dependencies added: async, base, bytestring, containers, cryptohash-sha256, directory, filepath, hspec, network, podman-test, process, unix

Files

+ CHANGELOG.md view
@@ -0,0 +1,49 @@+# Changelog++All notable changes to this project will be documented in this file.++The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)+and this project adheres to the+[Haskell Package Versioning Policy](https://pvp.haskell.org/).++## [Unreleased]++## [0.1.0] - 2026-11-25++### Added+- `withPod` and `withContainer`: run a pod of containers for as long as an+  action, ready before the action starts, and removed when it ends,+  however it ends.+- Endpoints of three kinds: a Unix socket of the service (`Native`), a TCP+  port bridged to a Unix socket by a container of socat (`Bridged`), and a+  TCP port published on a port of `127.0.0.1` that Podman picks+  (`Published`). A pod with sockets only has no network. The container of+  socat runs only in a pod that needs it: one with a `Bridged` endpoint, or+  one that waits for a `Published` endpoint to accept connections.+- Readiness: an endpoint accepts connections, a line in a log, a command+  that succeeds in a container, or a check of your own, within a deadline.+- Every run has its own pods and its own folder of sockets, so test+  processes run in parallel. The pods and folders of runs that died are+  removed by the next run.+- Images of a registry, pinned by their digest, and images built from a+  recipe, tagged by its hash; each pulled or built once for every process+  of the machine.+- `podmanUsable`, to skip the tests where Podman cannot run, or when+  `PODMAN_TEST_SKIP` is set.+- The Podman of the machine is found in a pure Nix shell, as `stack --nix`+  makes one: in `/usr/bin`, `/usr/local/bin` or NixOS's+  `/run/current-system/sw/bin` when it is not on the `PATH`, or where+  `PODMAN_TEST_PODMAN` says. It runs with the folders of the machine on its+  `PATH`, where it finds its setuid helpers, and without `LD_LIBRARY_PATH`+  or `LD_PRELOAD`. `podmanPath` says which one a run uses.+- The base folder of the sockets is private to the user: made with no+  access for anyone else, closed to others if they could use it, and+  refused with `UnsafeFolder` if it is a link or belongs to another user.+  The folders of the pods, and native sockets, are open to everyone, for+  services that run as another user in their containers, so this folder is+  what keeps the other users of the machine out.+- The last lines of the log of every container on the standard error when a+  pod is not ready or the action fails.++[Unreleased]: https://github.com/jprupp/podman-test/compare/v0.1.0...HEAD+[0.1.0]: https://github.com/jprupp/podman-test/releases/tag/v0.1.0
+ LICENSE view
@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 JP Rupp++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.
+ README.md view
@@ -0,0 +1,368 @@+# podman-test++[![CI](https://github.com/jprupp/podman-test/actions/workflows/ci.yml/badge.svg)](https://github.com/jprupp/podman-test/actions/workflows/ci.yml)+[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/jprupp/podman-test/blob/master/LICENSE)++Podman containers for the tests of Haskell programs. The services that a test+needs, such as a database, a cache or a node, run in rootless containers for+as long as the test does, and the test reaches them through Unix sockets. Tests+that run in parallel never meet, a container never outlives its test, and a+test starts only once its services answer. It works with any test framework:+it is plain `IO`, in the shape of `bracket`.++- [Changelog](https://github.com/jprupp/podman-test/blob/master/CHANGELOG.md)+- [Report a bug](https://github.com/jprupp/podman-test/issues)++## Contents++- [Why podman-test](#why-podman-test)+- [Design](#design)+- [Installation](#installation)+- [Quick start](#quick-start)+- [Endpoints](#endpoints)+- [Pods of several containers](#pods-of-several-containers)+- [Readiness](#readiness)+- [Images](#images)+- [Parallel runs and clean-up](#parallel-runs-and-clean-up)+- [With hspec](#with-hspec)+- [Requirements and limits](#requirements-and-limits)+- [Nix](#nix)+- [Troubleshooting](#troubleshooting)+- [Module overview](#module-overview)+- [Development](#development)+- [License](#license)++## Why podman-test++A test of code that talks to a real service finds what a mock cannot: the+protocol as the service speaks it, its errors, its timing. A container gives+every test the same version of the service, on every machine. But a test needs+more than `podman run`:++- **The container must go away with the test**, also when the test fails, and+  also when the test binary is killed.+- **Tests that run at once must not meet.** Fixed ports collide, and random+  ports collide too, now and then, and fail a test for no reason of its own.+- **The test must wait until the service answers**, not until its container+  has started.+- **A failure must explain itself**: what the service printed is often the+  only clue.++[testcontainers](https://hackage.haskell.org/package/testcontainers) does much+of this for Docker. This library is for Podman, rootless, with Unix sockets in+place of ports, and with no helper container left running to clean up.++## Design++- **Unix sockets, not ports.** Each pod has a folder of its own on the host,+  mounted into each of its containers at `/podman-test`, and each endpoint of a+  service is a socket in it. Tests that run at once have folders of their own,+  so their names never meet, and no port of the machine is taken. A pod whose+  endpoints are all sockets has no network at all.+- **A bridge for services that only speak TCP.** A small container of+  [socat](http://www.dest-unreach.org/socat/) in the pod joins each connection+  to a socket to the port of the service, which needs nothing installed. A pod+  that needs no bridge runs none: see [Endpoints](#endpoints).+- **TCP where a client needs it.** A port can still be published on+  `127.0.0.1`, on a port that Podman picks, for a client that only takes a host+  and a port.+- **The next run is the reaper.** Every pod carries the name of its run: the+  process ID and the start time of its process. A run removes its pods when its+  tests end, and the first pod of every run removes the pods of runs whose+  process is gone. No container is left running to watch.+- **Ready means ready.** A test gets its pod once every endpoint accepts+  connections, or once whatever else you name holds.+- **Pinned images.** An image of a registry is named by its digest; one built+  from a recipe is tagged by the hash of the recipe. Eight processes that need+  the same image pull or build it once.+- **Safe defaults.** A container may use 512 MiB of memory unless you say+  otherwise, every call to Podman has a deadline, and the logs of the+  containers go to the standard error when something fails.++## Installation++Add it to the dependencies of your test suite:++```yaml+tests:+  spec:+    dependencies:+      - podman-test+```++It needs Podman 4 or later, rootless, on Linux: see+[Requirements and limits](#requirements-and-limits).++## Quick start++A Redis that listens on a socket of its pod, and a test that talks to it:++```haskell+import Control.Exception (bracket)+import qualified Data.ByteString.Char8 as C+import Network.Socket (close)+import Network.Socket.ByteString (recv, sendAll)+import Test.Podman++redis :: ContainerSpec+redis =+  (container "redis" (Registry "docker.io/library/redis:7-alpine"))+    { command =+        [ "redis-server", "--port", "0", "--save", ""+        , "--unixsocket", socketInside "redis", "--unixsocketperm", "777"+        ]+    , endpoints = [Native "redis"]+    }++main :: IO ()+main = withContainer redis $ \p ->+  bracket (connectTo (address p "redis")) close $ \s -> do+    sendAll s (C.pack "PING\r\n")+    recv s 64 >>= C.putStrLn+```++It prints `+PONG`. `withContainer` pulls the image if Podman does not have it,+starts the container, waits until the socket accepts connections, runs the+action, and removes the container, whatever the action does. In a real test,+pin the image by its digest: see [Images](#images).++## Endpoints++An endpoint is how a test reaches a service, and its name names its socket.+`address` gives where it is on the host:++| Endpoint | The service | The test reaches it at |+| --- | --- | --- |+| `Native "db"` | listens on the socket `socketInside "db"`, which is `/podman-test/db.sock` | `UnixSocket` in the folder of the pod |+| `Bridged "db" 5432` | listens on TCP port 5432 | `UnixSocket` in the folder of the pod, through the bridge |+| `Published "db" 5432` | listens on TCP port 5432 | `TcpPort "127.0.0.1"` and a port that Podman picked |++`connectTo` opens a socket to an `Address`, and `sockAddr` gives it as the+`network` package takes it, for a client library that takes a `SockAddr`. A+client that takes the path of a Unix socket, such as hedis, takes the+`FilePath` of a `UnixSocket`.++**Native** is the best when the service can do it: nothing stands between the+test and the service. The service makes the socket as the user that it runs as+in its container, which is not the user of the tests, so it has to make it open+to everyone, as Redis does with `--unixsocketperm 777`.++**Bridged** works with any service. The bridge runs as root of its container,+which rootless Podman maps to the user of the tests, so the socket is theirs.++**Published** is for clients that only take a host and a port. The pod then+has a network, which it does not need otherwise.++**The bridge** is one more container in the pod, of one more image: socat on+Alpine, pulled from Docker Hub by its digest. A pod has one in two cases: it+has a `Bridged` endpoint, or it waits until a `Published` endpoint accepts+connections, which is what `pod` asks for every endpoint. A pod of `Native`+and `Published` endpoints that is ready by something else, such as `Succeeds`+or `LogLine`, runs the containers of its spec and nothing else. Tests that+must pull no image at all use such a pod, with images that the machine has.++## Pods of several containers++The containers of a pod share its network, so they reach each other on+`localhost`, and its folder of sockets. A client next to a server:++```haskell+pair :: PodSpec+pair =+  (pod "pair" [server, client])+    { ready = [Succeeds "client" ["redis-cli", "-h", "127.0.0.1", "ping"]] }+  where+    server = (container "server" redisImage) {command = ["redis-server", "--save", ""]}+    client =+      (container "client" redisImage)+        { entrypoint = Just "sh", command = ["-c", "while :; do sleep 3600; done"] }+```++`exec p "client" [...]` runs a command in a container of the pod and gives what+it printed, and `logs p "server"` gives the log of one. Without `outgoing =+True`, a pod with sockets only has no network beyond itself, so a test cannot+reach the Internet by mistake.++## Readiness++`withPod` gives the pod to the action once every `Readiness` of its spec holds,+in their order, within `readyWithin` seconds, 60 by default. `pod` sets+`ready` to `Accepts` for every endpoint.++| Readiness | Holds when |+| --- | --- |+| `Accepts "db"` | the endpoint accepts a connection; for a port, from inside the pod, through the bridge, so that a bridge or a port forwarder that accepts before the service listens does not count |+| `LogLine "db" "ready to accept"` | the log of the container has the text |+| `Succeeds "db" ["pg_isready"]` | the command succeeds in the container |+| `Probe "the schema is loaded" check` | `check :: Pod -> IO Bool` says so |++A container that stops before its pod is ready stops the wait at once, with+`Stopped`. A pod that is not ready in time throws `NotReady`, which says what+did not hold. Either way, the last lines of the log of each container go to the+standard error.++## Images++```haskell+-- an image of a registry, pinned by its digest: the same image for ever+redisImage :: Image+redisImage =+  Registry+    "docker.io/library/redis:7-alpine\+    \@sha256:ec1c2d3603c3d7d65b153bedda0248b641aa3bd7684503406b27b9e870ac0796"++-- an image built from a recipe that the tests carry+nodeImage :: Image+nodeImage =+  Built+    ImageSpec+      { name = "regtest"+      , containerfile = C.pack "FROM ...\nCOPY install.sh /\nRUN sh /install.sh\n"+      , files = [("install.sh", installScript)]+      }+```++An image that the machine has already, such as one that a script of the+package built, is named like one of a registry, by its reference:+`Registry "localhost/NAME:TAG"`. Podman has it, so nothing is pulled. When it+is missing, the pull fails and so does the pod: check with+`podman image exists` first to skip the tests instead.++A built image is tagged `localhost/NAME:HASH`, with a hash of the recipe and its+files: a change of the recipe is a new image, and an old branch still finds its+own. Pulling and building take a lock of the machine, so processes that start+together wait for the first instead of doing the work again. Images are never+removed by the library; `podman image prune` removes the old ones.++## Parallel runs and clean-up++Every process that uses the library is a run, named after its process ID and+the start time of its process. Its pods are `pt-RUN-N-NAME`, its containers+`pt-RUN-N-NAME-CONTAINER`, and its sockets are in its own folder:++```+$XDG_RUNTIME_DIR/podman-test/RUN/N/ENDPOINT.sock+```++So a test binary can run its tests in several threads, and a tool can run it as+several processes at once, as+[haskell-dev](https://github.com/jprupp/tools) does: nothing is shared. A pod is+removed when its action ends. When a run is killed, its pods stay until the+first pod of a later run removes them, with their folders. Nothing of a run+whose process still exists is ever removed.++## With hspec++`podmanUsable` says whether Podman can run here, and why not, so that a machine+without it runs the other tests and says what it left out:++```haskell+spec :: Spec+spec = do+  usable <- runIO podmanUsable+  describe "Redis" $+    it "answers PING" $ case usable of+      Left why -> pendingWith why+      Right () -> withContainer redis $ \p -> ...+```++Set `PODMAN_TEST_SKIP` to skip them on purpose. To share one pod between the+tests of a group, use hspec's `aroundAll`:++```haskell+aroundAll (withContainer redis) $+  it "answers PING" $ \p -> ...+```++## Requirements and limits++- **Podman 4 or later, rootless, on Linux.** The user needs subordinate IDs+  (`/etc/subuid` and `/etc/subgid`), as every rootless Podman does.+- **SELinux** is fine: the folder of sockets is mounted with the shared label.+- **Nix builds** work: see [Nix](#nix).+- **macOS**: Podman runs its containers in a virtual machine, whose shared+  folders do not carry sockets. Use `Published` endpoints there.+- **Permissions.** Rootless Podman maps root of a container to you, and its+  other users to subordinate IDs that are not you. A bridged socket is made+  by root of the bridge, so it is yours. A native socket is made by the+  service as its own user, so it must be open to everyone, and the folder of+  each pod is open to everyone so that the service can make it there. Other+  users of the machine are kept out by the base folder above them all,+  which is yours alone: made with no access for anyone else, and refused,+  with `UnsafeFolder`, if another user made it first or it is a link. That+  matters for `/tmp/podman-test-UID` and for `PODMAN_TEST_DIR`; the default,+  under `$XDG_RUNTIME_DIR`, is private already.+- **Paths of sockets** are at most 107 bytes on Linux. The folder is short, but+  a long name of an endpoint can still pass it; the library says so before it+  starts anything.++## Troubleshooting++- **`podman is not on the PATH, nor in …`**: there is no Podman where the+  library looks. Install it, or name it with `PODMAN_TEST_PODMAN`.+- **`podman info failed`**: rootless Podman is not set up for the user. Run+  `podman info` to see why.+- **A pod is not ready**: the logs of its containers are on the standard error.+  `readyWithin` gives a slow service more time.+- **Connection refused on a `Native` socket**: the service made it for its own+  user only. Make it open to everyone, or use `Bridged`.+- **Another folder for the sockets**: set `PODMAN_TEST_DIR`. It is made+  private to you, and refused if it belongs to someone else.+- **`UnsafeFolder`**: the base folder is not yours alone, as when another+  user made `/tmp/podman-test-UID` before you. Remove it, or choose another+  with `PODMAN_TEST_DIR`.+- **What a run left**: `podman pod ps --filter label=podman-test.run`.++## Nix++`stack --nix` builds and tests in a pure Nix shell: it keeps the files of+the machine, but leaves only packages of Nix on the `PATH`, so a test would+not find the machine's Podman there. The machine's Podman is the one to use:+rootless Podman needs `newuidmap` and `newgidmap`, which must be setuid, and+nothing in the store of Nix can be.++So the library looks for `podman` on the `PATH`, then in `/usr/bin`,+`/usr/local/bin` and NixOS's `/run/current-system/sw/bin`, and+`PODMAN_TEST_PODMAN` names another. It runs it with the folders of the+machine at the end of its `PATH`, NixOS's setuid wrappers in+`/run/wrappers/bin` first, so that Podman finds its helpers, and without+`LD_LIBRARY_PATH` and `LD_PRELOAD`, so that a program of the machine does not+load the libraries of the shell. Nothing has to change in `stack.yaml`:+the tests run in the Nix job of CI as in the other. `podmanPath` says which+Podman a run uses.++## Module overview++| Module | What it has |+| --- | --- |+| `Test.Podman` | pods, containers, endpoints, readiness, addresses: all that a test needs |+| `Test.Podman.Image` | images of a registry and built images, pulled or built once |+| `Test.Podman.Run` | the name and folder of a run, the clean-up of dead runs, locks of the machine |+| `Test.Podman.Command` | running `podman` with a deadline, and `podmanUsable` |++## Development++```sh+stack build+stack test                 # runs real containers; pending without Podman+```++For the time between two commits there is a faster loop, `haskell-dev`, from+[jprupp/tools](https://github.com/jprupp/tools), on your `PATH`:++```sh+haskell-dev build          # build without optimisation+haskell-dev test           # the tests in several processes at once: 5 s+haskell-dev docs           # build the documentation and check its comments+```++Do not mix the two kinds of build in one folder: the flags differ, so each+switch compiles everything again. CI builds and tests every change with Stack,+against the libraries of Ubuntu and with Nix, through the workflow that the+Haskell packages of jprupp share. Format the code with `haskell-format`+(ormolu). Changes are described in [CHANGELOG.md](CHANGELOG.md), and+contributions are welcome as pull requests on GitHub.++## License++MIT; see [LICENSE](LICENSE).
+ podman-test.cabal view
@@ -0,0 +1,91 @@+cabal-version: 1.12++-- This file has been generated from package.yaml by hpack version 0.39.6.+--+-- see: https://github.com/sol/hpack++name:           podman-test+version:        0.1.0+synopsis:       Podman containers for tests, in parallel, reached through Unix sockets+description:    Run the services that a test needs, such as a database or a node, in+                rootless Podman containers, from any test framework. Every run of the+                tests has its own containers and its own folder of Unix sockets, so test+                processes run in parallel without sharing ports. A service that listens+                on a Unix socket is reached directly; one that only listens on TCP is+                bridged to a socket; TCP ports on the loopback interface are there when+                a client needs them. Containers that a dead run left behind are removed+                by the next one.+category:       Testing+stability:      experimental+homepage:       https://github.com/jprupp/podman-test#readme+bug-reports:    https://github.com/jprupp/podman-test/issues+author:         JP Rupp+maintainer:     jprupp@protonmail.ch+copyright:      (c) 2026 JP Rupp+license:        MIT+license-file:   LICENSE+build-type:     Simple+extra-source-files:+    README.md+    CHANGELOG.md++source-repository head+  type: git+  location: https://github.com/jprupp/podman-test++library+  exposed-modules:+      Test.Podman+      Test.Podman.Command+      Test.Podman.Image+      Test.Podman.Run+  other-modules:+      Paths_podman_test+  hs-source-dirs:+      src+  default-extensions:+      DuplicateRecordFields+      LambdaCase+      NoFieldSelectors+      OverloadedRecordDot+  ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wredundant-constraints+  build-depends:+      base >=4.18 && <5+    , bytestring >=0.11 && <0.13+    , containers >=0.6 && <0.8+    , cryptohash-sha256 ==0.11.*+    , directory ==1.3.*+    , filepath >=1.4 && <1.6+    , network >=3.1 && <3.3+    , process ==1.6.*+    , unix ==2.8.*+  default-language: GHC2021++test-suite spec+  type: exitcode-stdio-1.0+  main-is: Spec.hs+  other-modules:+      Test.PodmanSpec+      Paths_podman_test+  hs-source-dirs:+      test+  default-extensions:+      DuplicateRecordFields+      LambdaCase+      NoFieldSelectors+      OverloadedRecordDot+  ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wredundant-constraints -threaded -rtsopts "-with-rtsopts=-N4 -M1g"+  build-tool-depends:+      hspec-discover:hspec-discover+  build-depends:+      async+    , base >=4.18 && <5+    , bytestring+    , directory+    , filepath+    , hspec >=2.10+    , network+    , podman-test+    , process+    , unix+  default-language: GHC2021
+ src/Test/Podman.hs view
@@ -0,0 +1,620 @@+-- |+-- Module      : Test.Podman+-- Copyright   : (c) 2026 JP Rupp+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- Podman containers for tests: the services that a test needs, such as a+-- database, a cache or a node, run in rootless containers for as long as+-- the test does, and are reached through Unix sockets.+--+-- = Purpose+--+-- A test of code that talks to a real service is the one that finds what a+-- mock cannot: the protocol as the service speaks it, its errors, its+-- timing. Running the service in a container gives every test the same+-- version of it, on every machine. Doing that well takes more than+-- @podman run@: the containers have to go away when the test does, even when+-- it fails; tests that run in parallel must not meet; and the test has to+-- wait until the service answers. This library does those things, for any+-- test framework: it is plain 'IO', in the shape of 'Control.Exception.bracket'.+--+-- = Design+--+-- * __Unix sockets, not ports.__ Every pod has a folder of its own on the+--   host, mounted into each of its containers at 'socketFolder', and every+--   endpoint of a service is a socket in it. Tests that run at once have+--   folders of their own, so they cannot meet, and no port of the machine is+--   taken. A service that can listen on a Unix socket does so ('Native'); one+--   that listens only on TCP is bridged to a socket by a small container of+--   @socat@ in its pod ('Bridged'). A pod whose endpoints are all sockets has+--   no network at all.+--+-- * __TCP where a client needs it.__ Some clients can only connect to a host+--   and a port. A 'Published' endpoint is published on a port of+--   @127.0.0.1@ that Podman picks, and its 'Address' says which.+--+-- * __A bridge only where it is needed.__ The bridge is one more container,+--   of one more image ('bridgeImage'). A pod has one when it has a 'Bridged'+--   endpoint, or when it waits until a 'Published' endpoint accepts+--   connections ('Accepts'). A pod of 'Native' and 'Published' endpoints+--   that is ready by another 'Readiness' runs the containers of its spec and+--   nothing else, so its tests need no image but their own.+--+-- * __Pods.__ The containers of a test are one pod: they share its network,+--   so they reach each other on @localhost@, and its folder of sockets.+--+-- * __Clean-up.__ A pod is removed when the action that uses it ends, however+--   it ends, and the pods of runs that were killed are removed by the next+--   run ("Test.Podman.Run").+--+-- * __Ready means ready.__ 'withPod' gives the pod to the action only once+--   every 'Readiness' of its spec holds: by default, once every endpoint+--   accepts connections.+--+-- * __Failures that explain themselves.__ When a pod does not become ready,+--   or the action fails, the last lines of the log of every container are+--   printed to the standard error.+--+-- * __Safe defaults.__ A container may use 512 MiB of memory unless its spec+--   says otherwise, and every call to Podman has a deadline.+--+-- = Example+--+-- A Redis that listens on a socket of the pod:+--+-- @+-- import Network.Socket (Socket)+-- import Test.Podman+--+-- redis :: PodSpec+-- redis =+--   pod+--     "redis"+--     [ (container "redis" (Registry "docker.io\/library\/redis:7-alpine"))+--         { command =+--             [ "redis-server", "--port", "0", "--save", ""+--             , "--unixsocket", socketInside "redis", "--unixsocketperm", "777" ]+--         , endpoints = [Native "redis"]+--         }+--     ]+--+-- main :: IO ()+-- main = withPod redis $ \\p -> do+--   s <- connectTo (address p "redis")+--   ...+-- @+--+-- = Requirements and limits+--+-- * Podman 4 or later, running rootless, on Linux. 'podmanUsable' says+--   whether it can run, so that a test can be skipped where it cannot.+-- * In a pure Nix shell, as @stack --nix@ makes one, the tests use the+--   Podman of the machine, which is not on the @PATH@ there: it is found in+--   the usual folders, or where @PODMAN_TEST_PODMAN@ says+--   ("Test.Podman.Command").+-- * A 'Native' socket is made by the service, as the user that it runs as in+--   its container, which is not the user of the tests: the service must make+--   it open to everyone, as Redis does with @--unixsocketperm 777@. Bridged+--   sockets are made by the bridge, as the user of the tests.+-- * The folders of the pods are open to everyone, for those services, under+--   a base folder that is the user's alone: one that another user made, or a+--   link, is refused with t'UnsafeFolder'.+-- * On macOS, Podman runs its containers in a virtual machine, whose shared+--   folders do not carry sockets: use 'Published' endpoints there.+module Test.Podman+  ( -- * Pods+    PodSpec (..),+    pod,+    withPod,+    withContainer,++    -- * Containers+    ContainerSpec (..),+    container,+    Endpoint (..),+    endpointName,+    socketFolder,+    socketInside,++    -- * Readiness+    Readiness (..),++    -- * A running pod+    Pod,+    address,+    podName,+    containerName,+    exec,+    execWithin,+    logs,++    -- * Addresses+    Address (..),+    sockAddr,+    connectTo,++    -- * Images+    Image (..),+    ImageSpec (..),+    bridgeImage,++    -- * Errors+    PodError (..),+    UnsafeFolder (..),++    -- * Podman+    podmanUsable,+    podmanPath,+    podman,+    podmanWithin,+    PodmanError (..),+  )+where++import Control.Concurrent (threadDelay)+import Control.Exception (Exception, SomeException, bracket, bracketOnError, onException, throw, throwIO, try)+import Control.Monad (forM, forM_, unless, void, when)+import Data.Char (isAsciiLower, isDigit)+import Data.List (isInfixOf, nub)+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import GHC.Clock (getMonotonicTime)+import Network.Socket+  ( Family (..),+    SockAddr (..),+    Socket,+    SocketType (..),+    close,+    connect,+    defaultProtocol,+    socket,+    tupleToHostAddress,+  )+import System.Directory (createDirectory, removeDirectoryRecursive)+import System.Exit (ExitCode (..))+import System.FilePath ((</>))+import System.IO (hPutStrLn, stderr)+import System.Posix.Files (setFileMode)+import Test.Podman.Command (PodmanError (..), podman, podmanPath, podmanStatus, podmanUsable, podmanWithin)+import Test.Podman.Image (Image (..), ImageSpec (..), ensureImage)+import Test.Podman.Run (UnsafeFolder (..), nextNumber, removeStale, runFolder, runLabel, runName)++-------------------------------------------------------------------------------+-- Specs+-------------------------------------------------------------------------------++-- | A pod to run: its containers, and when it is ready.+data PodSpec = PodSpec+  { -- | a short name, of lowercase letters, digits and dashes, which names+    -- the pod and its containers in @podman ps@+    name :: !String,+    -- | its containers, started in this order+    containers :: ![ContainerSpec],+    -- | whether its containers may reach the network beyond the pod. Without+    -- it, and without 'Published' endpoints, the pod has no network at all.+    outgoing :: !Bool,+    -- | what must hold before the pod is given to the action, checked in+    -- this order+    ready :: ![Readiness],+    -- | how many seconds all of 'ready' may take+    readyWithin :: !Int+  }++-- | A pod of these containers, of a name: ready once every endpoint of every+-- container accepts connections, within a minute, and without a network+-- beyond the pod.+pod :: String -> [ContainerSpec] -> PodSpec+pod name cs =+  PodSpec+    { name,+      containers = cs,+      outgoing = False,+      ready = [Accepts (endpointName e) | c <- cs, e <- c.endpoints],+      readyWithin = 60+    }++-- | A container of a pod.+data ContainerSpec = ContainerSpec+  { -- | a short name, unique in the pod, of lowercase letters, digits and+    -- dashes: the container is @POD-NAME@+    name :: !String,+    image :: !Image,+    -- | the entry point instead of that of the image, if any+    entrypoint :: !(Maybe String),+    -- | the command, which follows the entry point+    command :: ![String],+    -- | variables of its environment+    env :: ![(String, String)],+    -- | the most memory that it may use, as Podman reads it, such as+    -- @"512m"@, or no limit+    memory :: !(Maybe String),+    -- | folders in memory, each with its largest size, such as+    -- @("\/data", "256m")@+    tmpfs :: ![(FilePath, String)],+    -- | how the tests reach it+    endpoints :: ![Endpoint],+    -- | more arguments of @podman run@, put before the image+    options :: ![String]+  }+  deriving (Eq, Show)++-- | A container of a name and an image, with the command of the image, 512+-- MiB of memory and no endpoints.+container :: String -> Image -> ContainerSpec+container name image =+  ContainerSpec+    { name,+      image,+      entrypoint = Nothing,+      command = [],+      env = [],+      memory = Just "512m",+      tmpfs = [],+      endpoints = [],+      options = []+    }++-- | How the tests reach a service of a container. The name of an endpoint+-- is unique in its pod, and names its socket.+data Endpoint+  = -- | the service listens on the Unix socket 'socketInside' of this name+    Native !String+  | -- | the service listens on this TCP port, which a bridge joins to the+    -- Unix socket of this name+    Bridged !String !Int+  | -- | the service listens on this TCP port, which is published on a port+    -- of @127.0.0.1@ that Podman picks+    Published !String !Int+  deriving (Eq, Show)++-- | The name of an endpoint.+endpointName :: Endpoint -> String+endpointName (Native n) = n+endpointName (Bridged n _) = n+endpointName (Published n _) = n++-- | Where the folder of sockets of the pod is in each of its containers.+socketFolder :: FilePath+socketFolder = "/podman-test"++-- | The path, in a container, of the socket of an endpoint: what to give a+-- service that listens on a 'Native' socket.+socketInside :: String -> FilePath+socketInside n = socketFolder </> (n <> ".sock")++-- | What must hold before a pod is ready.+data Readiness+  = -- | the endpoint of this name accepts connections. For a socket of the+    -- service, a connection from the tests is accepted; for a TCP port, one+    -- from inside the pod, so that a bridge or a port forwarder that+    -- accepts before the service listens is not taken for the service. The+    -- connection from inside the pod is made by the bridge, so a pod that+    -- waits this way for a 'Published' endpoint has a bridge.+    Accepts !String+  | -- | the log of this container has this text+    LogLine !String !String+  | -- | this command succeeds in this container, as with @podman exec@+    Succeeds !String ![String]+  | -- | this check succeeds, as it says+    Probe !String !(Pod -> IO Bool)++instance Show Readiness where+  show (Accepts e) = "endpoint " <> e <> " accepts connections"+  show (LogLine c t) = "the log of " <> c <> " shows " <> show t+  show (Succeeds c cmd) = unwords cmd <> " succeeds in " <> c+  show (Probe what _) = what++-- | The image of the bridges, pinned by its digest: socat on Alpine. It is+-- pulled for the first pod that needs a bridge, and a pod that needs none+-- never asks for it.+bridgeImage :: Image+bridgeImage =+  Registry+    "docker.io/alpine/socat:1.8.0.3\+    \@sha256:2d83bdac2858b4bcfa57d478ce53ae3c18a1147a68db4f610454a2d60e5c19bc"++-------------------------------------------------------------------------------+-- Running pods+-------------------------------------------------------------------------------++-- | A pod that runs.+data Pod = Pod+  { full :: !String,+    folder :: !FilePath,+    endpoints :: !(Map String (Endpoint, Address)),+    short :: ![String],+    bridge :: !(Maybe String)+  }++-- | What went wrong with a pod, other than a call to Podman.+data PodError+  = -- | the spec is not one that can run, for this reason+    BadSpec !String+  | -- | the pod of this name was not ready in time: this did not hold+    NotReady !String !String+  | -- | a container of the pod, of this name, stopped before it was ready+    Stopped !String+  | -- | the pod has no endpoint or container of this name+    NoSuch !String+  deriving (Eq)++instance Show PodError where+  show (BadSpec why) = "Bad pod spec: " <> why+  show (NotReady p what) = "Pod " <> p <> " was not ready in time: not " <> what+  show (Stopped c) = "Container " <> c <> " stopped before its pod was ready"+  show (NoSuch n) = "No endpoint or container " <> n <> " in the pod"++instance Exception PodError++-- | Run an action with a pod that runs and is ready, and remove the pod when+-- the action ends, however it ends.+--+-- The images are pulled or built if they are not there, which only the+-- first test of the machine waits for. Then the pod is made, its containers+-- started, a bridge started if the pod needs one, and every 'Readiness' of+-- its spec checked. If the pod is not ready in time, or the+-- action throws, the last lines of the log of each container go to the+-- standard error before the pod is removed.+withPod :: PodSpec -> (Pod -> IO a) -> IO a+withPod spec act = do+  either (throwIO . BadSpec) return (check spec)+  removeStale+  n <- nextNumber+  run <- runFolder+  let full = "pt-" <> runName <> "-" <> show n <> "-" <> spec.name+      dir = run </> show n+      eps = concatMap (.endpoints) spec.containers+      -- the bridge makes the sockets of the bridged endpoints, and is where+      -- a published port is tried from inside the pod+      awaited = [endpoint | Accepts endpoint <- spec.ready]+      needsBridge = any isBridged eps || or [endpointName e `elem` awaited | e <- eps, isPublished e]+  case [p | e <- eps, not (isPublished e), let p = dir </> (endpointName e <> ".sock"), length p > 107] of+    p : _ ->+      throwIO . BadSpec $+        "the socket " <> p <> " has a path longer than 107 bytes: use a shorter name, or PODMAN_TEST_DIR"+    [] -> return ()+  refs <- mapM (ensureImage . (.image)) spec.containers+  bridgeRef <- if needsBridge then Just <$> ensureImage bridgeImage else return Nothing+  bracket (create full dir eps) (const (remove full dir)) $ \_ -> do+    forM_ (zip spec.containers refs) $ \(c, ref) -> start full dir c ref+    forM_ bridgeRef $ \ref -> startBridge full dir eps ref+    addresses <- forM eps $ \e -> (,) (endpointName e) . (,) e <$> addressOf full dir e+    let p =+          Pod+            { full,+              folder = dir,+              endpoints = Map.fromList addresses,+              short = map (.name) spec.containers,+              bridge = full <> "-bridge" <$ bridgeRef+            }+    (waitReady spec p >> act p) `onException` printLogs p++-- | 'withPod' for a pod of one container, named after it.+withContainer :: ContainerSpec -> (Pod -> IO a) -> IO a+withContainer c = withPod (pod c.name [c])++-- | Why a spec cannot run, if it cannot.+check :: PodSpec -> Either String ()+check spec+  | not (goodName spec.name) = badName "pod" spec.name+  | null spec.containers = Left "a pod needs a container"+  | n : _ <- filter (not . goodName) names = badName "container" n+  | n : _ <- dups names = Left ("two containers are named " <> n)+  | "bridge" `elem` names = Left "the container name bridge is that of the bridge of the pod"+  | n : _ <- filter (not . goodName) eps = badName "endpoint" n+  | n : _ <- dups eps = Left ("two endpoints are named " <> n)+  | otherwise = Right ()+  where+    names = map (.name) spec.containers+    eps = [endpointName e | c <- spec.containers, e <- c.endpoints]+    goodName s = not (null s) && all (\c -> isAsciiLower c || isDigit c || c == '-') s+    badName what n = Left ("the " <> what <> " name " <> show n <> " is not lowercase letters, digits and dashes")+    dups xs = [x | x <- nub xs, length (filter (== x) xs) > 1]++isBridged :: Endpoint -> Bool+isBridged = \case+  Bridged _ _ -> True+  _ -> False++isPublished :: Endpoint -> Bool+isPublished = \case+  Published _ _ -> True+  _ -> False++-- | Make the folder of a pod and the pod. The folder is open to everyone, so+-- that a service that runs as another user than the tests can make its+-- socket in it; it is in the folder of the run, under the base folder,+-- which is the user's alone ('Test.Podman.Run.privateFolder'), so no other+-- user of the machine can enter it.+create :: String -> FilePath -> [Endpoint] -> IO ()+create full dir eps =+  bracketOnError (createDirectory dir >> setFileMode dir 0o777) (const (remove full dir)) $ \_ -> do+    let published = [p | Published _ p <- eps]+        network+          | null published = ["--network", "none"]+          | otherwise = concat [["--publish", "127.0.0.1::" <> show p] | p <- published]+    void . podman $ ["pod", "create", "--name", full, "--label", runLabel <> "=" <> runName] <> network++-- | Remove a pod with its containers, and its folder. Nothing that fails+-- here is an error: the next run removes what is left.+remove :: String -> FilePath -> IO ()+remove full dir = do+  void $ try @SomeException (podman ["pod", "rm", "--force", "--time", "0", full])+  void $ try @SomeException (removeDirectoryRecursive dir)++-- | The arguments of @podman run@ that every container of a pod has. A+-- stopped container stays until its pod goes, so that its log can be read.+runArgs :: String -> FilePath -> String -> [String]+runArgs full dir n =+  [ "run",+    "--detach",+    "--pod",+    full,+    "--name",+    full <> "-" <> n,+    "--label",+    runLabel <> "=" <> runName,+    -- every container of the pod shares the folder, so it is labelled for+    -- SELinux as shared (z), not as private to one container (Z)+    "--volume",+    dir <> ":" <> socketFolder <> ":z"+  ]++start :: String -> FilePath -> ContainerSpec -> String -> IO ()+start full dir c ref =+  void . podman $+    runArgs full dir c.name+      <> maybe [] (\m -> ["--memory", m]) c.memory+      <> concat [["--tmpfs", path <> ":rw,size=" <> size <> ",mode=1777"] | (path, size) <- c.tmpfs]+      <> concat [["--env", k <> "=" <> v] | (k, v) <- c.env]+      <> maybe [] (\e -> ["--entrypoint", e]) c.entrypoint+      <> c.options+      <> [ref]+      <> c.command++-- | Start the bridge of a pod: a socat for each 'Bridged' endpoint, which+-- makes the socket and joins each connection to it to the port of the+-- service. It runs as root of its container, which is the user of the tests+-- on the host, so the sockets are theirs. A pod without a 'Bridged' endpoint+-- has one too when it waits for a 'Published' endpoint to accept+-- connections: the bridge is where that port is tried from inside the pod.+startBridge :: String -> FilePath -> [Endpoint] -> String -> IO ()+startBridge full dir eps ref =+  void . podman $+    runArgs full dir "bridge" <> ["--memory", "64m", "--entrypoint", "sh", ref, "-c", script]+  where+    script =+      concat+        [ "socat UNIX-LISTEN:" <> socketInside n <> ",fork,mode=777,unlink-early TCP:127.0.0.1:" <> show p <> " & "+        | Bridged n p <- eps+        ]+        <> "while :; do sleep 3600; done"++-- | The address of an endpoint of a pod that runs. The ports of a pod are+-- published by the pod itself, so the port of a 'Published' endpoint is+-- asked of the container that Podman keeps for the network of the pod: it+-- runs for as long as the pod, whatever its other containers do.+addressOf :: String -> FilePath -> Endpoint -> IO Address+addressOf full dir = \case+  Native n -> return (UnixSocket (dir </> (n <> ".sock")))+  Bridged n _ -> return (UnixSocket (dir </> (n <> ".sock")))+  Published _ p -> do+    infra <- podman ["pod", "inspect", full, "--format", "{{.InfraContainerID}}"]+    out <- podman ["port", infra, show p <> "/tcp"]+    case reverse (takeWhile (/= ':') (reverse (headOr "" (lines out)))) of+      digits | not (null digits), all isDigit digits -> return (TcpPort "127.0.0.1" (read digits))+      _ -> throwIO (BadSpec ("Podman published port " <> show p <> " nowhere: " <> out))+  where+    headOr d = \case+      x : _ -> x+      [] -> d++-- | Wait until every 'Readiness' of a spec holds, in their order, and give+-- up at the deadline of the spec. A container that stops on the way stops+-- the wait at once.+waitReady :: PodSpec -> Pod -> IO ()+waitReady spec p = do+  deadline <- (+ fromIntegral spec.readyWithin) <$> getMonotonicTime+  forM_ spec.ready $ \r -> poll deadline r (0.05 :: Double)+  where+    poll deadline r pause = do+      ok <- holds p r+      unless ok $ do+        stopped p >>= mapM_ (throwIO . Stopped)+        now <- getMonotonicTime+        when (now > deadline) $ throwIO (NotReady p.full (show r))+        threadDelay (round (pause * 1000000))+        poll deadline r (min 0.5 (pause * 1.5))++-- | Whether a 'Readiness' holds now.+holds :: Pod -> Readiness -> IO Bool+holds p = \case+  Accepts n -> case Map.lookup n p.endpoints of+    Nothing -> throwIO (NoSuch n)+    Just (Native _, a) -> accepts a+    Just (Bridged _ port, a) -> (&&) <$> accepts a <*> inside port+    Just (Published _ port, _) -> inside port+  LogLine c text -> isInfixOf text <$> logs p c+  Succeeds c cmd -> do+    (code, _, _) <- podmanStatus 120 (["exec", containerName p c] <> cmd)+    return (code == ExitSuccess)+  Probe _ f -> f p+  where+    accepts a = either (const False) (const True) <$> try @SomeException (connectTo a >>= close)+    -- a TCP connection to the port, from the bridge, in the network of the pod+    inside port = case p.bridge of+      Nothing -> return False+      Just b -> do+        (code, _, _) <- podmanStatus 120 ["exec", b, "socat", "-u", "OPEN:/dev/null", "TCP:127.0.0.1:" <> show port]+        return (code == ExitSuccess)++-- | The containers of a pod that have stopped, if any.+stopped :: Pod -> IO [String]+stopped p = do+  out <- podman ["ps", "--all", "--filter", "pod=" <> p.full, "--format", "{{.Names}} {{.State}}"]+  return [n | [n, st] <- map words (lines out), st `elem` ["exited", "stopped", "dead"]]++-- | Print the last lines of the log of every container of a pod.+printLogs :: Pod -> IO ()+printLogs p = forM_ (p.short <> ["bridge" | Just _ <- [p.bridge]]) $ \c -> do+  r <- try @SomeException (podmanStatus 60 ["logs", "--tail", "40", containerName p c])+  case r of+    Right (_, out, err) -> hPutStrLn stderr ("--- the log of " <> containerName p c <> ":\n" <> out <> err)+    Left _ -> return ()++-- | The address of an endpoint of a pod, by its name. Throws 'NoSuch' if the+-- pod has no endpoint of the name.+address :: Pod -> String -> Address+address p n = maybe (throw (NoSuch n)) snd (Map.lookup n p.endpoints)++-- | The name of the pod, as @podman pod ps@ shows it.+podName :: Pod -> String+podName p = p.full++-- | The name of a container of the pod, as @podman ps@ shows it, from its+-- name in the spec.+containerName :: Pod -> String -> String+containerName p c = p.full <> "-" <> c++-- | Run a command in a container of the pod, as @podman exec@ does, and give+-- what it printed. Throws a t'PodmanError' if it fails or takes more than two+-- minutes.+exec :: Pod -> String -> [String] -> IO String+exec = execWithin 120++-- | 'exec' with a deadline of so many seconds.+execWithin :: Int -> Pod -> String -> [String] -> IO String+execWithin secs p c cmd = podmanWithin secs (["exec", containerName p c] <> cmd)++-- | The log of a container of the pod, its standard output and then its+-- standard error.+logs :: Pod -> String -> IO String+logs p c = (\(_, out, err) -> out <> err) <$> podmanStatus 60 ["logs", containerName p c]++-------------------------------------------------------------------------------+-- Addresses+-------------------------------------------------------------------------------++-- | Where the tests reach an endpoint.+data Address+  = -- | a Unix socket at this path on the host+    UnixSocket !FilePath+  | -- | a TCP port of this host, which is always @127.0.0.1@+    TcpPort !String !Int+  deriving (Eq, Ord, Show)++-- | The address as the @network@ package takes it.+sockAddr :: Address -> SockAddr+sockAddr (UnixSocket path) = SockAddrUnix path+sockAddr (TcpPort _ port) = SockAddrInet (fromIntegral port) (tupleToHostAddress (127, 0, 0, 1))++-- | A socket connected to an address. The caller closes it.+connectTo :: Address -> IO Socket+connectTo a = bracketOnError (socket family Stream defaultProtocol) close $ \s -> s <$ connect s (sockAddr a)+  where+    family = case a of+      UnixSocket _ -> AF_UNIX+      TcpPort _ _ -> AF_INET
+ src/Test/Podman/Command.hs view
@@ -0,0 +1,211 @@+-- |+-- Module      : Test.Podman.Command+-- Copyright   : (c) 2026 JP Rupp+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- Running the @podman@ command, and finding out whether it can run.+--+-- = Why the command line+--+-- Podman has a REST API on a Unix socket too, but it is a service that has+-- to be started, and its JSON changes between versions more than the flags+-- of the command do. The command is there wherever Podman is installed, and+-- what this library asks of it is a handful of flags that have not changed+-- in years. Each call is a process, which costs a few milliseconds: nothing+-- next to the start of a container.+--+-- = Why every call has a deadline+--+-- A test that hangs is worse than one that fails: CI kills it after an hour+-- and says nothing about why. A call to @podman@ can hang when its storage is+-- locked by a crashed process, or when a registry does not answer. So every+-- call here gives up after a deadline, and throws a t'PodmanError' that says+-- what it ran and what Podman printed.+--+-- = Which podman+--+-- The program is the one named by @PODMAN_TEST_PODMAN@, if it is set, or the+-- first @podman@ on the @PATH@, or else the one of the machine: in+-- @\/usr\/bin@, @\/usr\/local\/bin@, or @\/run\/current-system\/sw\/bin@+-- on NixOS ('findPodman'). The last is for builds in a pure Nix shell, as+-- @stack --nix@ makes them: the shell keeps the files of the machine but+-- leaves only packages of Nix on the @PATH@, so the tests would not find+-- the Podman that the machine has.+--+-- The machine's Podman cannot come from Nix: rootless Podman needs+-- @newuidmap@ and @newgidmap@, which must be setuid, and nothing in the+-- store of Nix can be. So it runs in an environment of its own+-- ('podmanEnvironment'): the folders of the machine at the end of the+-- @PATH@, where it finds those programs and its other helpers, NixOS's+-- @\/run\/wrappers\/bin@ first among them, and no @LD_LIBRARY_PATH@ or+-- @LD_PRELOAD@, which a shell of Nix may set, and which would make a+-- program of the machine load libraries of Nix. The program is looked for+-- once in a run.+module Test.Podman.Command+  ( -- * Running podman+    podman,+    podmanWithin,+    podmanStatus,+    PodmanError (..),++    -- * Whether podman can run+    podmanUsable,+    podmanPath,++    -- * Which podman+    findPodman,+    podmanEnvironment,+    machineFolders,+  )+where++import Control.Exception (Exception, throwIO)+import Data.Char (isSpace)+import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef)+import Data.List (dropWhileEnd, intercalate)+import System.Directory (doesFileExist, executable, getPermissions)+import System.Environment (getEnvironment, lookupEnv)+import System.Exit (ExitCode (..))+import System.FilePath (searchPathSeparator, splitSearchPath, (</>))+import System.IO.Unsafe (unsafePerformIO)+import System.Process (CreateProcess (..), proc, readCreateProcessWithExitCode)+import System.Timeout (timeout)++-- | A call to @podman@ that failed or ran out of time, with what it was+-- given and what it printed.+data PodmanError+  = -- | it exited with this code, and printed this on its standard error+    PodmanFailed ![String] !Int !String+  | -- | it did not end within so many seconds+    PodmanTimedOut ![String] !Int+  | -- | there is no podman to run, for this reason ('findPodman')+    PodmanMissing !String+  deriving (Eq)++instance Show PodmanError where+  show (PodmanFailed args code err) =+    "podman " <> unwords args <> " exited with " <> show code <> ": " <> trim err+  show (PodmanTimedOut args secs) =+    "podman " <> unwords args <> " did not end within " <> show secs <> " seconds"+  show (PodmanMissing why) = why++instance Exception PodmanError++-- | Run @podman@ with these arguments, and give what it printed on its+-- standard output, without the white space at its end. Throws a+-- t'PodmanError' if it fails, or if it takes more than two minutes.+podman :: [String] -> IO String+podman = podmanWithin 120++-- | 'podman' with a deadline of so many seconds, for what can take longer,+-- such as pulling or building an image.+podmanWithin :: Int -> [String] -> IO String+podmanWithin secs args =+  podmanStatus secs args >>= \case+    (ExitSuccess, out, _) -> return (trim out)+    (ExitFailure code, _, err) -> throwIO (PodmanFailed args code err)++-- | Run @podman@ and give its exit code and both of its outputs, whether it+-- succeeded or not, for a call whose failure is an answer, such as+-- @podman image exists@. Throws only if it does not end in time.+podmanStatus :: Int -> [String] -> IO (ExitCode, String, String)+podmanStatus secs args =+  found >>= \case+    Left why -> throwIO (PodmanMissing why)+    Right (program, environment) -> do+      let process = (proc program args) {env = Just environment}+      timeout (secs * 1000000) (readCreateProcessWithExitCode process "") >>= \case+        Nothing -> throwIO (PodmanTimedOut args secs)+        Just result -> return result++-- | The podman of this run and the environment to run it in, looked for at+-- the first call and kept.+found :: IO (Either String (FilePath, [(String, String)]))+found =+  readIORef foundRef >>= \case+    Just r -> return r+    Nothing -> do+      environment <- getEnvironment+      program <- findPodman environment+      let r = (\path -> (path, podmanEnvironment environment)) <$> program+      atomicModifyIORef' foundRef (\_ -> (Just r, r))++foundRef :: IORef (Maybe (Either String (FilePath, [(String, String)])))+foundRef = unsafePerformIO (newIORef Nothing)+{-# NOINLINE foundRef #-}++-- | The podman that the calls of this run use, if there is one.+podmanPath :: IO (Maybe FilePath)+podmanPath = either (const Nothing) (Just . fst) <$> found++-- | The folders of the machine where its programs are, in the order in which+-- they are looked in: NixOS's setuid wrappers and its system, then those+-- of every other Linux.+machineFolders :: [FilePath]+machineFolders =+  ["/run/wrappers/bin", "/run/current-system/sw/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"]++-- | Find the podman to run, in an environment: the program that+-- @PODMAN_TEST_PODMAN@ names, if it is set; the first @podman@ on the+-- @PATH@; or the first in the folders of the machine where Podman is+-- installed. Gives why there is none, if there is none.+findPodman :: [(String, String)] -> IO (Either String FilePath)+findPodman environment = case lookup "PODMAN_TEST_PODMAN" environment of+  Just named+    | not (null named) ->+        runnable named >>= \case+          True -> return (Right named)+          False -> return (Left ("PODMAN_TEST_PODMAN names " <> named <> ", which is not a program that can run"))+  _ -> first (map (</> "podman") (onPath <> installed))+  where+    onPath = maybe [] splitSearchPath (lookup "PATH" environment)+    installed = ["/usr/bin", "/usr/local/bin", "/run/current-system/sw/bin"]+    first = \case+      [] ->+        return . Left $+          "podman is not on the PATH, nor in "+            <> intercalate ", " installed+            <> ": install Podman, or name it with PODMAN_TEST_PODMAN"+      p : ps -> runnable p >>= \ok -> if ok then return (Right p) else first ps+    runnable p = do+      exists <- doesFileExist p+      if exists then executable <$> getPermissions p else return False++-- | The environment to run podman in, from that of the tests: the folders of+-- the machine at the end of the @PATH@, those that it does not have yet,+-- so that podman finds @newuidmap@ and its other helpers where the machine+-- has them; and no @LD_LIBRARY_PATH@ or @LD_PRELOAD@, which would make a+-- program of the machine load the libraries of a shell of Nix.+podmanEnvironment :: [(String, String)] -> [(String, String)]+podmanEnvironment environment =+  ("PATH", path) : [kv | kv@(k, _) <- environment, k `notElem` ["PATH", "LD_LIBRARY_PATH", "LD_PRELOAD"]]+  where+    current = maybe [] splitSearchPath (lookup "PATH" environment)+    path = intercalate [searchPathSeparator] (current <> [d | d <- machineFolders, d `notElem` current])++-- | Whether this machine can run the containers of the tests, and why not if+-- it cannot: @Right ()@, or @Left@ a reason to show for the tests that are+-- skipped.+--+-- It cannot when @PODMAN_TEST_SKIP@ is set, to any value, when there is no+-- podman to run ('findPodman'), or when @podman info@ fails, as it does+-- when the user has no subordinate IDs for rootless containers. A test framework can+-- mark the tests as pending with the reason, so that a machine without+-- Podman runs the rest of the tests and says what it left out.+podmanUsable :: IO (Either String ())+podmanUsable =+  lookupEnv "PODMAN_TEST_SKIP" >>= \case+    Just _ -> return (Left "PODMAN_TEST_SKIP is set")+    Nothing ->+      found >>= \case+        Left why -> return (Left why)+        Right _ ->+          podmanStatus 60 ["info", "--format", "{{.Host.Arch}}"] >>= \case+            (ExitSuccess, _, _) -> return (Right ())+            (_, _, err) -> return (Left ("podman info failed: " <> trim err))++trim :: String -> String+trim = dropWhileEnd isSpace . dropWhile isSpace
+ src/Test/Podman/Image.hs view
@@ -0,0 +1,126 @@+-- |+-- Module      : Test.Podman.Image+-- Copyright   : (c) 2026 JP Rupp+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- The images that containers run: one of a registry, or one built from a+-- recipe that the tests carry.+--+-- = Pinned, so that a test means the same thing every time+--+-- A tag of a registry, such as @redis:7@, points at another image whenever+-- its owner pushes one, and a test that passed yesterday fails today with no+-- change of its own. Name an image of a registry by its digest, as in+-- @docker.io\/library\/redis:7-alpine\@sha256:…@, and it is the same image+-- for ever.+--+-- An image built here is tagged by a hash of its recipe and its files, as in+-- @localhost\/regtest:3f2a…@. A change of the recipe is a new tag, so a test+-- never runs an image built from an older recipe, and the old one is still+-- there for an older branch.+--+-- = Once, whatever runs at once+--+-- Eight test processes that start together would pull the same image eight+-- times, or build it eight times, each with a fresh layer cache. So pulling+-- and building take a lock of the machine for the image ("Test.Podman.Run"),+-- and look again whether the image is there once they have it: the first+-- process does the work, and the others find it done.+module Test.Podman.Image+  ( Image (..),+    ImageSpec (..),+    imageReference,+    ensureImage,+  )+where++import Control.Exception (finally)+import Control.Monad (forM_, unless)+import Crypto.Hash.SHA256 qualified as SHA256+import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.ByteString.Char8 qualified as C+import Data.Char (isAlphaNum, toLower)+import Numeric (showHex)+import System.Directory (createDirectoryIfMissing, removeDirectoryRecursive)+import System.Exit (ExitCode (..))+import System.FilePath (takeDirectory, (</>))+import Test.Podman.Command (podmanStatus, podmanWithin)+import Test.Podman.Run (nextNumber, runFolder, withLock)++-- | The image of a container.+data Image+  = -- | an image of a registry, by its full reference, best pinned by its+    -- digest: @docker.io\/library\/redis:7-alpine\@sha256:…@. An image that+    -- the machine has already, such as one that a script built, is named+    -- the same way, as @localhost\/NAME:TAG@: nothing is pulled when Podman+    -- has the image.+    Registry !String+  | -- | an image built from a recipe+    Built !ImageSpec+  deriving (Eq, Show)++-- | The recipe of an image to build: what @podman build@ is given.+data ImageSpec = ImageSpec+  { -- | the name of the image, without a registry or a tag, such as+    -- @regtest@: it is built as @localhost\/NAME:HASH@+    name :: !String,+    -- | the Containerfile+    containerfile :: !ByteString,+    -- | the files of the context of the build, by their paths in it, for the+    -- @COPY@ and @ADD@ of the Containerfile+    files :: ![(FilePath, ByteString)]+  }+  deriving (Eq, Show)++-- | The reference by which Podman knows an image: the one given for an image+-- of a registry, and @localhost\/NAME:HASH@ for one to build, where the hash+-- is that of the Containerfile and every file of the context.+imageReference :: Image -> String+imageReference (Registry ref) = ref+imageReference (Built spec) = "localhost/" <> map clean spec.name <> ":" <> take 16 (hex digest)+  where+    clean c = if isAlphaNum c || c `elem` ("-_." :: String) then toLower c else '-'+    digest =+      SHA256.hash . B.concat $+        part spec.containerfile : concat [[part (C.pack path), part bytes] | (path, bytes) <- spec.files]+    -- each piece with its length, so that two recipes never hash the same by+    -- moving bytes from one piece to the next+    part bytes = C.pack (show (B.length bytes) <> ":") <> bytes+    hex = concatMap (\w -> let s = showHex w "" in if length s < 2 then '0' : s else s) . B.unpack++-- | Make sure that Podman has the image, pulling or building it if it does+-- not, and give its reference. One process of the machine does the work+-- while the others wait for it.+ensureImage :: Image -> IO String+ensureImage image = do+  let ref = imageReference image+  have <- exists ref+  unless have . withLock (lockName ref) $ do+    -- another process may have made it while this one waited+    again <- exists ref+    unless again $ case image of+      Registry _ -> () <$ podmanWithin 1800 ["pull", "--quiet", ref]+      Built spec -> build ref spec+  return ref+  where+    exists ref = (\(code, _, _) -> code == ExitSuccess) <$> podmanStatus 60 ["image", "exists", ref]+    lockName ref = "image-" <> take 32 (concatMap (\w -> showHex w "") (B.unpack (SHA256.hash (C.pack ref))))++-- | Build an image from its recipe, in a context folder of its own in the+-- folder of this run, which is removed afterwards.+build :: String -> ImageSpec -> IO ()+build ref spec = do+  n <- nextNumber+  dir <- (</> ("build-" <> show n)) <$> runFolder+  flip finally (removeDirectoryRecursive dir) $ do+    createDirectoryIfMissing True dir+    B.writeFile (dir </> "Containerfile") spec.containerfile+    forM_ spec.files $ \(path, bytes) -> do+      createDirectoryIfMissing True (takeDirectory (dir </> path))+      B.writeFile (dir </> path) bytes+    _ <- podmanWithin 1800 ["build", "--quiet", "--layers", "--tag", ref, "--file", dir </> "Containerfile", dir]+    return ()
+ src/Test/Podman/Run.hs view
@@ -0,0 +1,286 @@+-- |+-- Module      : Test.Podman.Run+-- Copyright   : (c) 2026 JP Rupp+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- What sets one run of the tests apart from every other: its name, its+-- folder of sockets, the names of its containers, and the clean-up of what+-- runs that died left behind.+--+-- = A run+--+-- A run is one process: a test binary, or one of the processes that a tool+-- such as haskell-dev starts to run the tests in parallel. Its name is its+-- process ID and the time at which the process started, as the kernel keeps+-- it in @\/proc@. The process ID alone is not enough: the kernel gives the+-- numbers out again, and a new process with the number of a dead run would+-- keep that run's containers alive for ever.+--+-- Every pod and container of a run carries the label @podman-test.run@ with+-- its name, and every pod has a folder under the folder of the run.+--+-- = Clean-up without a reaper+--+-- A run removes its containers when the tests that use them end, even when+-- they fail. A run that is killed cannot, so the first pod of every run looks+-- for pods and folders of runs whose process is gone, and removes them. A+-- live run is never touched: its process exists, with the same start time.+-- There is no reaper container to start, as the Docker world uses: the next+-- run is the reaper.+--+-- = The folder+--+-- Unix sockets have a short limit on the length of their path, 107 bytes on+-- Linux, so the folder has to be short: @$XDG_RUNTIME_DIR\/podman-test@,+-- which is in memory and private to the user, or @\/tmp\/podman-test-UID@+-- where there is no runtime folder. @PODMAN_TEST_DIR@ chooses another.+--+-- = Private to the user+--+-- The folder of each pod is open to everyone, so that a service that runs+-- as another user in its container can make its socket there, and such a+-- socket is open to everyone, so that the tests can connect to it. What+-- keeps other users of the machine out is the folder above them all, which+-- must be the user's alone ('privateFolder'): made with no access for+-- anyone else, and refused if it is not a folder of the user, as when+-- another user made @\/tmp\/podman-test-UID@ first, or put a link to a+-- folder of theirs there. A folder of the user that others may read is+-- closed to them. Without that, another user could reach the services of+-- the tests, which have no password, or put files in the folders of their+-- sockets.+module Test.Podman.Run+  ( -- * The run+    runName,+    runFolder,+    baseFolder,+    privateBase,+    privateFolder,+    UnsafeFolder (..),+    nextNumber,+    runLabel,++    -- * Clean-up+    removeStale,+    removeStaleRuns,++    -- * Locks+    withLock,+  )+where++import Control.Concurrent.MVar (MVar, newMVar, withMVar)+import Control.Exception (Exception, SomeException, bracket, catch, evaluate, throwIO, try)+import Control.Monad (forM_, unless, void, when)+import Data.Bits ((.&.))+import Data.Char (isDigit)+import Data.IORef (IORef, atomicModifyIORef', newIORef)+import Data.Map.Strict qualified as Map+import GHC.IO.Handle.Lock (LockMode (..), hLock)+import System.Directory+  ( createDirectoryIfMissing,+    doesDirectoryExist,+    listDirectory,+    removeDirectoryRecursive,+  )+import System.Environment (lookupEnv)+import System.FilePath (takeDirectory, (</>))+import System.IO (IOMode (..), hClose, openFile)+import System.IO.Error (isAlreadyExistsError)+import System.IO.Unsafe (unsafePerformIO)+import System.Posix.Directory (createDirectory)+import System.Posix.Files+  ( fileMode,+    fileOwner,+    getSymbolicLinkStatus,+    isDirectory,+    isSymbolicLink,+    setFileMode,+  )+import System.Posix.Process (getProcessID)+import System.Posix.User (getEffectiveUserID)+import Test.Podman.Command (podman)++-- | The label that every pod and container of a run carries, with the name+-- of the run as its value.+runLabel :: String+runLabel = "podman-test.run"++-- | The name of this run: its process ID and the start time of its process,+-- joined by a dash, as in @4242-918273@.+runName :: String+runName = unsafePerformIO $ do+  pid <- show <$> getProcessID+  started <- maybe "0" id <$> startTime pid+  return (pid <> "-" <> started)+{-# NOINLINE runName #-}++-- | The start time of a process, in the clock ticks since the boot of the+-- machine that the kernel counts, if the process exists and the system has+-- @\/proc@.+startTime :: String -> IO (Maybe String)+startTime pid = do+  r <- try (readFile ("/proc" </> pid </> "stat") >>= evaluate . fieldOf)+  return $ case r of+    Left (_ :: SomeException) -> Nothing+    Right v -> v+  where+    -- the name of the program, the second field, may hold spaces and+    -- brackets, so the fields are counted from after its last bracket: the+    -- start time is the 22nd field, the 20th after the name+    fieldOf s = case drop 19 (words (afterName s)) of+      t : _ | all isDigit t -> Just t+      _ -> Nothing+    afterName s = case break (== ')') (reverse s) of+      (rest, _ : _) -> reverse rest+      _ -> s++-- | Whether the run of this name is still going: its process exists and+-- started when the name says. Where there is no @\/proc@, every run is taken+-- to be going, so that nothing of a live run is ever removed.+alive :: String -> IO Bool+alive name = case break (== '-') name of+  (pid, '-' : started)+    | not (null pid),+      all isDigit pid -> do+        proc <- doesDirectoryExist "/proc/self"+        if not proc then return True else (== Just started) <$> startTime pid+  _ -> return True++-- | The folder under which every run has its own: @PODMAN_TEST_DIR@ if it is+-- set, @$XDG_RUNTIME_DIR\/podman-test@ if there is a runtime folder, and+-- @\/tmp\/podman-test-UID@ otherwise.+baseFolder :: IO FilePath+baseFolder =+  lookupEnv "PODMAN_TEST_DIR" >>= \case+    Just dir | not (null dir) -> return dir+    _ ->+      lookupEnv "XDG_RUNTIME_DIR" >>= \case+        Just dir | not (null dir) -> return (dir </> "podman-test")+        _ -> ("/tmp/podman-test-" <>) . show <$> getEffectiveUserID++-- | 'baseFolder', made private to the user ('privateFolder').+privateBase :: IO FilePath+privateBase = do+  dir <- baseFolder+  privateFolder dir+  return dir++-- | A folder that cannot be made private to the user, and why.+data UnsafeFolder = UnsafeFolder !FilePath !String+  deriving (Eq)++instance Show UnsafeFolder where+  show (UnsafeFolder path why) =+    "The folder "+      <> path+      <> " of podman-test is not private to this user: "+      <> why+      <> ". Remove it, or choose another with PODMAN_TEST_DIR."++instance Exception UnsafeFolder++-- | Make sure that a folder is the user's alone: make it, with its parents,+-- with no access for anyone else if it is not there; take away the access+-- of others if it is a folder of the user's that others may use; and throw+-- t'UnsafeFolder' if it is a link, not a folder, or a folder of another+-- user, none of which the user can trust.+privateFolder :: FilePath -> IO ()+privateFolder dir = do+  createDirectoryIfMissing True (takeDirectory dir)+  made <- try (createDirectory dir 0o700)+  case made of+    Left e | not (isAlreadyExistsError e) -> ioError e+    _ -> return ()+  st <- getSymbolicLinkStatus dir+  me <- getEffectiveUserID+  when (isSymbolicLink st) $ throwIO (UnsafeFolder dir "it is a symbolic link")+  unless (isDirectory st) $ throwIO (UnsafeFolder dir "it is not a folder")+  when (fileOwner st /= me) $+    throwIO (UnsafeFolder dir ("it belongs to another user, of UID " <> show (fileOwner st)))+  when (fileMode st .&. 0o077 /= 0) $ setFileMode dir 0o700++-- | The folder of this run, made if it is not there, in the private base+-- folder.+runFolder :: IO FilePath+runFolder = do+  dir <- (</> runName) <$> privateBase+  createDirectoryIfMissing False dir+  return dir++counter :: IORef Int+counter = unsafePerformIO (newIORef 0)+{-# NOINLINE counter #-}++-- | A number that no other call in this run gets, from 1 up: what keeps the+-- names of two pods of the same run apart.+nextNumber :: IO Int+nextNumber = atomicModifyIORef' counter (\n -> (n + 1, n + 1))++cleaned :: IORef Bool+cleaned = unsafePerformIO (newIORef False)+{-# NOINLINE cleaned #-}++-- | 'removeStaleRuns' once in a run: the first call does it, and later+-- calls do nothing. 'Test.Podman.withPod' calls it.+removeStale :: IO ()+removeStale = do+  first <- atomicModifyIORef' cleaned (\done -> (True, not done))+  when first removeStaleRuns++-- | Remove the pods, with their containers, and the folders of runs whose+-- process is gone. Nothing of a run that is going is ever removed, and a+-- failure to remove something is not an error: a run that cannot clean up+-- still runs.+removeStaleRuns :: IO ()+removeStaleRuns = do+  -- the names of the pods of every run, and the run of each from the label:+  -- podman pod ps writes labels differently from one version of Podman to+  -- the next, but podman pod inspect keeps them in a map in every one+  pods <-+    lines+      <$> podman ["pod", "ps", "--filter", "label=" <> runLabel, "--format", "{{.Name}}"]+        `catch` \(_ :: SomeException) -> return []+  forM_ pods $ \pod -> do+    let labelOf = "{{index .Labels \"" <> runLabel <> "\"}}"+    label <- try @SomeException (podman ["pod", "inspect", pod, "--format", labelOf])+    case label of+      Right name | not (null name) -> do+        going <- alive name+        unless going . void $+          try @SomeException (podman ["pod", "rm", "--force", "--time", "0", pod])+      _ -> return ()+  base <- privateBase+  exists <- doesDirectoryExist base+  when exists $ do+    names <- listDirectory base+    forM_ [n | n <- names, n /= "locks"] $ \name -> do+      going <- alive name+      unless going . void $ try @SomeException (removeDirectoryRecursive (base </> name))++-- | Run an action while holding the lock of this name, which every run of+-- the machine shares: for what two runs must not do at once, such as+-- building the same image. The lock is a file under the base folder, locked+-- with @flock@, which the kernel lets go of if the process dies.+--+-- The threads of one process take turns at it first, with a lock of the+-- process: GHC does not let a process open one file for writing twice, so+-- the second thread would fail to open the file instead of waiting.+withLock :: String -> IO a -> IO a+withLock name act = do+  fresh <- newMVar ()+  turn <- atomicModifyIORef' locks $ \m -> case Map.lookup name m of+    Just old -> (m, old)+    Nothing -> (Map.insert name fresh m, fresh)+  withMVar turn $ \_ -> do+    dir <- (</> "locks") <$> privateBase+    createDirectoryIfMissing False dir+    bracket (openFile (dir </> name) ReadWriteMode) hClose $ \h -> do+      hLock h ExclusiveLock+      act++locks :: IORef (Map.Map String (MVar ()))+locks = unsafePerformIO (newIORef Map.empty)+{-# NOINLINE locks #-}
+ test/Spec.hs view
@@ -0,0 +1,1 @@+{-# OPTIONS_GHC -F -pgmF hspec-discover #-}
+ test/Test/PodmanSpec.hs view
@@ -0,0 +1,321 @@+-- |+-- Module      : Test.PodmanSpec+-- Copyright   : (c) 2026 JP Rupp+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- Tests of the library against Podman: Redis, pinned by its digest, in pods+-- reached through a socket of its own, through a bridge and through a port;+-- a pod that needs no bridge and runs none;+-- two containers of a pod that talk on @localhost@; eight pods at once;+-- containers that stop, pods that are never ready, stale runs, specs that+-- cannot run, and images built by several processes at once.+--+-- The tests that need Podman are pending where 'podmanUsable' says that it+-- cannot run. Each group at the top is one thing, so that a tool that runs+-- the groups in parallel processes, such as haskell-dev, may do so.+module Test.PodmanSpec (spec) where++import Control.Concurrent.Async (mapConcurrently, replicateConcurrently)+import Control.Exception (bracket, try)+import Control.Monad (filterM, void)+import Data.Bits ((.&.))+import Data.ByteString.Char8 qualified as C+import Data.List (isInfixOf, isPrefixOf, nub)+import Network.Socket (close)+import Network.Socket.ByteString (recv, sendAll)+import System.Directory+  ( createDirectoryIfMissing,+    doesDirectoryExist,+    doesFileExist,+    doesPathExist,+    removePathForcibly,+  )+import System.Environment (setEnv, unsetEnv)+import System.Exit (ExitCode (..))+import System.FilePath ((</>))+import System.Posix.Files (createSymbolicLink, fileMode, fileOwner, getFileStatus, setFileMode)+import System.Posix.Types (FileMode)+import System.Posix.User (getEffectiveUserID)+import Test.Hspec+import Test.Podman+import Test.Podman.Command (findPodman, machineFolders, podmanEnvironment, podmanStatus)+import Test.Podman.Image (ensureImage, imageReference)+import Test.Podman.Run (baseFolder, privateFolder, removeStaleRuns, runFolder, runLabel)++-- | Redis, pinned by its digest.+redisImage :: Image+redisImage =+  Registry+    "docker.io/library/redis:7-alpine\+    \@sha256:ec1c2d3603c3d7d65b153bedda0248b641aa3bd7684503406b27b9e870ac0796"++-- | A Redis that listens on a TCP port, and on nothing else.+redisTcp :: ContainerSpec+redisTcp =+  (container "redis" redisImage)+    { command = ["redis-server", "--port", "6379", "--save", ""],+      memory = Just "128m"+    }++-- | A Redis that listens on a socket of its pod, open to everyone.+redisNative :: ContainerSpec+redisNative =+  redisTcp+    { command =+        [ "redis-server",+          "--port",+          "0",+          "--save",+          "",+          "--unixsocket",+          socketInside "redis",+          "--unixsocketperm",+          "777"+        ],+      endpoints = [Native "redis"]+    }++-- | What Redis answers to PING at an address.+ping :: Address -> IO String+ping a = bracket (connectTo a) close $ \s -> do+  sendAll s (C.pack "PING\r\n")+  C.unpack <$> recv s 64++-- | Whether Podman has a pod of this name.+podExists :: String -> IO Bool+podExists n = (\(code, _, _) -> code == ExitSuccess) <$> podmanStatus 60 ["pod", "exists", n]++-- | Whether Podman has a container of this name.+containerExists :: String -> IO Bool+containerExists n = (\(code, _, _) -> code == ExitSuccess) <$> podmanStatus 60 ["container", "exists", n]++spec :: Spec+spec = do+  usable <- runIO podmanUsable+  let podmanIt name test = it name $ either pendingWith (const test) usable++  describe "endpoints" $ do+    podmanIt "reaches a service on its own socket, and removes the pod and its folder after" $ do+      (name, dir) <- withContainer redisNative $ \p -> do+        let a = address p "redis"+        ping a `shouldReturn` "+PONG\r\n"+        case a of+          UnixSocket path -> do+            base <- baseFolder+            path `shouldSatisfy` (base `isPrefixOf`)+            return (podName p, takeFolder path)+          TcpPort _ _ -> fail "Not a socket"+      podExists name `shouldReturn` False+      doesDirectoryExist dir `shouldReturn` False++    podmanIt "bridges a TCP port to a socket of the user of the tests" $+      withContainer redisTcp {endpoints = [Bridged "redis" 6379]} $ \p -> do+        let a = address p "redis"+        ping a `shouldReturn` "+PONG\r\n"+        case a of+          UnixSocket path -> do+            me <- getEffectiveUserID+            fileOwner <$> getFileStatus path `shouldReturn` me+          TcpPort _ _ -> expectationFailure "Not a socket"++    podmanIt "publishes a TCP port on the loopback interface" $+      withContainer redisTcp {endpoints = [Published "redis" 6379]} $ \p -> do+        let a = address p "redis"+        case a of+          TcpPort host port -> do+            host `shouldBe` "127.0.0.1"+            port `shouldSatisfy` (> 0)+          UnixSocket _ -> expectationFailure "Not a port"+        ping a `shouldReturn` "+PONG\r\n"++    podmanIt "runs no bridge in a pod of published ports that is ready by a command of its own" $ do+      let published = redisTcp {endpoints = [Published "redis" 6379]}+          byCommand = (pod "plain" [published]) {ready = [Succeeds "redis" ["redis-cli", "ping"]]}+      withPod byCommand $ \p -> do+        containerExists (containerName p "redis") `shouldReturn` True+        containerExists (containerName p "bridge") `shouldReturn` False+        ping (address p "redis") `shouldReturn` "+PONG\r\n"++  describe "pods" $ do+    podmanIt "lets the containers of a pod reach each other on localhost" $ do+      let client =+            (container "client" redisImage)+              { entrypoint = Just "sh",+                command = ["-c", "while :; do sleep 3600; done"],+                memory = Just "64m"+              }+          spec' =+            (pod "pair" [redisTcp, client])+              { ready = [Succeeds "client" ["redis-cli", "-h", "127.0.0.1", "ping"]]+              }+      withPod spec' $ \p ->+        exec p "client" ["redis-cli", "-h", "127.0.0.1", "ping"] `shouldReturn` "PONG"++    podmanIt "runs eight pods at once, each with its own socket" $ do+      answers <- replicateConcurrently 8 . withContainer redisNative $ \p -> do+        let a = address p "redis"+        (,) a <$> ping a+      map snd answers `shouldBe` replicate 8 "+PONG\r\n"+      length (nub (map fst answers)) `shouldBe` 8++  describe "failures" $ do+    podmanIt "stops waiting when a container stops, and removes the pod" $ do+      r <-+        try . withContainer redisNative {command = [], entrypoint = Just "false"} $+          \p -> return (podName p)+      case r of+        Left (Stopped c) -> c `shouldSatisfy` ("-redis" `isSuffixOf'`)+        Left e -> expectationFailure ("Another error: " <> show e)+        Right _ -> expectationFailure "The pod was ready"++    podmanIt "gives up on a pod that is not ready in time" $ do+      let never = (pod "never" [redisTcp]) {ready = [LogLine "redis" "no such line"], readyWithin = 2}+      withPod never (\_ -> return ()) `shouldThrow` \case+        NotReady _ what -> "no such line" `isInfixOf` what+        _ -> False++    it "refuses a spec that cannot run" $ do+      let bad = pod "bad" [redisNative, redisNative]+      withPod bad (\_ -> return ()) `shouldThrow` \case+        BadSpec _ -> True+        _ -> False+      withPod (pod "Bad Name" [redisNative]) (\_ -> return ()) `shouldThrow` \case+        BadSpec _ -> True+        _ -> False++    podmanIt "refuses a socket whose path is too long for Linux" $ do+      let long = redisNative {endpoints = [Native (replicate 100 'a')]}+      withContainer long (\_ -> return ()) `shouldThrow` \case+        BadSpec _ -> True+        _ -> False++  describe "stale runs" $+    podmanIt "removes the pods and folders of runs that died, and nothing of one that runs" $ do+      let dead = "999999999-1"+          stale = "pt-" <> dead <> "-1-stale"+      void $ podmanStatus 60 ["pod", "rm", "--force", stale]+      void $ podmanStatus 60 ["pod", "create", "--name", stale, "--label", runLabel <> "=" <> dead]+      base <- baseFolder+      createDirectoryIfMissing True (base </> dead </> "1")+      mine <- runFolder+      removeStaleRuns+      podExists stale `shouldReturn` False+      doesPathExist (base </> dead) `shouldReturn` False+      doesDirectoryExist mine `shouldReturn` True++  describe "private folders" $ do+    it "makes a missing folder for the user alone, and closes one of the user's to others" $ do+      sandbox <- (</> "private-test") <$> runFolder+      createDirectoryIfMissing True sandbox+      let fresh = sandbox </> "fresh"+          open = sandbox </> "open"+      privateFolder fresh+      modeOf fresh `shouldReturn` 0o700+      createDirectoryIfMissing True open+      setFileMode open 0o755+      privateFolder open+      modeOf open `shouldReturn` 0o700++    it "refuses a link and a file in place of the folder" $ do+      sandbox <- (</> "private-test") <$> runFolder+      createDirectoryIfMissing True (sandbox </> "target")+      let link = sandbox </> "link"+          file = sandbox </> "file"+      removePathForcibly link+      createSymbolicLink (sandbox </> "target") link+      privateFolder link `shouldThrow` \(UnsafeFolder _ why) -> "link" `isInfixOf` why+      writeFile file ""+      privateFolder file `shouldThrow` \(UnsafeFolder _ why) -> "not a folder" `isInfixOf` why++    podmanIt "refuses a folder of another user" $ do+      -- root of a container is the user of the tests; another user of the+      -- container is a subordinate ID on the host, so a folder that root of+      -- the container gives to one belongs to another user of the machine+      sandbox <- (</> "private-test") <$> runFolder+      createDirectoryIfMissing True sandbox+      ref <- ensureImage redisImage+      let script = "mkdir -p /x/theirs && chown 999:999 /x/theirs"+      void $ podman ["run", "--rm", "--volume", sandbox <> ":/x:z", "--entrypoint", "sh", ref, "-c", script]+      privateFolder (sandbox </> "theirs") `shouldThrow` \(UnsafeFolder _ why) -> "another user" `isInfixOf` why++  describe "images" $ do+    it "names a built image by the hash of its recipe" $ do+      let recipe = ImageSpec {name = "Echo Test", containerfile = C.pack "FROM scratch\n", files = []}+          ref = imageReference (Built recipe)+      ref `shouldSatisfy` ("localhost/echo-test:" `isPrefixOf`)+      imageReference (Built recipe {files = [("a", C.pack "b")]}) `shouldNotBe` ref+      imageReference (Built recipe) `shouldBe` ref++    podmanIt "builds an image once for several builds at once, and runs it" $ do+      let base = case redisImage of+            Registry r -> r+            Built _ -> error "not a registry image"+          recipe =+            ImageSpec+              { name = "podman-test-spec",+                containerfile = C.pack ("FROM " <> base <> "\nCOPY hello.txt /hello.txt\n"),+                files = [("hello.txt", C.pack "hello")]+              }+          image = Built recipe+      void $ podmanStatus 60 ["image", "rm", "--force", imageReference image]+      let reader =+            (container "reader" image)+              { entrypoint = Just "sh",+                command = ["-c", "while :; do sleep 3600; done"],+                memory = Just "64m"+              }+      let readIt _ = withContainer reader (\p -> exec p "reader" ["cat", "/hello.txt"])+      outs <- mapConcurrently readIt [1 .. 3 :: Int]+      outs `shouldBe` replicate 3 "hello"++  describe "which podman" $ do+    it "runs podman with the folders of the machine on its PATH, and without the libraries of a shell" $ do+      let environment =+            [ ("PATH", "/nix/store/x/bin:/usr/bin"),+              ("LD_LIBRARY_PATH", "/nix/store/y/lib"),+              ("LD_PRELOAD", "z"),+              ("HOME", "/h")+            ]+          adjusted = podmanEnvironment environment+      lookup "LD_LIBRARY_PATH" adjusted `shouldBe` Nothing+      lookup "LD_PRELOAD" adjusted `shouldBe` Nothing+      lookup "HOME" adjusted `shouldBe` Just "/h"+      let folders = maybe [] (splitOn ':') (lookup "PATH" adjusted)+      take 2 folders `shouldBe` ["/nix/store/x/bin", "/usr/bin"]+      filter (`elem` machineFolders) folders `shouldMatchList` machineFolders++    podmanIt "finds the podman of the machine when the PATH has none, as in a pure shell of Nix" $ do+      let installed = ["/usr/bin/podman", "/usr/local/bin/podman", "/run/current-system/sw/bin/podman"]+      machine <- filterM doesFileExist installed+      case machine of+        [] -> pendingWith "this machine has no podman in its usual folders"+        p : _ -> findPodman [("PATH", "/nix/store/none/bin")] `shouldReturn` Right p++    it "takes the podman that PODMAN_TEST_PODMAN names, and refuses one that cannot run" $ do+      sandbox <- (</> "which-test") <$> runFolder+      createDirectoryIfMissing True sandbox+      let fake = sandbox </> "my-podman"+          missing = sandbox </> "no-podman"+      writeFile fake "#!/bin/sh\n"+      setFileMode fake 0o755+      findPodman [("PODMAN_TEST_PODMAN", fake), ("PATH", "/nowhere")] `shouldReturn` Right fake+      findPodman [("PODMAN_TEST_PODMAN", missing)] >>= \case+        Left why -> why `shouldSatisfy` isInfixOf missing+        Right p -> expectationFailure ("Took " <> p)++  describe "podmanUsable" $+    it "says why it cannot run when PODMAN_TEST_SKIP is set" $+      withSkip $+        podmanUsable `shouldReturn` Left "PODMAN_TEST_SKIP is set"+  where+    splitOn c xs = case break (== c) xs of+      (a, _ : rest) -> a : splitOn c rest+      (a, []) -> [a]+    modeOf :: FilePath -> IO FileMode+    modeOf path = (.&. 0o777) . fileMode <$> getFileStatus path+    takeFolder = reverse . drop 1 . dropWhile (/= '/') . reverse+    isSuffixOf' s x = reverse s `isPrefixOf` reverse x+    withSkip act = bracket (setEnv "PODMAN_TEST_SKIP" "1") (const (unsetEnv "PODMAN_TEST_SKIP")) (const act)