packages feed

sandwich-contexts-kubernetes 0.1.3.0 → 0.2.0.0

raw patch · 24 files changed

+2170/−190 lines, 24 filesdep +timedep +toml-parserdep ~sandwich-contexts

Dependencies added: time, toml-parser

Dependency ranges changed: sandwich-contexts

Files

+ CHANGELOG.md view
@@ -0,0 +1,59 @@+# Changelog for sandwich-contexts-kubernetes++## 0.2.0.0++* Add `Test.Sandwich.Contexts.Kubernetes.MetricsServer` to install the metrics-server (so `kubectl top` / the metrics API work), with configurable manifest source and `--kubelet-insecure-tls`.+* Add `Test.Sandwich.Contexts.Kubernetes.OOMWatcher` to detect OOMKilled containers, via a streaming pod watch (`withOOMWatcher`) or a one-shot check (`checkForOOMKills`).+* Add `Test.Sandwich.Contexts.Kubernetes.ResourceWatcher` to record per-pod CPU, memory and network usage over a test by polling the kubelet summary API (no metrics-server needed), writing a CSV, peak summaries, and SVG charts. All three watchers default to cluster-wide and can be scoped to a namespace.+* Make metrics-server installation on kind clusters configurable via `kindClusterMetricsServer` (defaults on, bumped to v0.7.2) instead of always installing v0.6.4.+* Clean up leftover container-runtime volumes and per-profile state dirs after tearing down a Minikube cluster.+* SeaweedFS: install the CSI driver (`seaweedFsCsiDriver`) and a standalone S3 gateway (`seaweedFsS3`), both on by default, and build the operator image with Nix. `SeaweedFSContext` now has the CSI `StorageClass`.+* BREAKING CHANGE: `seaweedFsImage` is now an `ImageLoadSpec` rather than `Text`.+* SeaweedFS: add `seaweedFsExtraImages` to preload extra images, and `seaweedFsOperatorImageExpr` to choose the Nix expression for the operator image.+* SeaweedFS: `SeaweedFSContext` now has the filer JWT signing keys.+* SeaweedFS: add `fastSeaweedFSOptions` for faster startup, along with the options it uses: `seaweedFsMasterConcurrentStart`, `seaweedFsServerExtraArgs`, and readiness/liveness probe overrides.+* SeaweedFS: add `seaweedFsFilerConfig` to choose the filer store.+* Add `minikubeClusterExtraEnv` to set environment variables on every `minikube` invocation.+* BREAKING CHANGE: `loadImageIfNecessary` and `loadImageIfNecessary'` now return the image name the cluster knows the image by. The SeaweedFS server image is now loaded only if the cluster doesn't have it already.+* Add `Test.Sandwich.Contexts.Kubernetes.SeaweedFSMini`, a single-pod SeaweedFS without the operator. It starts much faster and provides the same `SeaweedFSContext`.+* Add `postgresK8SExtraEnv` to pass extra environment variables to the Postgres container.+* Add `minikubeClusterForceRemove` to tear down a docker-driver cluster by removing its containers instead of running `minikube delete`.+* `withKubectlLogs` now follows the logs (previously it only captured what was there at startup) and prefixes each line with a timestamp.+* Fix `withKubectlPortForward` never restarting the forward after it exits, leaving the local port unbound for the rest of the run.+* Gate the Postgres readiness probe on the pod IP, so it doesn't report ready against the temporary server the entrypoint runs during setup.+* Retry `minikube image load` when it reports a transient push failure, instead of failing the cluster context outright.+* BREAKING CHANGE: new fields in `SeaweedFSOptions`, `SeaweedFSContext`, `KindClusterOptions`, `MinikubeClusterOptions`, `PostgresK8SOptions` and `KubernetesClusterType`. Build these by updating the defaults rather than with the constructor.++## 0.1.3.0++* Add `Test.Sandwich.Contexts.Kubernetes.PostgresServer`.+* Add `Test.Sandwich.Contexts.Kubernetes.Typesense`.+* Support reading the image name from OCI images.+* Be able to install the MinIO operator from Nix.+* Be able to install Kata Containers from a Helm chart, and drop the legacy KataContainers method.+* Export `KustomizationDir` from `Test.Sandwich.Contexts.Kubernetes.MinioS3Server`.+* Use the latest `sandwich` process file logging and managed asyncs.++## 0.1.2.0++* Add `getKubectlEnvironment`, similar to `askKubectlEnvironment` but not requiring reader context.+* Re-export `NetworkAddress` from `Test.Sandwich.Contexts.Kubernetes.MinioS3Server`.+* Add more low-level functions to `Test.Sandwich.Contexts.Kubernetes.Namespace`.++## 0.1.1.1++* Bump Kata context to use latest 3.19.1 by default.+* Add debugging to KataContainers.hs.+* Fix kubectlBinary reference.++## 0.1.1.0++* Switch to `kubernetes-api` and `kubernetes-api-client`.+* Fix compatibility with text-2.1.2.+* Be able to configure network policies for MinioS3Server.hs.+* Fix MinioS3Server.hs destroy.+* Remove a bunch of Control.Monad.Catch usage.++## 0.1.0.0++* Initial release
+ LICENSE view
@@ -0,0 +1,30 @@+Copyright Tom McLaughlin (c) 2026++All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++    * Redistributions of source code must retain the above copyright+      notice, this list of conditions and the following disclaimer.++    * Redistributions in binary form must reproduce the above+      copyright notice, this list of conditions and the following+      disclaimer in the documentation and/or other materials provided+      with the distribution.++    * Neither the name of Tom McLaughlin nor the names of other+      contributors may be used to endorse or promote products derived+      from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
lib/Test/Sandwich/Contexts/Kubernetes.hs view
@@ -49,6 +49,32 @@   -- * Port forwarding   , module Test.Sandwich.Contexts.Kubernetes.KubectlPortForward +  -- * Metrics server+  , installMetricsServer+  , introduceMetricsServer+  , withMetricsServer+  , MetricsServerOptions(..)+  , MetricsServerManifestSource(..)+  , defaultMetricsServerOptions++  -- * OOM watcher+  , checkForOOMKills+  , withOOMWatcher+  , withOOMWatcher'+  , withOOMWatcher''+  , OOMWatcherOptions(..)+  , defaultOOMWatcherOptions++  -- * Resource watcher (CPU + memory + network, via the kubelet summary API)+  , introduceResourceWatcher+  , resourceWatcher+  , withResourceWatcher+  , withResourceWatcher'+  , ResourceWatcher(..)+  , markEvent+  , ResourceWatcherOptions(..)+  , defaultResourceWatcherOptions+   -- * Types   , kubernetesCluster   , KubernetesClusterContext(..)@@ -74,6 +100,9 @@ import Test.Sandwich.Contexts.Kubernetes.Kubectl import Test.Sandwich.Contexts.Kubernetes.KubectlLogs import Test.Sandwich.Contexts.Kubernetes.KubectlPortForward+import Test.Sandwich.Contexts.Kubernetes.MetricsServer+import Test.Sandwich.Contexts.Kubernetes.OOMWatcher+import Test.Sandwich.Contexts.Kubernetes.ResourceWatcher import Test.Sandwich.Contexts.Kubernetes.Types import Test.Sandwich.Contexts.Kubernetes.Waits 
lib/Test/Sandwich/Contexts/Kubernetes/Images.hs view
@@ -85,7 +85,7 @@         -- Note: don't pass minikubeFlags here. These are pretty much intended for "minikube start" only.         -- TODO: clarify the documentation and possibly add an extra field where extra options can be passed         -- to "minikube image" commands.-        Minikube.getLoadedImagesMinikube kubernetesClusterTypeMinikubeBinary kubernetesClusterName []+        Minikube.getLoadedImagesMinikube kubernetesClusterTypeMinikubeBinary kubernetesClusterName [] kubernetesClusterTypeMinikubeExtraEnvironment  -- | Test if a cluster has a given image loaded. clusterContainsImage :: (@@ -112,7 +112,7 @@     KubernetesClusterKind {..} ->       Kind.clusterContainsImageKind kcc kubernetesClusterTypeKindClusterDriver kubernetesClusterTypeKindBinary kubernetesClusterTypeKindClusterEnvironment image     KubernetesClusterMinikube {..} ->-      Minikube.clusterContainsImageMinikube kubernetesClusterTypeMinikubeBinary kubernetesClusterName [] image+      Minikube.clusterContainsImageMinikube kubernetesClusterTypeMinikubeBinary kubernetesClusterName [] kubernetesClusterTypeMinikubeExtraEnvironment image  -- | Same as 'loadImage', but first checks if the given image is already present on the cluster. loadImageIfNecessary :: (@@ -120,7 +120,8 @@   )   -- | Image load spec   => ImageLoadSpec-  -> m ()+  -- | The transformed image name+  -> m Text loadImageIfNecessary image = do   kcc <- getContext kubernetesCluster   loadImageIfNecessary' kcc image@@ -134,10 +135,12 @@   -- | Image load spec   -> ImageLoadSpec   -- | The transformed image name-  -> m ()+  -> m Text loadImageIfNecessary' kcc imageLoadSpec = do-  unlessM (imageLoadSpecToImageName imageLoadSpec >>= clusterContainsImage' kcc) $+  imageName <- imageLoadSpecToImageName imageLoadSpec+  unlessM (clusterContainsImage' kcc imageName) $     void $ loadImage' kcc imageLoadSpec+  return imageName  -- | Load an image into a Kubernetes cluster. This will load the image onto the cluster -- and return the modified image name (i.e. the name by which the cluster knows the image).@@ -170,7 +173,7 @@         Kind.loadImageKind kubernetesClusterTypeKindBinary kubernetesClusterTypeKindClusterName imageLoadSpec kubernetesClusterTypeKindClusterEnvironment       (KubernetesClusterMinikube {..}) ->         -- Don't pass minikubeFlags; see comment above.-        Minikube.loadImageMinikube kubernetesClusterTypeMinikubeBinary kubernetesClusterName [] imageLoadSpec+        Minikube.loadImageMinikube kubernetesClusterTypeMinikubeBinary kubernetesClusterName [] kubernetesClusterTypeMinikubeExtraEnvironment imageLoadSpec          -- Because of the possible silent failure in "minikube image load", confirm that this         -- image made it onto the cluster.
lib/Test/Sandwich/Contexts/Kubernetes/KataContainers.hs view
@@ -98,10 +98,11 @@   case kubernetesClusterType of     KubernetesClusterKind {} -> expectationFailure [i|Can't install Kata Containers on Kind at presenpt.|]     KubernetesClusterMinikube {..} -> do-      output <- readCreateProcessWithLogging (proc kubernetesClusterTypeMinikubeBinary [+      sshEnv <- minikubeProcEnv kubernetesClusterTypeMinikubeExtraEnvironment+      output <- readCreateProcessWithLogging ((proc kubernetesClusterTypeMinikubeBinary [                                                  "--profile", toString kubernetesClusterTypeMinikubeProfileName                                                  , "ssh", [i|egrep -c 'vmx|svm' /proc/cpuinfo|]-                                                 ]) ""+                                                 ]) { env = sshEnv }) ""       case readMay output of         Just (0 :: Int) -> expectationFailure [i|Preflight check: didn't find "vmx" or "svm" in /proc/cpuinfo. Please make sure virtualization support is enabled.|]         Just _ -> return ()
lib/Test/Sandwich/Contexts/Kubernetes/KindCluster.hs view
@@ -52,6 +52,7 @@ import Test.Sandwich.Contexts.Kubernetes.KindCluster.Config import qualified Test.Sandwich.Contexts.Kubernetes.KindCluster.Images as Images import Test.Sandwich.Contexts.Kubernetes.KindCluster.Setup+import Test.Sandwich.Contexts.Kubernetes.MetricsServer (MetricsServerOptions, defaultMetricsServerOptions) import Test.Sandwich.Contexts.Kubernetes.Types import Test.Sandwich.Contexts.Kubernetes.Util.Container (isInContainer) import Test.Sandwich.Contexts.Kubernetes.Util.UUID@@ -92,6 +93,10 @@   , kindClusterName :: KindClusterName   -- | Container driver, either "docker" or "podman". Defaults to "docker".   , kindClusterDriver :: Maybe Text+  -- | Whether to install the [metrics-server](https://github.com/kubernetes-sigs/metrics-server)+  -- (so @kubectl top@ / the metrics API work). 'Nothing' skips it. Defaults to+  -- 'Just' 'defaultMetricsServerOptions'.+  , kindClusterMetricsServer :: Maybe MetricsServerOptions   -- , kindClusterCpus :: Maybe Text   -- , kindClusterMemory :: Maybe Text   }@@ -104,6 +109,7 @@   , kindClusterExtraMounts = []   , kindClusterName = KindClusterNameAutogenerate Nothing   , kindClusterDriver = Nothing+  , kindClusterMetricsServer = Just defaultMetricsServerOptions   -- , kindClusterCpus = Nothing   -- , kindClusterMemory = Nothing   }@@ -222,7 +228,7 @@                      })                void $ waitForProcess ps            ))-           (\kcc -> bracket_ (setUpKindCluster kcc kindBinary kubectlBinary environmentToUse driver)+           (\kcc -> bracket_ (setUpKindCluster kcc kindBinary kubectlBinary environmentToUse driver kindClusterMetricsServer)                              (return ())                              (action kcc)            )
lib/Test/Sandwich/Contexts/Kubernetes/KindCluster/Setup.hs view
@@ -18,6 +18,7 @@ import Relude import System.Exit import Test.Sandwich+import Test.Sandwich.Contexts.Kubernetes.MetricsServer import Test.Sandwich.Contexts.Kubernetes.Types import Test.Sandwich.Contexts.Kubernetes.Waits import UnliftIO.Environment@@ -26,8 +27,8 @@  setUpKindCluster :: (   MonadLoggerIO m, MonadUnliftIO m, HasBaseContextMonad context m-  ) => KubernetesClusterContext -> FilePath -> FilePath -> Maybe [(String, String)] -> Text -> m ()-setUpKindCluster kcc@(KubernetesClusterContext {..}) kindBinary kubectlBinary environmentToUse driver = do+  ) => KubernetesClusterContext -> FilePath -> FilePath -> Maybe [(String, String)] -> Text -> Maybe MetricsServerOptions -> m ()+setUpKindCluster kcc@(KubernetesClusterContext {..}) kindBinary kubectlBinary environmentToUse driver maybeMetricsServer = do   baseEnv <- maybe getEnvironment return environmentToUse   let env = L.nubBy (\x y -> fst x == fst y) (("KUBECONFIG", kubernetesClusterKubeConfigPath) : baseEnv)   let runWithKubeConfig cmd = createProcessWithFileLogging' "kind-setup" ((shell cmd) { env = Just env, delegate_ctlc = True })@@ -47,15 +48,9 @@                          --timeout=300s|]     >>= waitForProcess >>= (`shouldBe` ExitSuccess) -  -- info [i|Installing metrics server using helm|]-  -- void $ runWithKubeConfig [i|helm repo add bitnami https://charts.bitnami.com/bitnami|]-  -- void $ runWithKubeConfig [i|helm install metrics-server-release bitnami/metrics-server|]--  info [i|Installing metrics server|]-  runWithKubeConfig [i|#{kubectlBinary} apply -f https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.6.4/components.yaml|]-    >>= waitForProcess >>= (`shouldBe` ExitSuccess)-  runWithKubeConfig [i|#{kubectlBinary} patch -n kube-system deployment metrics-server --type=json -p '[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--kubelet-insecure-tls"}]'|]-    >>= waitForProcess >>= (`shouldBe` ExitSuccess)+  case maybeMetricsServer of+    Nothing -> info [i|Skipping metrics-server installation|]+    Just metricsServerOptions -> installMetricsServer' kcc kubectlBinary metricsServerOptions    when (driver == "docker") $ do     info [i|Fixing perms on /dev/fuse|] -- Needed on NixOS where it gets mounted 0600, don't know why
lib/Test/Sandwich/Contexts/Kubernetes/KubectlLogs.hs view
@@ -29,7 +29,8 @@  -- * Implementation --- | Run a @kubectl logs@ process, placing the logs in a file in the current test node directory.+-- | Run a @kubectl logs --follow@ process, placing the logs in a file in the current test node+-- directory. Lines are prefixed with an RFC3339 timestamp. -- -- Note that this will stop working if the pod you're talking to goes away (even if you do it against a service). -- If this happens, a rerun of the command is needed to resume log forwarding.@@ -54,6 +55,10 @@   kubectlBinary <- askFile @"kubectl"    let args = ["logs", toString target+             -- Without --follow, kubectl dumps whatever is buffered and exits+             -- immediately, so the log file only ever covers the pod's startup.+             , "--follow"+             , "--timestamps"              , "--namespace", toString namespace              , "--kubeconfig", kubeConfigFile]              <> (maybe [] (\x -> ["--container", toString x]) maybeContainer)
lib/Test/Sandwich/Contexts/Kubernetes/KubectlPortForward.hs view
@@ -39,8 +39,8 @@  -- | Run a @kubectl port-forward@ process, making the port available in the 'KubectlPortForwardContext'. ----- Note that this will stop working if the pod you're talking to goes away (even if you do it against a service).--- If this happens, a rerun of the command is needed to resume port forwarding.+-- Note that the forward stops working if the pod you're talking to goes away (even if you do it+-- against a service), so a background thread reruns the command whenever it exits. withKubectlPortForward :: (   HasCallStack, KubectlBasic context m   )@@ -93,20 +93,24 @@   let logPath = dir </> toString (T.replace "/" "_" targetName) <.> "port-forwarding.log"    withFile logPath WriteMode $ \h -> do-    let restarterThread = forever $ do-          bracket (createProcess ((proc kubectlBinary args) {-                                     std_out = UseHandle h-                                     , std_err = UseHandle h-                                     , create_group = True-                                     }))-                  (\(_, _, _, ps) -> gracefullyStopProcess ps 30_000_000)-                  (\(_, _, _, ps) -> do-                      pid <- liftIO $ getPid ps-                      info [i|Got pid for kubectl port forward: #{pid}|]+    -- createProcess_ rather than createProcess: the latter closes the handles it's given, so every+    -- restart after the first would get an already-closed one.+    let runOnce = bracket (createProcess_ "kubectl port-forward" ((proc kubectlBinary args) {+                                             std_out = UseHandle h+                                             , std_err = UseHandle h+                                             , create_group = True+                                             }))+                          (\(_, _, _, ps) -> gracefullyStopProcess ps 30_000_000)+                          (\(_, _, _, ps) -> do+                              pid <- liftIO $ getPid ps+                              info [i|Got pid for kubectl port forward: #{pid}|] -                      code <- waitForProcess ps-                      warn [i|kubectl port-forward #{targetName} #{port}:#{targetPort} exited with code: #{code}. Restarting...|]-                  )+                              code <- waitForProcess ps+                              warn [i|kubectl port-forward #{targetName} #{port}:#{targetPort} exited with code: #{code}. Restarting...|]+                          )++    let restarterThread = forever $ do+          handleAny (\e -> warn [i|Failed to run kubectl port-forward #{targetName} #{port}:#{targetPort}: #{e}. Restarting...|]) runOnce           threadDelay 1_000_000  -- 1 second delay between restarts to ensure we don't spin here      managedWithAsync_ "kubectl-port-forward-restarter" restarterThread $ do
+ lib/Test/Sandwich/Contexts/Kubernetes/MetricsServer.hs view
@@ -0,0 +1,176 @@+{-# LANGUAGE ConstraintKinds #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE TypeOperators #-}++{-|++Install the [Kubernetes metrics-server](https://github.com/kubernetes-sigs/metrics-server)+onto a cluster, so that the [Metrics API](https://kubernetes.io/docs/tasks/debug/debug-cluster/resource-metrics-pipeline/)+(@kubectl top@, @metrics.k8s.io@) becomes available.++This is handy together with "Test.Sandwich.Contexts.Kubernetes.ResourceWatcher",+which uses @kubectl top@ to record per-pod CPU and memory usage over a test.++For test clusters (kind/Minikube) the kubelet's serving certificate isn't signed+by the cluster CA, so metrics-server is configured with @--kubelet-insecure-tls@+by default ('metricsServerKubeletInsecureTls').++If you run tests that forbid unexpected image pulls (e.g. for hermeticity),+preload the metrics-server image onto the cluster yourself (e.g. with+'Test.Sandwich.Contexts.Kubernetes.Images.loadImageIfNecessary'') before calling+this, and point 'metricsServerManifestSource' at a locally-fetched manifest whose+image ref matches the preloaded image.++-}++module Test.Sandwich.Contexts.Kubernetes.MetricsServer (+  -- * Install+  installMetricsServer+  , installMetricsServer'++  -- * Spec-tree helpers+  , introduceMetricsServer+  , withMetricsServer++  -- * Options+  , MetricsServerOptions(..)+  , MetricsServerManifestSource(..)+  , defaultMetricsServerOptions+  ) where++import Control.Monad+import Control.Monad.IO.Unlift+import Control.Monad.Logger+import Data.String.Interpolate+import Relude+import System.Exit+import Test.Sandwich+import Test.Sandwich.Contexts.Files+import Test.Sandwich.Contexts.Kubernetes.Kubectl+import Test.Sandwich.Contexts.Kubernetes.Types+import Test.Sandwich.Contexts.Nix (HasNixContext)+import UnliftIO.Concurrent (threadDelay)+import UnliftIO.Process+++-- | Where to obtain the metrics-server manifest (the @components.yaml@).+data MetricsServerManifestSource =+  -- | Apply the manifest directly from a URL (default: the official release).+  MetricsServerManifestUrl Text+  -- | Apply a manifest from a local file (e.g. one fetched/built via Nix).+  | MetricsServerManifestFile FilePath+  deriving (Show, Eq)++data MetricsServerOptions = MetricsServerOptions {+  -- | Where to get the @components.yaml@ manifest.+  metricsServerManifestSource :: MetricsServerManifestSource+  -- | Whether to add @--kubelet-insecure-tls@ to the metrics-server args. Needed+  -- on kind/Minikube, whose kubelet serving certs aren't signed by the cluster CA.+  , metricsServerKubeletInsecureTls :: Bool+  -- | How long to wait (seconds) for the deployment rollout and for the metrics+  -- API to start serving.+  , metricsServerWaitTimeoutSeconds :: Double+  } deriving (Show, Eq)++-- | Default options: install metrics-server v0.7.2 from the official release URL,+-- with @--kubelet-insecure-tls@ and a 120s wait.+defaultMetricsServerOptions :: MetricsServerOptions+defaultMetricsServerOptions = MetricsServerOptions {+  metricsServerManifestSource = MetricsServerManifestUrl "https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.7.2/components.yaml"+  , metricsServerKubeletInsecureTls = True+  , metricsServerWaitTimeoutSeconds = 120+  }++-- | Type alias for a context with a @kubectl@ binary added.+type ContextWithKubectl context = LabelValue "file-kubectl" (EnvironmentFile "kubectl") :> context++-- | Install metrics-server onto the current cluster, deriving the cluster and+-- @kubectl@ binary from the context.+installMetricsServer :: (+  KubectlBasic context m+  )+  => MetricsServerOptions+  -> m ()+installMetricsServer options = do+  kcc <- getContext kubernetesCluster+  kubectlBinary <- askFile @"kubectl"+  installMetricsServer' kcc kubectlBinary options++-- | Same as 'installMetricsServer', but allows you to pass in the+-- 'KubernetesClusterContext' and @kubectl@ binary path.+installMetricsServer' :: (+  MonadUnliftIO m, MonadLoggerIO m+  , HasBaseContextMonad context m+  )+  -- | Cluster context+  => KubernetesClusterContext+  -- | Path to the @kubectl@ binary+  -> FilePath+  -> MetricsServerOptions+  -> m ()+installMetricsServer' kcc kubectlBinary (MetricsServerOptions {..}) = do+  env <- getKubectlEnvironment kcc++  let runK name args = do+        ps <- createProcessWithFileLogging' name ((proc kubectlBinary args) { env = Just env })+        waitForProcess ps >>= (`shouldBe` ExitSuccess)++  let manifestArg = case metricsServerManifestSource of+        MetricsServerManifestUrl url -> toString url+        MetricsServerManifestFile path -> path++  info [i|Installing metrics-server from #{manifestArg}|]+  runK "metrics-server-apply" ["apply", "-f", manifestArg]++  when metricsServerKubeletInsecureTls $ do+    info [i|Patching metrics-server with --kubelet-insecure-tls|]+    runK "metrics-server-patch" [+      "patch", "-n", "kube-system", "deployment", "metrics-server", "--type=json"+      , "-p", [i|[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--kubelet-insecure-tls"}]|]+      ]++  info [i|Waiting for metrics-server rollout|]+  runK "metrics-server-rollout" [+    "rollout", "status", "deployment/metrics-server", "-n", "kube-system"+    , [i|--timeout=#{round metricsServerWaitTimeoutSeconds :: Int}s|]+    ]++  -- The metrics pipeline takes a little while to start serving after the+  -- deployment is available; poll `kubectl top` until it succeeds.+  let intervalMicros = 3_000_000+  let attempts = max 1 (round (metricsServerWaitTimeoutSeconds * 1_000_000 / fromIntegral intervalMicros)) :: Int+  let topReady = do+        (ec, _, _) <- readCreateProcessWithExitCode ((proc kubectlBinary ["top", "pods", "-n", "kube-system"]) { env = Just env }) ""+        return (ec == ExitSuccess)+  let waitTop n+        | n <= 0 = warn [i|metrics-server did not start serving `kubectl top` within #{metricsServerWaitTimeoutSeconds}s; continuing anyway|]+        | otherwise = topReady >>= \case+            True -> info [i|metrics-server is serving pod metrics|]+            False -> threadDelay intervalMicros >> waitTop (n - 1)+  waitTop attempts++-- | Bracket-style: install metrics-server, then run the action. (Nothing to tear+-- down -- the cluster is ephemeral.)+withMetricsServer :: (+  KubectlBasic context m+  )+  => MetricsServerOptions+  -> m a+  -> m a+withMetricsServer options action = installMetricsServer options >> action++-- | Introduce metrics-server: bring in a @kubectl@ binary via Nix and install+-- metrics-server before running the child spec. Use this nested inside a cluster+-- introduction (e.g. 'Test.Sandwich.Contexts.Kubernetes.introduceKindClusterViaNix').+introduceMetricsServer :: (+  HasBaseContext context, HasNixContext context, HasKubernetesClusterContext context+  , MonadUnliftIO m+  )+  => MetricsServerOptions+  -> SpecFree (ContextWithKubectl context) m ()+  -> SpecFree context m ()+introduceMetricsServer options spec =+  introduceBinaryViaNixPackage @"kubectl" "kubectl" $+    before "Install metrics-server" (installMetricsServer options) spec
lib/Test/Sandwich/Contexts/Kubernetes/MinikubeCluster.hs view
@@ -40,7 +40,6 @@ import Control.Monad import Control.Monad.IO.Unlift import Control.Monad.Logger-import qualified Data.List as L import Data.String.Interpolate import Data.Text as T import Kubernetes.Client.Config@@ -51,6 +50,7 @@ import Test.Sandwich import Test.Sandwich.Contexts.Files import qualified Test.Sandwich.Contexts.Kubernetes.MinikubeCluster.Images as Images+import Test.Sandwich.Contexts.Kubernetes.MinikubeCluster.Remove import Test.Sandwich.Contexts.Kubernetes.Types import Test.Sandwich.Contexts.Kubernetes.Util.UUID import Test.Sandwich.Contexts.Nix@@ -67,6 +67,13 @@   , minikubeClusterDriver :: Maybe Text   , minikubeClusterCpus :: Maybe Text   , minikubeClusterMemory :: Maybe Text+  -- | Extra environment variables to set on every @minikube@ invocation for+  -- this cluster (start, delete, image loads, service forwards, @ssh@).+  , minikubeClusterExtraEnv :: [(String, String)]+  -- | Tear the cluster down by force-removing its node containers, instead of+  -- running @minikube delete@. Only applies to the @docker@ driver, where a+  -- node is just a container; ignored otherwise. Can be faster.+  , minikubeClusterForceRemove :: Bool   } defaultMinikubeClusterOptions :: MinikubeClusterOptions defaultMinikubeClusterOptions = MinikubeClusterOptions {@@ -76,6 +83,8 @@   , minikubeClusterDriver = Nothing   , minikubeClusterCpus = Nothing   , minikubeClusterMemory = Nothing+  , minikubeClusterExtraEnv = []+  , minikubeClusterForceRemove = False   }  -- * Introduce@@ -179,30 +188,18 @@   let deleteLogFile = minikubeDir </> "minikube-delete.log"    withFile startLogFile WriteMode $ \logH ->-    (bracket (startMinikubeCluster minikubeBinary logH clusterName minikubeKubeConfigFile options)-             (\_ -> do+    (bracket (timeAction "start Minikube cluster" $ startMinikubeCluster minikubeBinary logH clusterName minikubeKubeConfigFile options)+             (\_ -> timeAction "delete Minikube cluster" $ do                  info [i|Deleting minikube cluster: #{clusterName}|]--                 let extraFlags = case "--rootless" `L.elem` minikubeClusterExtraFlags of-                       True -> ["--rootless"]-                       False -> []--                 withFile deleteLogFile WriteMode $ \deleteH -> do-                   let deleteCp = (proc minikubeBinary (["delete"-                                                        , "--profile", clusterName-                                                        , "--logtostderr"-                                                        ] <> extraFlags)) {-                         delegate_ctlc = True-                         , create_group = True-                         , std_out = UseHandle deleteH-                         , std_err = UseHandle deleteH-                         }-                   withCreateProcess deleteCp $ \_ _ _ p ->-                     waitForProcess p >>= \case-                       ExitSuccess -> return ()-                       ExitFailure n -> warn [i|Minikube cluster delete failed with code #{n}.|]+                 removeMinikubeCluster+                   clusterName+                   minikubeBinary+                   minikubeClusterDriver+                   minikubeClusterExtraFlags+                   minikubeClusterExtraEnv+                   minikubeClusterForceRemove deleteLogFile              ))-             (\p -> do+             (\p -> timeAction "use Minikube cluster" $ do                  waitForProcess p >>= \case                    ExitSuccess -> return ()                    ExitFailure n -> expectationFailure [i|Minikube cluster creation failed with code #{n}.|]@@ -219,6 +216,7 @@                        kubernetesClusterTypeMinikubeBinary = minikubeBinary                        , kubernetesClusterTypeMinikubeProfileName = toText clusterName                        , kubernetesClusterTypeMinikubeFlags = minikubeClusterExtraFlags+                       , kubernetesClusterTypeMinikubeExtraEnvironment = minikubeClusterExtraEnv                        }                    }              )@@ -228,7 +226,7 @@   ) => FilePath -> Handle -> String -> String -> MinikubeClusterOptions -> m ProcessHandle startMinikubeCluster minikubeBinary logH clusterName minikubeKubeConfigFile (MinikubeClusterOptions {..}) = do   baseEnv <- getEnvironment-  let env = L.nubBy (\x y -> fst x == fst y) (("KUBECONFIG", minikubeKubeConfigFile) : baseEnv)+  let env = addOrReplaceEnv minikubeClusterExtraEnv (("KUBECONFIG", minikubeKubeConfigFile) : baseEnv)    -- Note: this doesn't actually work! These options actually go to the docker daemon, not the "start" operation.   -- It may not be possible to get a label on the Docker container in current minikube.
lib/Test/Sandwich/Contexts/Kubernetes/MinikubeCluster/Forwards.hs view
@@ -31,7 +31,7 @@   HasCallStack, MonadLoggerIO m, MonadUnliftIO m, HasBaseContextMonad context m   ) => KubernetesClusterContext -> Text -> Text -> Text -> (URI -> m a) -> m a withForwardKubernetesService' (KubernetesClusterContext {kubernetesClusterType=(KubernetesClusterMinikube {..}), ..}) profile namespace service action = do-  baseEnv <- liftIO getEnvironment+  baseEnv <- addOrReplaceEnv kubernetesClusterTypeMinikubeExtraEnvironment <$> liftIO getEnvironment   let env = L.nubBy (\x y -> fst x == fst y) (("KUBECONFIG", kubernetesClusterKubeConfigPath) : baseEnv)    let extraFlags = case "--rootless" `L.elem` kubernetesClusterTypeMinikubeFlags of@@ -82,7 +82,7 @@   HasCallStack, MonadLoggerIO m, MonadUnliftIO m, HasBaseContextMonad context m   ) => KubernetesClusterContext -> Text -> Text -> Text -> (URI -> m a) -> m a withForwardKubernetesServiceFileLogging' (KubernetesClusterContext {kubernetesClusterType=(KubernetesClusterMinikube {..}), ..}) profile namespace service action = do-  baseEnv <- liftIO getEnvironment+  baseEnv <- addOrReplaceEnv kubernetesClusterTypeMinikubeExtraEnvironment <$> liftIO getEnvironment   let env = L.nubBy (\x y -> fst x == fst y) (("KUBECONFIG", kubernetesClusterKubeConfigPath) : baseEnv)    let extraFlags = case "--rootless" `L.elem` kubernetesClusterTypeMinikubeFlags of
lib/Test/Sandwich/Contexts/Kubernetes/MinikubeCluster/Images.hs view
@@ -1,6 +1,7 @@ {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-}+{-# LANGUAGE NumericUnderscores #-} {-# LANGUAGE TypeOperators #-}  module Test.Sandwich.Contexts.Kubernetes.MinikubeCluster.Images (@@ -12,6 +13,7 @@ import Control.Monad import Control.Monad.IO.Unlift import Control.Monad.Logger+import Control.Retry import qualified Data.Aeson as A import qualified Data.ByteString as B import qualified Data.List as L@@ -32,6 +34,9 @@ import UnliftIO.Temporary  +imageLoadRetryPolicy :: Monad m => RetryPolicyM m+imageLoadRetryPolicy = capDelay 15_000_000 (exponentialBackoff 1_000_000) <> limitRetries 5+ -- | Load an image onto a cluster. This image can come from a variety of sources, as specified by the 'ImageLoadSpec'. loadImageMinikube :: (   HasCallStack, MonadUnliftIO m, MonadLoggerIO m, HasBaseContextMonad context m@@ -42,11 +47,13 @@   -> Text   -- | Extra flags to pass to @minikube@   -> [Text]+  -- | Extra environment variables to add over the ambient environment (empty = inherit unchanged)+  -> [(String, String)]   -- | Image load spec   -> ImageLoadSpec   -- | Returns transformed image name   -> m Text-loadImageMinikube minikubeBinary clusterName minikubeFlags imageLoadSpec = do+loadImageMinikube minikubeBinary clusterName minikubeFlags minikubeExtraEnv imageLoadSpec = do   case imageLoadSpec of     ImageLoadSpecTarball image -> do       -- File or directory image@@ -88,8 +95,22 @@       imageLoad (toString image) True >> return image    where+    -- The usual reason a load fails is that containerd inside the node isn't serving yet:+    -- @ctr: cannot access socket /run/containerd/containerd.sock: no such file or directory@.+    -- That needs time rather than another immediate attempt, so back off between tries.     imageLoad :: (MonadLoggerIO m, HasBaseContextMonad context m, HasCallStack) => String -> Bool -> m ()-    imageLoad toLoad daemon = do+    imageLoad toLoad daemon =+      retrying imageLoadRetryPolicy shouldRetry (const (imageLoadOnce toLoad daemon)) >>= \case+        Nothing -> return ()+        Just details -> expectationFailure [i|minikube image load failed; error output detected (#{details})|]+      where+        shouldRetry _ Nothing = return False+        shouldRetry _ (Just details) = do+          warn [i|minikube image load failed (#{details}); retrying|]+          return True++    imageLoadOnce :: (MonadLoggerIO m, HasBaseContextMonad context m, HasCallStack) => String -> Bool -> m (Maybe Text)+    imageLoadOnce toLoad daemon = do       let extraFlags = case "--rootless" `L.elem` minikubeFlags of                          True -> ["--rootless"]                          False -> []@@ -102,6 +123,8 @@        debug [i|#{minikubeBinary} #{T.unwords $ fmap toText args}|] +      procEnv <- minikubeProcEnv minikubeExtraEnv+       -- Gather stderr output while also logging it       logFn <- askLoggerIO       ctx <- ask@@ -110,18 +133,21 @@             modifyIORef' stderrOutputVar (<> str)             logFn loc src level str -      liftIO $ flip runLoggingT customLogFn $ flip runReaderT ctx $-        createProcessWithLogging (proc minikubeBinary args)-          >>= \(ps, asy) -> finally (waitForProcess ps >>= (`shouldBe` ExitSuccess))-                                    (cancel asy)+      exitCode <- liftIO $ flip runLoggingT customLogFn $ flip runReaderT ctx $+        createProcessWithLogging ((proc minikubeBinary args) { env = procEnv })+          >>= \(ps, asy) -> finally (waitForProcess ps) (cancel asy)        stderrOutput <- fromLogStr <$> readIORef stderrOutputVar -      let ef (details :: Text) = expectationFailure [i|minikube image load failed; error output detected (#{details})|]+      return $ failureReason exitCode stderrOutput -      when (check1 stderrOutput) $ ef "Contained 'Failed to load cached images for profile' message"-      when (check2 stderrOutput) $ ef "Contained 'ctr: failed to ingest' message"-      when (check3 stderrOutput) $ ef "Contained 'failed pushing to' message"+    failureReason :: ExitCode -> ByteString -> Maybe Text+    failureReason exitCode stderrOutput+      | exitCode /= ExitSuccess = Just [i|Exited with #{exitCode}|]+      | check1 stderrOutput = Just "Contained 'Failed to load cached images for profile' message"+      | check2 stderrOutput = Just "Contained 'ctr: failed to ingest' message"+      | check3 stderrOutput = Just "Contained 'failed pushing to' message"+      | otherwise = Nothing      -- This is crazy, but minikube image load sometimes fails silently.     -- One example: https://github.com/kubernetes/minikube/issues/16032@@ -146,13 +172,16 @@   -> Text   -- | Extra flags to pass to @minikube@   -> [Text]+  -- | Extra environment variables to add over the ambient environment (empty = inherit unchanged)+  -> [(String, String)]   -> m (Set Text)-getLoadedImagesMinikube minikubeBinary clusterName minikubeFlags = do+getLoadedImagesMinikube minikubeBinary clusterName minikubeFlags minikubeExtraEnv = do+  procEnv <- minikubeProcEnv minikubeExtraEnv   -- TODO: use "--format json" and parse?   (Set.fromList . T.words . toText) <$> readCreateProcessWithLogging (-    proc minikubeBinary (["image", "ls"-                         , "--profile", toString clusterName-                         ] <> fmap toString minikubeFlags)) ""+    (proc minikubeBinary (["image", "ls"+                          , "--profile", toString clusterName+                          ] <> fmap toString minikubeFlags)) { env = procEnv }) ""  -- | Test if the cluster contains a given image, by cluster name. clusterContainsImageMinikube :: (@@ -164,15 +193,17 @@   -> Text   -- | Extra flags to pass to @minikube@   -> [Text]+  -- | Extra environment variables to add over the ambient environment (empty = inherit unchanged)+  -> [(String, String)]   -- | Image name   -> Text   -> m Bool-clusterContainsImageMinikube minikubeBinary clusterName minikubeFlags image = do+clusterContainsImageMinikube minikubeBinary clusterName minikubeFlags minikubeExtraEnv image = do   imageName <- case isAbsolute (toString image) of     False -> pure image     True -> readImageName (toString image) -  loadedImages <- getLoadedImagesMinikube minikubeBinary clusterName minikubeFlags+  loadedImages <- getLoadedImagesMinikube minikubeBinary clusterName minikubeFlags minikubeExtraEnv    return (     imageName `Set.member` loadedImages
+ lib/Test/Sandwich/Contexts/Kubernetes/MinikubeCluster/Remove.hs view
@@ -0,0 +1,163 @@+{-# LANGUAGE ConstraintKinds #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE TypeOperators #-}++module Test.Sandwich.Contexts.Kubernetes.MinikubeCluster.Remove (+  removeMinikubeCluster+  ) where++import Control.Monad+import Control.Monad.IO.Unlift+import Control.Monad.Logger+import qualified Data.List as L+import Data.String.Interpolate+import Data.Text as T+import Relude hiding (withFile)+import System.Exit+import System.FilePath+import Test.Sandwich+import Test.Sandwich.Contexts.Kubernetes.Types+import UnliftIO.Directory+import UnliftIO.Environment+import UnliftIO.Exception+import UnliftIO.IO+import UnliftIO.Process+++removeMinikubeCluster :: (+  MonadLoggerIO m, MonadUnliftIO m, MonadReader context m, HasBaseContext context+  )+  => String+  -> FilePath+  -> Maybe Text+  -> [Text]+  -> [(String, String)]+  -> Bool+  -> FilePath+  -> m ()+removeMinikubeCluster clusterName minikubeBinary driver extraFlags' extraEnv forceRemove deleteLogFile = do+  -- For container-runtime drivers (docker/podman) each node is a container, with a+  -- volume named after it. Capture the names now, while the containers still exist and+  -- carry minikube's labels, so we can remove both below. VM-based drivers (kvm2, etc.)+  -- have neither, so we skip them.+  let containerRuntime = fromMaybe "docker" driver+  let usingContainerDriver = containerRuntime `L.elem` ["docker", "podman"]+  nodeNames <- if usingContainerDriver+    then getMinikubeClusterNodeNames containerRuntime clusterName+    else pure []++  if | forceRemove && containerRuntime == "docker" ->+         timeAction "force remove minikube containers" $+           removeClusterContainers containerRuntime nodeNames+     | otherwise ->+         timeAction "run minikube delete" $ do+           let extraFlags = case "--rootless" `L.elem` extraFlags' of+                 True -> ["--rootless"]+                 False -> []++           deleteEnv <- addOrReplaceEnv extraEnv <$> getEnvironment+           withFile deleteLogFile WriteMode $ \deleteH -> do+             let deleteCp = (proc minikubeBinary (["delete"+                                                  , "--profile", clusterName+                                                  , "--logtostderr"+                                                  ] <> extraFlags)) {+                   delegate_ctlc = True+                   , create_group = True+                   , env = Just deleteEnv+                   , std_out = UseHandle deleteH+                   , std_err = UseHandle deleteH+                   }+             withCreateProcess deleteCp $ \_ _ _ p ->+               waitForProcess p >>= \case+                 ExitSuccess -> return ()+                 ExitFailure n -> expectationFailure [i|Minikube cluster delete failed with code #{n}.|]++  timeAction "remove cluster volumes" $ deleteClusterVolumes containerRuntime nodeNames+  when usingContainerDriver $+    timeAction "remove cluster network" $ removeClusterNetwork containerRuntime clusterName+  timeAction "remove minikube profile dirs" $+    removeMinikubeProfileDirs clusterName extraEnv+++-- | Resolve MINIKUBE_HOME the same way minikube does (see localpath.MiniPath): default to+-- @$HOME/.minikube@, honor a @MINIKUBE_HOME@ that already ends in @.minikube@, else append it.+-- A @MINIKUBE_HOME@ in the passed cluster-scoped env takes precedence over the ambient process env,+-- so profile cleanup targets the same home the cluster was actually started with.+getMinikubeHome :: MonadIO m => [(String, String)] -> m FilePath+getMinikubeHome extraEnv = resolve (L.lookup "MINIKUBE_HOME" extraEnv) >>= \case+  Just p -> return p+  Nothing -> UnliftIO.Environment.lookupEnv "MINIKUBE_HOME" >>= resolve >>= \case+    Just p -> return p+    Nothing -> (</> ".minikube") <$> getHomeDirectory+  where+    resolve :: MonadIO m => Maybe String -> m (Maybe FilePath)+    resolve = \case+      Just p | p /= "" -> return $ Just $ if takeFileName p == ".minikube" then p else p </> ".minikube"+      _ -> return Nothing++getMinikubeClusterNodeNames :: (MonadLoggerIO m, MonadUnliftIO m) => Text -> String -> m [String]+getMinikubeClusterNodeNames containerRuntime clusterName =+  handleAny (\e -> [] <$ warn [i|Couldn't list #{containerRuntime} containers for cluster #{clusterName}: #{e}|]) $+    readCreateProcessWithExitCode (proc (toString containerRuntime) [+        "ps", "-a"+        , "--filter", [i|label=mode.minikube.sigs.k8s.io=#{clusterName}|]+        , "--format", "{{.Names}}"+        ]) "" >>= \case+      (ExitSuccess, out, _) -> pure [toString l | l <- T.lines (toText out), not (T.null (T.strip l))]+      (ExitFailure _, _, _) -> pure []++-- | Force-remove the cluster's node containers, along with the anonymous volumes they own.+removeClusterContainers :: (MonadLoggerIO m) => Text -> [String] -> m ()+removeClusterContainers _ [] = return ()+removeClusterContainers containerRuntime names = forM_ names $ \name -> do+  debug [i|Removing #{containerRuntime} container: #{name}|]+  readCreateProcessWithExitCode (proc (toString containerRuntime) ["rm", "-f", "-v", name]) "" >>= \case+    (ExitSuccess, _, _) -> return ()+    (ExitFailure n, _, err) ->+      warn [i|Couldn't remove #{containerRuntime} container #{name} (exit #{n}); leaving it behind: #{err}|]++removeClusterNetwork :: (MonadLoggerIO m) => Text -> String -> m ()+removeClusterNetwork containerRuntime clusterName = do+  networks <- readCreateProcessWithExitCode cp "" >>= \case+    (ExitSuccess, out, _) ->+      return [toString l | l <- T.lines (toText out), not (T.null (T.strip l))]+    x -> expectationFailure [i|removeClusterNetwork: couldn't parse networks: #{x}|]++  forM_ networks  $ \net -> do+    debug [i|Removing #{containerRuntime} network: #{net}|]+    void $ readCreateProcessWithExitCode (proc (toString containerRuntime) ["network", "rm", net]) ""++  where+    cp = proc (toString containerRuntime) [+      "network", "ls"+      , "--filter", [i|label=name.minikube.sigs.k8s.io=#{clusterName}|]+      , "--format", "{{.Name}}"+      ]++-- | Force-remove the given container-runtime volumes ("--force" ignores any that are already gone,+-- and is supported by both @docker volume rm@ and @podman volume rm@). Best-effort.+deleteClusterVolumes :: (MonadLoggerIO m, MonadUnliftIO m) => Text -> [String] -> m ()+deleteClusterVolumes _ [] = return ()+deleteClusterVolumes containerRuntime volumes = handleAny logErr $ do+  debug [i|Removing leftover #{containerRuntime} volumes: #{volumes}|]+  void $ readCreateProcessWithExitCode (proc (toString containerRuntime) (["volume", "rm", "--force"] <> volumes)) ""+  where+    logErr :: MonadLoggerIO m => SomeException -> m ()+    logErr e = warn [i|Error removing #{containerRuntime} volumes #{volumes}: #{e}|]++-- | Remove the per-profile state that "minikube delete" should clean up but sometimes leaves behind:+-- @<minikube-home>/profiles/<profile>@ and @.../machines/<profile>@. The rest of MINIKUBE_HOME (the+-- multi-gigabyte image caches, certs, addons) is shared across clusters, so we leave it untouched.+removeMinikubeProfileDirs :: (MonadLoggerIO m, MonadUnliftIO m) => String -> [(String, String)] -> m ()+removeMinikubeProfileDirs clusterName extraEnv = handleAny logErr $ do+  miniPath <- getMinikubeHome extraEnv+  forM_ ["profiles", "machines"] $ \sub -> do+    let dir = miniPath </> sub </> clusterName+    whenM (doesPathExist dir) $ do+      debug [i|Removing leftover minikube state dir: #{dir}|]+      removePathForcibly dir+  where+    logErr :: MonadLoggerIO m => SomeException -> m ()+    logErr e = warn [i|Error removing minikube state dirs for #{clusterName}: #{e}|]
lib/Test/Sandwich/Contexts/Kubernetes/MinioS3Server.hs view
@@ -171,7 +171,7 @@             loadImageIfNecessary' kcc (ImageLoadSpecDocker image IfNotPresent)            debug [i|Preloading image: #{busyboxImage}|]-          loadImageIfNecessary' kcc (ImageLoadSpecDocker busyboxImage IfNotPresent)+          void $ loadImageIfNecessary' kcc (ImageLoadSpecDocker busyboxImage IfNotPresent)          (userAndPassword@(username, password), finalYaml) <- case transformKustomizeChunks (toString minioS3ServerNamespace) (toString deploymentName) (T.splitOn "---\n" (toText allYaml)) of           Left err -> expectationFailure [i|Couldn't transform kustomize chunks: #{err}|]
+ lib/Test/Sandwich/Contexts/Kubernetes/OOMWatcher.hs view
@@ -0,0 +1,200 @@+{-# LANGUAGE ConstraintKinds #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE NumericUnderscores #-}+{-# LANGUAGE TypeApplications #-}++{-|++Detect [OOMKilled](https://kubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction/)+containers in a Kubernetes cluster.++A container OOMKill is almost always a memory/resource misconfiguration (a pod's+memory limit too low, or the node overcommitted), and it tends to surface as a+baffling downstream flake -- e.g. a server pod gets OOM-killed, loses readiness,+its Service endpoint is removed, kube-proxy installs a "no endpoints" REJECT for+the NodePort, and clients start getting "connection refused". These helpers let+you detect it explicitly and fail the test instead.++By default the watch covers all namespaces; set 'oomWatcherNamespace' to scope it+to one (e.g. so a test that deliberately OOMKills a pod elsewhere doesn't trip it).++-}++module Test.Sandwich.Contexts.Kubernetes.OOMWatcher (+  -- * Spec-level (around)+  withOOMWatcher++  -- * Reader-based (action-level)+  , checkForOOMKills+  , withOOMWatcher'++  -- * Explicit-argument variants+  , findOOMKilled'+  , checkForOOMKills'+  , withOOMWatcher''++  -- * Options+  , OOMWatcherOptions(..)+  , defaultOOMWatcherOptions+  ) where++import Control.Monad+import Control.Monad.IO.Unlift+import Control.Monad.Logger+import qualified Data.List as L+import Data.String.Interpolate+import Relude+import System.IO (hGetLine)+import System.Process (cleanupProcess)+import Test.Sandwich.Util.Process (gracefullyStopProcess)+import Test.Sandwich+import Test.Sandwich.Contexts.Files+import Test.Sandwich.Contexts.Kubernetes.Kubectl+import Test.Sandwich.Contexts.Kubernetes.Types+import Test.Sandwich.Contexts.Kubernetes.Util.KubectlTop (namespaceArgs, scopeLabel)+import UnliftIO.Async (withAsync)+import UnliftIO.Concurrent (threadDelay)+import UnliftIO.Exception+import UnliftIO.Process+++data OOMWatcherOptions = OOMWatcherOptions {+  -- | Namespace to watch, or all namespaces when 'Nothing' (the default).+  oomWatcherNamespace :: Maybe Text+  } deriving (Show, Eq)++-- | Watch all namespaces.+defaultOOMWatcherOptions :: OOMWatcherOptions+defaultOOMWatcherOptions = OOMWatcherOptions {+  oomWatcherNamespace = Nothing+  }++-- | One-shot: fail if any container is/was OOMKilled. Reader-based version that+-- obtains the cluster and @kubectl@ binary from the context.+checkForOOMKills :: (+  KubectlBasic context m+  )+  -- | Namespace to check, or all namespaces when 'Nothing'+  => Maybe Text+  -> m ()+checkForOOMKills namespace = do+  kcc <- getContext kubernetesCluster+  kubectlBinary <- askFile @"kubectl"+  checkForOOMKills' kcc kubectlBinary namespace++-- | Around-style spec node: run the wrapped subtree with a background pod-status+-- watch, failing the run at the end if any container is observed OOMKilled. The+-- spec-level counterpart to the action-level 'withOOMWatcher'', mirroring+-- 'Test.Sandwich.Contexts.Kubernetes.Namespace.withKubernetesNamespace'.+withOOMWatcher :: (+  KubectlBasicWithoutReader context m+  )+  => OOMWatcherOptions+  -> SpecFree context m ()+  -> SpecFree context m ()+withOOMWatcher options = around [i|Watch for OOMKills in #{scopeLabel (oomWatcherNamespace options)}|]+  (void . withOOMWatcher' options)++-- | Run @action@ with a background pod-status watch, failing the run at the end+-- if any container is observed OOMKilled. Reader-based version.+withOOMWatcher' :: (+  KubectlBasic context m+  )+  => OOMWatcherOptions+  -> m a+  -> m a+withOOMWatcher' options action = do+  kcc <- getContext kubernetesCluster+  kubectlBinary <- askFile @"kubectl"+  withOOMWatcher'' kcc kubectlBinary options action++-- | Returns a human-readable pod listing if any container is (or was, via+-- @lastState@) OOMKilled, else Nothing. Checks one namespace, or all when 'Nothing'.+findOOMKilled' :: (+  MonadUnliftIO m, MonadLoggerIO m+  , HasBaseContextMonad context m+  ) => KubernetesClusterContext -> FilePath -> Maybe Text -> m (Maybe String)+findOOMKilled' kcc kubectlBinary namespace = do+  env <- getKubectlEnvironment kcc+  let runK args = readCreateProcessWithFileLogging ((proc kubectlBinary args) { env = Just env }) ""++  reasons <- runK (["get", "pods"] <> namespaceArgs namespace <> ["-o"+                  , "jsonpath={range .items[*]}{range .status.containerStatuses[*]}{.state.terminated.reason} {.lastState.terminated.reason} {end}{end}"])++  if "OOMKilled" `L.isInfixOf` reasons+    then Just <$> runK (["get", "pods"] <> namespaceArgs namespace <> ["-o", "wide"])+    else return Nothing++-- | One-shot: fail if any container is/was OOMKilled (one namespace, or all when 'Nothing').+checkForOOMKills' :: (+  MonadUnliftIO m, MonadLoggerIO m+  , HasBaseContextMonad context m+  ) => KubernetesClusterContext -> FilePath -> Maybe Text -> m ()+checkForOOMKills' kcc kubectlBinary namespace =+  findOOMKilled' kcc kubectlBinary namespace >>= \case+    Nothing -> return ()+    Just detail -> expectationFailure [i|Detected an OOMKilled container in #{scopeLabel namespace} (memory/resource misconfiguration). Pods:\n#{detail}|]++-- | Run @action@ with a background pod-status *watch*, failing the run at the end+-- if any container is observed OOMKilled.+--+-- Container OOMKills produce no kubectl event (verified empirically) -- the only+-- signal is @.status.containerStatuses[].{state,lastState}.terminated.reason@. So+-- instead of polling, we stream @kubectl get pods --watch@ (default table output,+-- which streams one row per watch event; the row's STATUS column shows+-- "OOMKilled"). The apiserver pushes a row whenever a pod's status changes, so we+-- see an OOMKilled the instant kubelet sets it, including for short-lived pods+-- (e.g. runner pods) that are deleted right after. We scan each streamed row for+-- "OOMKilled" and re-establish the watch if it drops. (NB: we deliberately do not+-- use @-o jsonpath@ -- its @--watch@ only prints the initial state, not updates.)+withOOMWatcher'' :: (+  MonadUnliftIO m, MonadLoggerIO m+  , HasBaseContextMonad context m+  ) => KubernetesClusterContext -> FilePath -> OOMWatcherOptions -> m a -> m a+withOOMWatcher'' kcc kubectlBinary (OOMWatcherOptions {..}) action = do+  env <- getKubectlEnvironment kcc+  oomRef <- newIORef Nothing++  let scope = scopeLabel oomWatcherNamespace+  let nsArgs = namespaceArgs oomWatcherNamespace++  -- Grab a fuller `-o wide` listing for the failure message; fall back to the raw+  -- watch line if that kubectl call fails.+  let snapshot fallback = handleAny (const (return fallback)) $+        readCreateProcessWithFileLogging ((proc kubectlBinary (["get", "pods"] <> nsArgs <> ["-o", "wide"])) { env = Just env }) ""++  let handleLine line = when ("OOMKilled" `L.isInfixOf` line) $ do+        existing <- readIORef oomRef+        when (isNothing existing) $ snapshot line >>= (writeIORef oomRef . Just)++  -- One streaming watch attempt: read one table row per pod update until it ends+  -- (EOF). A row whose STATUS is "OOMKilled" means a container was OOM-killed.+  let oneWatch = bracket+        (createProcess (proc kubectlBinary (["get", "pods"] <> nsArgs <> ["--watch", "--no-headers"])) { env = Just env, std_out = CreatePipe, std_err = CreatePipe, create_group = True })+        -- `kubectl ... --watch` does not reliably exit on SIGTERM when its target is being torn down, so+        -- a plain cleanupProcess (terminate + blocking wait) hangs teardown. Stop the process group+        -- gracefully first (SIGINT, escalating to SIGKILL after the grace period), then clean up handles.+        (\tup@(_, _, _, ph) -> gracefullyStopProcess ph 5_000_000 >> liftIO (cleanupProcess tup))+        (\(_, mHOut, _, _) -> case mHOut of+            Nothing -> return ()+            Just hOut ->+              let loop = tryAny (liftIO (hGetLine hOut)) >>= \r -> case r of+                    Left _ -> return ()              -- EOF / closed: this watch ended+                    Right line -> handleLine line >> loop+              in loop)++  -- Watches drop periodically; re-establish until the action finishes (cancel).+  let watchForever = forever $ do+        handleAny (\e -> debug [i|(#{scope}) OOM pod-watch ended, re-establishing: #{e}|]) oneWatch+        threadDelay 1_000_000++  let finalCheck = do+        -- belt and suspenders: also do a one-shot check at teardown+        direct <- handleAny (const (return Nothing)) (findOOMKilled' kcc kubectlBinary oomWatcherNamespace)+        watched <- readIORef oomRef+        case watched <|> direct of+          Just detail -> expectationFailure [i|Detected an OOMKilled container in #{scope} during the run (memory/resource misconfiguration). Pods:\n#{detail}|]+          Nothing -> return ()++  finally (withAsync watchForever (const action)) finalCheck
lib/Test/Sandwich/Contexts/Kubernetes/PostgresServer.hs view
@@ -30,6 +30,7 @@   ) where  import Control.Monad+import qualified Data.Aeson as A import Data.String.Interpolate import Data.Text as T import Relude@@ -52,6 +53,7 @@   , postgresK8SPassword :: Text   , postgresK8SDatabase :: Text   , postgresK8SPreloadImage :: Bool+  , postgresK8SExtraEnv :: [(Text, Text)]   } defaultPostgresK8SOptions :: Text -> PostgresK8SOptions defaultPostgresK8SOptions namespace = PostgresK8SOptions {@@ -61,6 +63,7 @@   , postgresK8SPassword = "postgres"   , postgresK8SDatabase = "test"   , postgresK8SPreloadImage = True+  , postgresK8SExtraEnv = []   }  -- | Introduce a PostgreSQL server on a Kubernetes cluster.@@ -120,20 +123,21 @@    let postgresPort = 5432 :: Int -  when postgresK8SPreloadImage $ do+  when postgresK8SPreloadImage $ timeAction "Preload PostgreSQL image" $ do     debug [i|Preloading postgres image: #{postgresK8SImage}|]-    loadImageIfNecessary' kcc (ImageLoadSpecDocker postgresK8SImage IfNotPresent)+    void $ loadImageIfNecessary' kcc (ImageLoadSpecDocker postgresK8SImage IfNotPresent)    let yaml = postgresYaml deploymentName postgresK8SNamespace postgresK8SImage                           postgresK8SUsername postgresK8SPassword postgresK8SDatabase+                          postgresK8SExtraEnv -  let create = do+  let create = timeAction "Creating PostgreSQL" $ do         (ps, _) <- createProcessWithLoggingAndStdin           ((proc kubectlBinary ["apply", "-f", "-"]) { env = Just env })           (toString yaml)         waitForProcess ps >>= (`shouldBe` ExitSuccess) -  let destroy = do+  let destroy = timeAction "Destroying PostgreSQL" $ do         info [i|Destroying PostgreSQL K8S resources|]         (ps, _) <- createProcessWithLoggingAndStdin           ((proc kubectlBinary ["delete", "-f", "-", "--ignore-not-found"]) { env = Just env })@@ -149,12 +153,13 @@                    , "--timeout=120s"                    , "--kubeconfig", kubernetesClusterKubeConfigPath                    ]-    timeout 150_000_000 (do-      (ps, _) <- createProcessWithLogging ((proc kubectlBinary waitArgs) { env = Just env })-      waitForProcess ps >>= (`shouldBe` ExitSuccess)-      ) >>= \case-        Just () -> return ()-        Nothing -> expectationFailure [i|Timed out waiting for PostgreSQL pod to be ready|]+    timeAction "Waiting for PostgreSQL" $+      timeout 150_000_000 (do+        (ps, _) <- createProcessWithLogging ((proc kubectlBinary waitArgs) { env = Just env })+        waitForProcess ps >>= (`shouldBe` ExitSuccess)+        ) >>= \case+          Just () -> return ()+          Nothing -> expectationFailure [i|Timed out waiting for PostgreSQL pod to be ready|]      let serviceName = [i|service/#{deploymentName}|] :: Text     withKubectlPortForward' kubectlBinary kubernetesClusterKubeConfigPath postgresK8SNamespace@@ -173,8 +178,8 @@       void $ action ctx  -postgresYaml :: Text -> Text -> Text -> Text -> Text -> Text -> Text-postgresYaml name namespace image username password database = [__i|+postgresYaml :: Text -> Text -> Text -> Text -> Text -> Text -> [(Text, Text)] -> Text+postgresYaml name namespace image username password database extraEnv = [__i|   apiVersion: v1   kind: Pod   metadata:@@ -193,15 +198,12 @@       - name: POSTGRES_PASSWORD         value: "#{password}"       - name: POSTGRES_DB-        value: "#{database}"+        value: "#{database}"#{extraEnvLines}       ports:       - containerPort: 5432       readinessProbe:-        exec:-          command:-          - pg_isready-          - -U-          - "#{username}"+        tcpSocket:+          port: 5432         initialDelaySeconds: 5         periodSeconds: 2   ---@@ -217,3 +219,7 @@     - port: 5432       targetPort: 5432   |]+  where+    extraEnvLines :: Text+    extraEnvLines = mconcat [ "\n    - name: " <> k <> "\n      value: " <> decodeUtf8 (A.encode v)+                            | (k, v) <- extraEnv ]
+ lib/Test/Sandwich/Contexts/Kubernetes/ResourceWatcher.hs view
@@ -0,0 +1,365 @@+{-# LANGUAGE ConstraintKinds #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE NumericUnderscores #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE TypeOperators #-}++{-|++Record per-pod (or per-container) CPU, memory, and network usage over the course of a test by polling+the __kubelet summary API__ (@\/api\/v1\/nodes\/<node>\/proxy\/stats\/summary@, cAdvisor-backed) directly.++This needs __no metrics-server__ and pulls no images (the summary API is built into every kubelet). It+captures both the CPU __rate__ (@cpu.usageNanoCores@) and the __cumulative__ CPU counter+(@cpu.usageCoreNanoSeconds@) — so total CPU-seconds are accurate regardless of the sample interval+(rate sampling alone misses spikes between samples) — plus memory working set and per-pod network rx\/tx.++Caveat: cAdvisor cannot see inside __kata__ (VM-sandboxed) pods — they report zero. Run such pods on+the default runtime if you need to measure them.++Three entry points, sharing one core:++  * 'introduceResourceWatcher' — spec-level node that brackets a subtree and provides a+    'ResourceWatcher' handle to its children (so tests can drop timeline markers via 'markEvent').+  * 'withResourceWatcher' — action-level bracket you call inside an @it@ to monitor just that section.+  * 'withResourceWatcher'' — same, with the cluster context and @kubectl@ path passed in explicitly.++On completion these artifacts are written into the current test folder:++  * @pod-resources.csv@ — the raw time series+    (@elapsed_s,pod,cpu_core_ns,cpu_nanocores,mem_ws_bytes,net_rx_bytes,net_tx_bytes@).+  * @pod-resources-summary.json@ — derived per-pod totals (CPU-seconds, peak\/mean memory, net rx\/tx)+    plus overall aggregates.+  * @pod-cpu-peak.txt@ \/ @pod-memory-peak.txt@ — each pod's peak CPU\/memory, sorted descending (logged too).+  * @pod-resources-events.csv@ — timeline markers emitted via 'markEvent' (@elapsed_s,label@).+  * @pod-cpu.svg@ \/ @pod-memory.svg@ \/ @pod-network.svg@ — charts over time, one line per pod.+  * @pod-resources-report.html@ — a self-contained report stitching the charts, ranked tables, and events.++By default it watches all namespaces; set 'resourceWatcherNamespaces' to scope it. With+'resourceWatcherContainerLevel', each pod is broken down by container (identifier gains a+@\/container@ suffix; network stays pod-level and is reported as 0 for container rows).++-}++module Test.Sandwich.Contexts.Kubernetes.ResourceWatcher (+  -- * Spec-level (introduce)+  introduceResourceWatcher+  , resourceWatcher++  -- * Action-level (reader-based)+  , withResourceWatcher++  -- * Action-level (explicit arguments)+  , withResourceWatcher'++  -- * The handle+  , ResourceWatcher(..)+  , markEvent++  -- * Options+  , ResourceWatcherOptions(..)+  , defaultResourceWatcherOptions+  ) where++import Control.Monad+import Control.Monad.IO.Unlift+import Control.Monad.Logger+import Data.Aeson (eitherDecodeStrict, encode, object, (.=))+import qualified Data.Aeson.Key as AK+import qualified Data.Aeson.KeyMap as KM+import Data.Aeson.Types (Value(..))+import qualified Data.ByteString.Lazy as BL+import qualified Data.Map.Strict as M+import Data.String.Interpolate+import qualified Data.Text as T+import Data.Time.Clock (diffUTCTime, getCurrentTime)+import Numeric (showFFloat)+import Relude+import System.Exit (ExitCode(..))+import System.FilePath ((</>))+import Test.Sandwich+import Test.Sandwich.Contexts.Files+import Test.Sandwich.Contexts.Kubernetes.Kubectl+import Test.Sandwich.Contexts.Kubernetes.Types+import Test.Sandwich.Contexts.Kubernetes.Util.SeriesPlot (renderSeriesSvg)+import UnliftIO.Async (withAsync)+import UnliftIO.Concurrent (threadDelay)+import UnliftIO.Exception+import UnliftIO.Process+++-- | A handle, available to children of 'introduceResourceWatcher' (or returned by+-- 'withResourceWatcher'), for dropping labeled markers onto the resource timeline so a particular+-- test action can be correlated with the data.+newtype ResourceWatcher = ResourceWatcher {+  -- | Record a timeline marker at the current elapsed time. Prefer 'markEvent' from a test.+  resourceWatcherMark :: Text -> IO ()+  }++-- | Context label carrying the 'ResourceWatcher' handle under 'introduceResourceWatcher'.+resourceWatcher :: Label "resourceWatcher" ResourceWatcher+resourceWatcher = Label++-- | Drop a labeled marker onto the resource timeline (lifted 'resourceWatcherMark').+markEvent :: MonadIO m => ResourceWatcher -> Text -> m ()+markEvent rw = liftIO . resourceWatcherMark rw++data ResourceWatcherOptions = ResourceWatcherOptions {+  -- | Namespaces to watch. Empty (the default) means all namespaces.+  resourceWatcherNamespaces :: [Text]+  -- | How often to sample the summary API, in microseconds.+  , resourceWatcherIntervalMicros :: Int+  -- | When 'True', break each pod down by container (identifier gains a @\/container@ suffix).+  -- Network is pod-level only, so it is reported as 0 for container rows.+  , resourceWatcherContainerLevel :: Bool+  -- | Whether to render the SVG charts and the HTML report (in addition to the CSV/JSON/peaks).+  , resourceWatcherWriteReport :: Bool+  } deriving (Show, Eq)++-- | Watch all namespaces, sample every 5s, pod-level, and write the charts + report.+defaultResourceWatcherOptions :: ResourceWatcherOptions+defaultResourceWatcherOptions = ResourceWatcherOptions {+  resourceWatcherNamespaces = []+  , resourceWatcherIntervalMicros = 5_000_000+  , resourceWatcherContainerLevel = False+  , resourceWatcherWriteReport = True+  }++-- | One poll of a pod (or container): elapsed time plus the raw summary-API counters.+data Sample = Sample {+  sElapsed   :: !Double+  , sCpuCoreNs :: !Integer  -- ^ cumulative cpu.usageCoreNanoSeconds+  , sCpuNano   :: !Integer  -- ^ instantaneous cpu.usageNanoCores (rate)+  , sMem       :: !Integer  -- ^ memory.workingSetBytes+  , sRx        :: !Integer  -- ^ cumulative network.rxBytes (0 for container rows)+  , sTx        :: !Integer  -- ^ cumulative network.txBytes (0 for container rows)+  }++-- | Spec-level node: brackets a subtree, monitoring the configured namespaces for its duration, and+-- provides a 'ResourceWatcher' handle to children (via the 'resourceWatcher' context) so tests can+-- call 'markEvent'. Artifacts are written into the node's folder when it finishes.+introduceResourceWatcher :: (+  KubectlBasicWithoutReader context m+  )+  => ResourceWatcherOptions+  -> SpecFree (LabelValue "resourceWatcher" ResourceWatcher :> context) m ()+  -> SpecFree context m ()+introduceResourceWatcher options =+  introduceWith [i|Watch pod resources in #{scope options}|] resourceWatcher (void . withResourceWatcher options)++-- | Run @action@ (given a 'ResourceWatcher' handle) while sampling per-pod CPU/memory/network,+-- writing artifacts on completion. Obtains the cluster and @kubectl@ binary from the context.+withResourceWatcher :: (+  MonadUnliftIO m, MonadLoggerIO m+  , HasBaseContextMonad context m, HasKubernetesClusterContext context, HasFile context "kubectl"+  )+  => ResourceWatcherOptions+  -> (ResourceWatcher -> m a)+  -> m a+withResourceWatcher options action = do+  kcc <- getContext kubernetesCluster+  kubectlBinary <- askFile @"kubectl"+  withResourceWatcher' kcc kubectlBinary options action++-- | Same as 'withResourceWatcher', but with the 'KubernetesClusterContext' and @kubectl@ path+-- passed in explicitly.+withResourceWatcher' :: (+  MonadUnliftIO m, MonadLoggerIO m, HasBaseContextMonad context m+  )+  => KubernetesClusterContext+  -> FilePath+  -> ResourceWatcherOptions+  -> (ResourceWatcher -> m a)+  -> m a+withResourceWatcher' kcc kubectlBinary opts@(ResourceWatcherOptions {..}) action = do+  env <- getKubectlEnvironment kcc+  startTime <- liftIO getCurrentTime+  samplesRef <- newIORef (M.empty :: Map Text [Sample])+  eventsRef <- newIORef ([] :: [(Double, Text)])++  let rw = ResourceWatcher $ \label -> do+        now <- getCurrentTime+        modifyIORef' eventsRef ((realToFrac (diffUTCTime now startTime), label) :)++  let keep ns = null resourceWatcherNamespaces || ns `elem` resourceWatcherNamespaces++  -- Bound every kubectl call with --request-timeout so a poll can't block indefinitely. Without it, a+  -- call made while the cluster is tearing down can wedge, and cancelling the loop (withAsync) then+  -- blocks forever in cleanupProcess/waitForProcess, hanging the whole teardown. With it, kubectl exits+  -- on its own and the loop is always promptly cancellable.+  let reqTimeout = "--request-timeout=10s"+  let pollOnce = do+        now <- liftIO getCurrentTime+        let elapsed = realToFrac (diffUTCTime now startTime) :: Double+        (ec, nodesOut, _) <- readCreateProcessWithExitCode+          ((proc kubectlBinary ["get", "nodes", "-o", "name", reqTimeout]) { env = Just env }) ""+        when (ec == ExitSuccess) $+          forM_ (nodeNames (toText nodesOut)) $ \node -> do+            (ec2, out, _) <- readCreateProcessWithExitCode+              ((proc kubectlBinary ["get", "--raw", [i|/api/v1/nodes/#{node}/proxy/stats/summary|], reqTimeout]) { env = Just env }) ""+            when (ec2 == ExitSuccess) $+              forM_ (parseSamples resourceWatcherContainerLevel (encodeUtf8 (toText out))) $ \(ns, key, ccns, cn, mem, rx, tx) ->+                when (keep ns) $+                  modifyIORef' samplesRef (M.insertWith (<>) (ns <> "/" <> key) [Sample elapsed ccns cn mem rx tx])++  let loop = forever $ do+        handleAny (\e -> debug [i|(#{scope opts}) summary-api sample failed: #{e}|]) pollOnce+        threadDelay resourceWatcherIntervalMicros++  let writeArtifacts = do+        cleaned <- M.map (sortOn sElapsed) . M.filter (not . null) <$> readIORef samplesRef+        events <- sortOn fst <$> readIORef eventsRef+        if M.null cleaned+          then debug [i|(#{scope opts}) No pod resource samples collected; skipping artifacts|]+          else getCurrentFolder >>= \case+            Nothing -> debug [i|(#{scope opts}) No current folder; skipping resource artifacts|]+            Just dir -> writeAll opts dir cleaned events++  finally (withAsync loop (const (action rw))) writeArtifacts++-- | Label for the @namespace@ scope, used in log messages.+scope :: ResourceWatcherOptions -> Text+scope (ResourceWatcherOptions { resourceWatcherNamespaces = [] }) = "all namespaces"+scope (ResourceWatcherOptions { resourceWatcherNamespaces = nss }) = T.intercalate "," nss++-- | @node/<name>@ lines from @kubectl get nodes -o name@ → bare node names.+nodeNames :: Text -> [Text]+nodeNames = mapMaybe (T.stripPrefix "node/" . T.strip) . T.lines++-- | Pull @(namespace, key, cpuCoreNs, cpuNanoCores, memWs, rxBytes, txBytes)@ out of a summary-API+-- response. @key@ is @pod@ (or @pod/container@ when @containerLevel@). Containers carry no network,+-- so rx\/tx are 0 for them. Missing fields default to 0; malformed JSON yields no rows.+parseSamples :: Bool -> ByteString -> [(Text, Text, Integer, Integer, Integer, Integer, Integer)]+parseSamples containerLevel bs = case eitherDecodeStrict bs of+  Left _ -> []+  Right v -> concatMap perPod (asArray (lookupKey "pods" v))+  where+    perPod p =+      let ns = strAt ["podRef", "namespace"] p+          pod = strAt ["podRef", "name"] p+      in if T.null pod then [] else if containerLevel+        then [ (ns, pod <> "/" <> cn, intAt ["cpu", "usageCoreNanoSeconds"] c, intAt ["cpu", "usageNanoCores"] c+               , intAt ["memory", "workingSetBytes"] c, 0, 0)+             | c <- asArray (lookupKey "containers" p), let cn = strAt ["name"] c, not (T.null cn) ]+        else [ (ns, pod, intAt ["cpu", "usageCoreNanoSeconds"] p, intAt ["cpu", "usageNanoCores"] p+               , intAt ["memory", "workingSetBytes"] p, intAt ["network", "rxBytes"] p, intAt ["network", "txBytes"] p) ]+    asArray (Just (Array a)) = toList a+    asArray _ = []++lookupKey :: Text -> Value -> Maybe Value+lookupKey k (Object o) = KM.lookup (AK.fromText k) o+lookupKey _ _ = Nothing++intAt :: [Text] -> Value -> Integer+intAt [] (Number n) = round n+intAt (k:ks) (Object o) = maybe 0 (intAt ks) (KM.lookup (AK.fromText k) o)+intAt _ _ = 0++strAt :: [Text] -> Value -> Text+strAt [] (String s) = s+strAt (k:ks) (Object o) = maybe "" (strAt ks) (KM.lookup (AK.fromText k) o)+strAt _ _ = ""++-- | Write all artifacts for the collected (non-empty, time-sorted) per-pod series.+writeAll :: (MonadUnliftIO m, MonadLoggerIO m, HasBaseContextMonad context m)+  => ResourceWatcherOptions -> FilePath -> Map Text [Sample] -> [(Double, Text)] -> m ()+writeAll opts dir cleaned events = do+  -- Raw time series.+  let csvRows = [ [i|#{fmt1 (sElapsed s)},#{pod},#{sCpuCoreNs s},#{sCpuNano s},#{sMem s},#{sRx s},#{sTx s}|]+                | (pod, pts) <- M.toList cleaned, s <- pts ]+  liftIO $ writeFileText (dir </> "pod-resources.csv")+    (T.unlines ("elapsed_s,pod,cpu_core_ns,cpu_nanocores,mem_ws_bytes,net_rx_bytes,net_tx_bytes" : csvRows))++  -- Per-pod derived totals (CPU-seconds from the cumulative counter; net totals = last-first).+  let derived = [ (pod, cpuSeconds pts, memPeak pts, memMean pts, deltaOf sRx pts, deltaOf sTx pts)+                | (pod, pts) <- M.toList cleaned ]+      byCpu = sortOn (\(_, c, _, _, _, _) -> Down c) derived+      totCpu = sum [c | (_, c, _, _, _, _) <- derived]+      totRx  = sum [r | (_, _, _, _, r, _) <- derived]+      totTx  = sum [t | (_, _, _, _, _, t) <- derived]++  liftIO $ BL.writeFile (dir </> "pod-resources-summary.json") $ encode $ object+    [ "pods" .= [ object [ "pod" .= pod, "cpu_seconds" .= c, "mem_peak_bytes" .= mp+                         , "mem_mean_bytes" .= mm, "net_rx_bytes" .= rx, "net_tx_bytes" .= tx ]+                | (pod, c, mp, mm, rx, tx) <- byCpu ]+    , "totals" .= object [ "cpu_seconds" .= totCpu, "net_rx_bytes" .= totRx, "net_tx_bytes" .= totTx ]+    , "events" .= [ object ["elapsed_s" .= e, "label" .= l] | (e, l) <- events ]+    ]++  liftIO $ writeFileText (dir </> "pod-resources-events.csv")+    (T.unlines ("elapsed_s,label" : [ [i|#{fmt1 e},#{l}|] | (e, l) <- events ]))++  -- Peak CPU (millicores) and memory (MiB) per pod, sorted descending (also logged).+  let cpuPeaks = sortOn (Down . snd) [ (pod, foldl' max 0 (map sCpuNano pts)) | (pod, pts) <- M.toList cleaned ]+      cpuPeakText = T.unlines [ [i|#{fmt1 (fromIntegral c / 1e6)}m\t#{pod}|] | (pod, c) <- cpuPeaks ]+  liftIO $ writeFileText (dir </> "pod-cpu-peak.txt") cpuPeakText+  info [i|Peak pod CPU, millicores (#{scope opts}):\n#{cpuPeakText}|]++  let memPeaks = sortOn (Down . snd) [ (pod, memPeak pts) | (pod, pts) <- M.toList cleaned ]+      memPeakText = T.unlines [ [i|#{fmtMiB m} MiB\t#{pod}|] | (pod, m) <- memPeaks ]+  liftIO $ writeFileText (dir </> "pod-memory-peak.txt") memPeakText+  info [i|Peak pod memory (#{scope opts}):\n#{memPeakText}|]++  when (resourceWatcherWriteReport opts) $ do+    let cpuSvg = renderSeriesSvg "Pod CPU usage over time (millicores)" "No CPU samples."+                   (M.map (\pts -> [(sElapsed s, fromIntegral (sCpuNano s) / 1e6) | s <- pts]) cleaned)+        memSvg = renderSeriesSvg "Pod memory working set over time (MiB)" "No memory samples."+                   (M.map (\pts -> [(sElapsed s, fromIntegral (sMem s) / mib) | s <- pts]) cleaned)+        netSvg = renderSeriesSvg "Pod cumulative network rx over time (MiB)" "No network samples."+                   (M.map (\pts -> [(sElapsed s, fromIntegral (sRx s) / mib) | s <- pts]) cleaned)+    liftIO $ writeFileText (dir </> "pod-cpu.svg") cpuSvg+    liftIO $ writeFileText (dir </> "pod-memory.svg") memSvg+    liftIO $ writeFileText (dir </> "pod-network.svg") netSvg+    liftIO $ writeFileText (dir </> "pod-resources-report.html") $+      renderReport byCpu (totCpu, totRx, totTx) events cpuSvg memSvg netSvg++  where+    mib = 1024 * 1024 :: Double+    cpuSeconds pts = fromIntegral (deltaOf sCpuCoreNs pts) / 1e9 :: Double+    -- cumulative counters are monotonic, so total over the window = max - min+    deltaOf f pts = let ys = map f pts; mx = foldl' max 0 ys in mx - foldl' min mx ys+    memPeak pts = foldl' max 0 (map sMem pts)+    memMean pts = if null pts then 0 else sum (map sMem pts) `div` fromIntegral (length pts)++-- | A self-contained HTML report: headline totals, ranked table, inline charts, event markers.+renderReport+  :: [(Text, Double, Integer, Integer, Integer, Integer)]  -- (pod, cpuSec, memPeak, memMean, rx, tx)+  -> (Double, Integer, Integer)                             -- (totalCpuSec, totalRx, totalTx)+  -> [(Double, Text)]                                       -- events+  -> Text -> Text -> Text                                   -- cpu/mem/net SVGs+  -> Text+renderReport rows (totCpu, totRx, totTx) events cpuSvg memSvg netSvg = [i|<!DOCTYPE html>+<html><head><meta charset="utf-8"><title>Pod resource report</title>+<style>body{font-family:sans-serif;margin:2em;max-width:1100px}table{border-collapse:collapse}+td,th{border:1px solid \#ccc;padding:3px 8px;text-align:right}th:first-child,td:first-child{text-align:left}+svg{max-width:100%;height:auto;border:1px solid \#eee;margin:1em 0}</style></head><body>+<h1>Pod resource report</h1>+<p><b>Total CPU:</b> #{fmt1 totCpu} core-seconds &nbsp; <b>Total net rx:</b> #{fmtMiB totRx} MiB &nbsp; <b>Total net tx:</b> #{fmtMiB totTx} MiB</p>+<h2>Per-pod totals (by CPU-seconds)</h2>+<table><tr><th>pod</th><th>CPU (core-s)</th><th>mem peak (MiB)</th><th>mem mean (MiB)</th><th>net rx (MiB)</th><th>net tx (MiB)</th></tr>+#{podRows}+</table>+<h2>Events</h2>+<table><tr><th>elapsed (s)</th><th>label</th></tr>+#{eventRows}+</table>+<h2>CPU</h2>#{cpuSvg}+<h2>Memory</h2>#{memSvg}+<h2>Network (cumulative rx)</h2>#{netSvg}+</body></html>+|]+  where+    podRows = T.concat [ tr [pod, fmt1 c, fmtMiB mp, fmtMiB mm, fmtMiB rx, fmtMiB tx]+                       | (pod, c, mp, mm, rx, tx) <- rows ]+    eventRows = T.concat [ tr [fmt1 e, l] | (e, l) <- events ]+    tr cells = "<tr>" <> T.concat ["<td>" <> c <> "</td>" | c <- cells] <> "</tr>"++fmt1 :: Double -> Text+fmt1 x = toText (showFFloat (Just 1) x "")++fmtMiB :: Integer -> Text+fmtMiB b = fmt1 (fromIntegral b / (1024 * 1024))
lib/Test/Sandwich/Contexts/Kubernetes/SeaweedFS.hs view
@@ -20,18 +20,40 @@   , withSeaweedFS   , withSeaweedFS' +  -- * Options+  , defaultSeaweedFSOptions+  , fastSeaweedFSOptions++  -- * Other options+  , defaultSeaweedFSCsiDriverOptions+  , defaultSeaweedFSS3Options+  , defaultSeaweedFsOperatorImageExpr+  , defaultSeaweedFSProbeOverride+   -- * Types   , SeaweedFSOptions(..)-  , defaultSeaweedFSOptions+  , SeaweedFSCsiDriverOptions(..)+  , SeaweedFSS3Options(..)+  , SeaweedFSProbeOverride(..)    , seaweedFs   , SeaweedFSContext(..)   , HasSeaweedFSContext++  -- * Shared internals (used by "Test.Sandwich.Contexts.Kubernetes.SeaweedFSMini")+  , ContextWithSeaweedFS+  , seaweedFsStorageClassName+  , s3ConfigSecretYaml+  , installSeaweedFsCsiDriver+  , retryKubectl   ) where  import Control.Monad+import Control.Monad.IO.Unlift (MonadUnliftIO)+import Control.Monad.Logger (MonadLoggerIO) import Data.Aeson as A import qualified Data.List as L+import qualified Data.Map as Map import Data.String.Interpolate import qualified Data.Text as T import qualified Data.Vector as V@@ -41,42 +63,186 @@ import System.FilePath import Test.Sandwich import Test.Sandwich.Contexts.Files-import Test.Sandwich.Contexts.Kubernetes.Images (loadImage')+import Test.Sandwich.Contexts.Kubernetes.Images (loadImage', loadImageIfNecessary') import Test.Sandwich.Contexts.Kubernetes.Types import Test.Sandwich.Contexts.Kubernetes.Util.Aeson import Test.Sandwich.Contexts.Nix+import qualified Toml+import Toml (Table'(MkTable), Value'(..))+import UnliftIO.Concurrent (threadDelay) import UnliftIO.Environment+import UnliftIO.Exception (handleAny, throwIO) import UnliftIO.IO (withFile) import UnliftIO.Process-import UnliftIO.Temporary   data SeaweedFSContext = SeaweedFSContext {   seaweedFsOptions :: SeaweedFSOptions+  -- | @StorageClass@ for SeaweedFS-backed volumes, if the CSI driver was installed (see+  -- 'seaweedFsCsiDriver').+  , seaweedFsCsiStorageClass :: Maybe Text+  -- | Filer JWT write signing key (security.toml @jwt.filer_signing.key@), read from the+  -- @\<baseName\>-security-config@ Secret; present it to call the filer HTTP API directly.+  -- 'Nothing' if absent.+  , seaweedFsFilerJwtWriteKey :: Maybe Text+  -- | Filer JWT read signing key. Always 'Nothing': the pinned operator doesn't emit one.+  , seaweedFsFilerJwtReadKey :: Maybe Text   } deriving (Show)  data SeaweedFSOptions = SeaweedFSOptions {-  seaweedFsImage :: Text+  seaweedFsImage :: ImageLoadSpec+  -- | Extra images to preload into the cluster (so operator-managed pods don't pull them at+  -- runtime). Defaults to @[]@.+  , seaweedFsExtraImages :: [ImageLoadSpec]+  -- | The Nix expression (built via the test's nix context) producing the operator manager image+  -- tarball. Defaults to 'defaultSeaweedFsOperatorImageExpr'.+  , seaweedFsOperatorImageExpr :: Text   , seaweedFsBaseName :: Text   , seaweedFsMasterReplicas :: Int   , seaweedFsFilerReplicas :: Int   , seaweedFsVolumeReplicas :: Int+  -- | Set @master.concurrentStart: true@, so the operator creates the+  -- master\/volume\/filer StatefulSets in one pass instead of gating each on+  -- the previous. Cuts startup time; the operator marks it testing-only.+  -- Defaults to 'False' (ordered startup).+  , seaweedFsMasterConcurrentStart :: Bool+  , seaweedFsServerExtraArgs :: [Text]+  -- | Raw @filer.toml@ for the filer metadata store, dropped verbatim into the Seaweed CR's+  -- @spec.filer.config@. 'Nothing' uses the operator default (embedded @leveldb2@). Supply a+  -- @[leveldb3]@\/@[postgres]@\/@[redis2]@ etc. block to select another store; for external+  -- stores you must run the backing DB and (for SQL) create the table yourself.+  , seaweedFsFilerConfig :: Maybe Text+  , seaweedFsMasterReadinessProbe :: Maybe SeaweedFSProbeOverride+  , seaweedFsVolumeReadinessProbe :: Maybe SeaweedFSProbeOverride+  , seaweedFsFilerReadinessProbe :: Maybe SeaweedFSProbeOverride+  , seaweedFsMasterLivenessProbe :: Maybe SeaweedFSProbeOverride+  , seaweedFsVolumeLivenessProbe :: Maybe SeaweedFSProbeOverride+  , seaweedFsFilerLivenessProbe :: Maybe SeaweedFSProbeOverride   , seaweedFsVolumeServerDiskCount :: Int   , seaweedFsVolumeSizeLimitMb :: Int   , seaweedFsVolumeStorageRequest :: Text+  -- | If 'Just', deploy a standalone S3 gateway (@spec.s3@ in the Seaweed CR).+  -- Defaults to 'Just' 'defaultSeaweedFSS3Options'.+  , seaweedFsS3 :: Maybe SeaweedFSS3Options+  -- | Whether to install the+  -- [seaweedfs-csi-driver](https://github.com/seaweedfs/seaweedfs-csi-driver),+  -- which provisions Kubernetes @PersistentVolume@s backed by this SeaweedFS+  -- filer (via the @seaweedfs-storage@ 'StorageClass'). Defaults to 'Just'+  -- 'defaultSeaweedFSCsiDriverOptions'.+  , seaweedFsCsiDriver :: Maybe SeaweedFSCsiDriverOptions   } deriving (Show)+-- | Default options: 3 master replicas, 2 filer replicas, 1 volume replica. defaultSeaweedFSOptions :: SeaweedFSOptions defaultSeaweedFSOptions = SeaweedFSOptions {-  seaweedFsImage = "chrislusf/seaweedfs:3.73"+  seaweedFsImage = ImageLoadSpecDocker "chrislusf/seaweedfs:4.33" IfNotPresent+  , seaweedFsExtraImages = []+  , seaweedFsOperatorImageExpr = defaultSeaweedFsOperatorImageExpr   , seaweedFsBaseName = "seaweed1"   , seaweedFsMasterReplicas = 3   , seaweedFsFilerReplicas = 2   , seaweedFsVolumeReplicas = 1+  , seaweedFsMasterConcurrentStart = False+  , seaweedFsServerExtraArgs = []+  , seaweedFsFilerConfig = Nothing+  , seaweedFsMasterReadinessProbe = Nothing+  , seaweedFsVolumeReadinessProbe = Nothing+  , seaweedFsFilerReadinessProbe = Nothing+  , seaweedFsMasterLivenessProbe = Nothing+  , seaweedFsVolumeLivenessProbe = Nothing+  , seaweedFsFilerLivenessProbe = Nothing   , seaweedFsVolumeServerDiskCount = 1   , seaweedFsVolumeSizeLimitMb = 1024   , seaweedFsVolumeStorageRequest = "2Gi"+  , seaweedFsS3 = Just defaultSeaweedFSS3Options+  , seaweedFsCsiDriver = Just defaultSeaweedFSCsiDriverOptions   } +-- | Single-node SeaweedFS options tuned for fast startup on ephemeral test+-- clusters: one replica each, parallel bring-up, @-ip.bind=0.0.0.0@ to avoid+-- the startup DNS crash-loop, and short readiness probes.+fastSeaweedFSOptions :: SeaweedFSOptions+fastSeaweedFSOptions = defaultSeaweedFSOptions {+  seaweedFsMasterReplicas = 1+  , seaweedFsFilerReplicas = 1+  , seaweedFsVolumeReplicas = 1+  , seaweedFsMasterConcurrentStart = True+  , seaweedFsServerExtraArgs = ["-ip.bind=0.0.0.0"]+  , seaweedFsMasterReadinessProbe = Just fastReadinessProbe+  , seaweedFsVolumeReadinessProbe = Just fastReadinessProbe+  , seaweedFsFilerReadinessProbe = Just fastReadinessProbe+  }+  where+    fastReadinessProbe = defaultSeaweedFSProbeOverride {+      seaweedFsProbeInitialDelaySeconds = Just 2+      , seaweedFsProbePeriodSeconds = Just 2+      , seaweedFsProbeSuccessThreshold = Just 1+      }++data SeaweedFSProbeOverride = SeaweedFSProbeOverride {+  seaweedFsProbeInitialDelaySeconds :: Maybe Int+  , seaweedFsProbeTimeoutSeconds :: Maybe Int+  , seaweedFsProbePeriodSeconds :: Maybe Int+  , seaweedFsProbeSuccessThreshold :: Maybe Int+  , seaweedFsProbeFailureThreshold :: Maybe Int+  } deriving (Show, Eq)++defaultSeaweedFSProbeOverride :: SeaweedFSProbeOverride+defaultSeaweedFSProbeOverride = SeaweedFSProbeOverride {+  seaweedFsProbeInitialDelaySeconds = Nothing+  , seaweedFsProbeTimeoutSeconds = Nothing+  , seaweedFsProbePeriodSeconds = Nothing+  , seaweedFsProbeSuccessThreshold = Nothing+  , seaweedFsProbeFailureThreshold = Nothing+  }++-- | Options for installing the SeaweedFS CSI driver.+data SeaweedFSCsiDriverOptions = SeaweedFSCsiDriverOptions {+  -- | The seaweedfs-csi-driver release (git tag) whose @deploy/kubernetes/seaweedfs-csi.yaml@+  -- manifest to install, e.g. @\"v1.4.5\"@.+  seaweedFsCsiDriverVersion :: Text+  -- | Images referenced by the CSI driver manifest, preloaded into the cluster+  -- before applying it (the manifest pins @imagePullPolicy: IfNotPresent@, so+  -- preloading avoids any runtime pull). Must match+  -- 'seaweedFsCsiDriverVersion'.+  , seaweedFsCsiDriverImages :: [ImageLoadSpec]+  } deriving (Show, Eq)++defaultSeaweedFSCsiDriverOptions :: SeaweedFSCsiDriverOptions+defaultSeaweedFSCsiDriverOptions = SeaweedFSCsiDriverOptions {+  seaweedFsCsiDriverVersion = "v1.4.5"+  , seaweedFsCsiDriverImages = fmap (`ImageLoadSpecDocker` IfNotPresent) [+      "chrislusf/seaweedfs-csi-driver:latest"+      , "chrislusf/seaweedfs-mount:latest"+      , "registry.k8s.io/sig-storage/csi-node-driver-registrar:v2.8.0"+      , "registry.k8s.io/sig-storage/csi-provisioner:v3.5.0"+      , "registry.k8s.io/sig-storage/csi-attacher:v4.3.0"+      , "registry.k8s.io/sig-storage/csi-resizer:v1.8.0"+      , "registry.k8s.io/sig-storage/livenessprobe:v2.10.0"+      ]+  }++seaweedFsStorageClassName :: Text+seaweedFsStorageClassName = "seaweedfs-storage"++-- | Options for the standalone S3 gateway (see 'seaweedFsS3'). The gateway is provisioned with a+-- single admin identity using these credentials; consumers that talk to the gateway authenticate+-- with them.+data SeaweedFSS3Options = SeaweedFSS3Options {+  seaweedFsS3AccessKey :: Text+  , seaweedFsS3SecretKey :: Text+  } deriving (Show, Eq)++defaultSeaweedFSS3Options :: SeaweedFSS3Options+defaultSeaweedFSS3Options = SeaweedFSS3Options {+  seaweedFsS3AccessKey = "seaweedfs"+  , seaweedFsS3SecretKey = "seaweedfssecretkey"+  }++-- | The seaweedfs-csi-driver manifest deploys into the @default@ namespace (its RBAC+-- subjects are hardcoded there), regardless of where the SeaweedFS filer lives.+seaweedFsCsiNamespace :: String+seaweedFsCsiNamespace = "default"+ seaweedFs :: Label "seaweedFs" SeaweedFSContext seaweedFs = Label type HasSeaweedFSContext context = HasLabel context "seaweedFs" SeaweedFSContext@@ -128,109 +294,356 @@   baseEnv <- getEnvironment    NixContext {..} <- getContext nixContext+  -- Reuse the test's nix context for the nixpkgs pin, rather than pinning our own.+  let renderWithPkgs = renderDerivationWithPkgs nixContextNixpkgsDerivation -  let cp = proc nixContextNixBinary [-        "build", "--impure"-        , "--extra-experimental-features", "nix-command"-        , "--expr", seaweedFsOperatorDerivation-        , "--no-link"-        , "--json"-        ]+  let env = baseEnv+          & (("KUBECONFIG", kubernetesClusterKubeConfigPath) :)+          & L.nubBy (\x y -> fst x == fst y) -  operatorJson <- withFile "/dev/null" WriteMode $ \hNull ->-    readCreateProcess (cp { std_err = UseHandle hNull }) ""+  let runK name args = createProcessWithFileLogging' name ((proc kubectlBinary args) { env = Just env })+                       >>= waitForProcess >>= (`shouldBe` ExitSuccess) -  operatorPath <- case A.eitherDecodeStrict (encodeUtf8 operatorJson) of-    Right (A.Array (V.toList -> ((A.Object (aesonLookup "outputs" -> Just (A.Object (aesonLookup "out" -> Just (A.String p))))):_))) -> pure p-    x -> expectationFailure [i|Couldn't parse seaweedfs-operator path: #{x}|]+  (storageClass, jwtWriteKey, jwtReadKey) <- timeAction "SeaweedFS setup" $ do+    -- The operator manager image, built entirely by Nix (see 'seaweedFsOperatorImageExpr').+    info [i|------------------ Building and loading SeaweedFS operator image ------------------|]+    operatorImageTarball <- timeAction "Build operator image (Nix)" $+      nixBuildExprToPath nixContextNixBinary (toString (renderWithPkgs (seaweedFsOperatorImageExpr options)))+    operatorImageName <- timeAction "Load operator image into cluster" $+      loadImage' kcc (ImageLoadSpecTarball (toString operatorImageTarball))+    info [i|Loaded operator image into cluster as: #{operatorImageName}|] -  info [i|Got operator path: #{operatorPath}|]+    info [i|------------------ Preloading SeaweedFS server image ------------------|]+    -- Load conditionally so a baked-in image (e.g. from a minikube preload) is skipped; either way we+    -- get back the ref to configure the SeaweedFS CR with.+    imageName <- timeAction "Preload SeaweedFS server image" $+      loadImageIfNecessary' kcc (seaweedFsImage options) -  -- Build a Nix environment with some tools needed by the operator-  nixEnvPath <- buildNixSymlinkJoin ["coreutils", "gnumake", "go", "stdenv", "which"]-  info [i|Built Nix environment for operator builds: #{nixEnvPath}|]+    info [i|------------------ Preloading extra images ------------------|]+    timeAction "Preload extra images" $+      forM_ (seaweedFsExtraImages options) $ \spec -> do+        loaded <- loadImage' kcc spec+        info [i|Preloaded extra image: #{loaded}|] -  let originalSearchPathParts = maybe [] splitSearchPath (L.lookup "PATH" baseEnv)-  let finalPath = (nixEnvPath </> "bin") : takeDirectory kubectlBinary : originalSearchPathParts-                & fmap toText-                & T.intercalate (toText [searchPathSeparator])-                & toString+    -- The operator's CRD + controller manifests, rendered by Nix via kustomize+    info [i|------------------ Installing SeaweedFS operator ------------------|]+    manifestsDir <- timeAction "Render operator manifests (Nix)" $+      nixBuildExprToPath nixContextNixBinary (toString (renderWithPkgs seaweedFsOperatorManifestsExpr))+    timeAction "Apply operator manifests" $ do+      runK "seaweedfs-operator-crds" ["apply", "--server-side", "-f", toString manifestsDir </> "crd.yaml"]+      runK "seaweedfs-operator-deploy" ["apply", "-f", toString manifestsDir </> "operator.yaml"]+    timeAction "Wait for operator controller-manager" $+      runK "seaweedfs-operator-wait" [+        "wait", "deployment/seaweedfs-operator-controller-manager", "-n", "seaweedfs-operator-system"+        , "--for", "condition=Available", "--timeout=300s"+        ] -  let env = baseEnv-          & (("KUBECONFIG", kubernetesClusterKubeConfigPath) :)-          & (("PATH", finalPath) :)-          & L.nubBy (\x y -> fst x == fst y)+    -- The S3 gateway mounts this secret as its identities config; create it before the CR so the+    -- gateway pod can start. Done with @apply@ so a re-run against an existing namespace is fine.+    whenJust (seaweedFsS3 options) $ \s3Options -> timeAction "Create S3 config secret" $+      createProcessWithFileLoggingAndStdin' "seaweedfs-s3-secret" ((proc kubectlBinary ["apply", "-f", "-"]) { env = Just env }) (toString (s3ConfigSecretYaml namespace (seaweedFsBaseName options) s3Options))+        >>= waitForProcess >>= (`shouldBe` ExitSuccess) -  withSystemTempDirectory "seaweedfs-operator" $ \dir -> do-    let target = dir </> "seaweefs-operator"-    _ <- readCreateProcess (proc "cp" ["-r", toString operatorPath, target]) ""-    _ <- readCreateProcess (proc "chmod" ["-R", "u+w", target]) ""+    info [i|------------------ Creating SeaweedFS deployment ------------------|]+    timeAction "Create Seaweed CR" $ do+      let val = decodeUtf8 $ A.encode $ example namespace imageName options+      createProcessWithFileLoggingAndStdin' "seaweedfs-kubectl-create" ((proc kubectlBinary ["create", "-f", "-"]) { env = Just env }) val+        >>= waitForProcess >>= (`shouldBe` ExitSuccess) -    let runOperatorCmd cmd extraEnv = createProcessWithFileLogging' "seaweedfs-operator" (-          (shell cmd) {-              env = Just (env <> extraEnv)-              , cwd = Just target-              }-          ) >>= waitForProcess >>= (`shouldBe` ExitSuccess)+    timeAction "Wait for SeaweedFS cluster (master/volume/filer)" $ do+      info [i|Waiting for the SeaweedFS cluster (master/volume/filer) to be ready|]+      forM_ (["master", "volume", "filer"] :: [Text]) $ \component ->+        retryKubectl kubectlBinary env (toString ([i|seaweedfs-wait-#{component}|] :: Text))+          ["rollout", "status", "-n", toString namespace, toString ([i|statefulset/#{seaweedFsBaseName options}-#{component}|] :: Text), "--timeout=300s"]+      -- The standalone S3 gateway is a stateless Deployment (<baseName>-s3), not a StatefulSet.+      when (isJust (seaweedFsS3 options)) $+        retryKubectl kubectlBinary env "seaweedfs-wait-s3"+          ["rollout", "status", "-n", toString namespace, toString ([i|deployment/#{seaweedFsBaseName options}-s3|] :: Text), "--timeout=300s"] -    info [i|------------------ Building and uploading SeaweedFS Docker image ------------------|]+    storageClass <- case seaweedFsCsiDriver options of+      Nothing -> do+        info [i|Skipping SeaweedFS CSI driver installation|]+        pure Nothing+      Just csiOptions -> timeAction "Install CSI driver" $ do+        info [i|------------------ Preloading SeaweedFS CSI driver images ------------------|]+        forM_ (seaweedFsCsiDriverImages csiOptions) $ \spec -> do+          loaded <- loadImage' kcc spec+          info [i|Preloaded CSI image: #{loaded}|]+        info [i|------------------ Installing SeaweedFS CSI driver ------------------|]+        installSeaweedFsCsiDriver nixContextNixBinary nixContextNixpkgsDerivation kubectlBinary env namespace (seaweedFsBaseName options) csiOptions+        pure (Just seaweedFsStorageClassName) -    let initialImageName = "seaweedfs/seaweedfs-operator:v0.0.1"+    -- Read the operator's security.toml (a base64-encoded @Secret@) so callers can present the+    -- @jwt.filer_signing.key@ write key to the filer HTTP API. No read key is emitted, so it stays+    -- 'Nothing'.+    (jwtWriteKey, jwtReadKey) <- do+      let secretName = seaweedFsBaseName options <> "-security-config"+      securityToml <- handleAny (\_ -> pure "") $ readCreateProcess+        ((proc kubectlBinary+          [ "get", "secret", toString secretName, "-n", toString namespace+          , "-o", "go-template={{ index .data \"security.toml\" | base64decode }}" ]) { env = Just env }) ""+      let keys = parseFilerJwtKeys (T.pack securityToml)+      info [i|SeaweedFS filer JWT keys present: write=#{isJust (fst keys)} read=#{isJust (snd keys)}|]+      pure keys -    info [i|Doing make docker-build|]-    runOperatorCmd "make docker-build" [("IMG", toString initialImageName)]+    return (storageClass, jwtWriteKey, jwtReadKey) -    newImageName <- loadImage' kcc (ImageLoadSpecDocker initialImageName IfNotPresent)-    info [i|Loaded image into cluster as: #{newImageName}|]+  action $ SeaweedFSContext {+    seaweedFsOptions = options+    , seaweedFsCsiStorageClass = storageClass+    , seaweedFsFilerJwtWriteKey = jwtWriteKey+    , seaweedFsFilerJwtReadKey = jwtReadKey+    } -    info [i|------------------ Installing SeaweedFS operator ------------------|] -    info [i|Doing make install|]-    runOperatorCmd "make install" [("IMG", toString newImageName)]-    info [i|Doing make deploy|]-    runOperatorCmd "make deploy" [("IMG", toString newImageName)]+example :: Text -> Text -> SeaweedFSOptions -> Yaml.Value+example namespace imageName (SeaweedFSOptions {..}) = let Right x = Yaml.decodeEither' raw in x+ where+  -- Standalone S3 gateway (preferred over the deprecated filer-embedded S3). We turn off the+  -- embedded IAM (which, with no identities configured, denies everything) and instead point+  -- the gateway at a config secret holding a single admin identity (see 's3ConfigSecretYaml').+  s3Block :: Text+  s3Block = case seaweedFsS3 of+    Nothing -> ""+    Just _ -> [i|+  s3:+    replicas: 1+    iam: false+    configSecret:+      name: #{seaweedFsBaseName}-s3-config+      key: config.json|]+  -- The filer.toml store config, indented under @config: |@ (6 spaces, matching the post-dedent+  -- nesting). Defaults to the operator's embedded leveldb2.+  filerConfigBlock :: Text+  filerConfigBlock =+    let toml = fromMaybe "[leveldb2]\nenabled = true\ndir = \"/data/filerldb2\"" seaweedFsFilerConfig+    in mconcat ["\n      " <> l | l <- T.lines toml]+  -- See 'seaweedFsMasterConcurrentStart'.+  concurrentStartBlock :: Text+  concurrentStartBlock = if seaweedFsMasterConcurrentStart then "\n    concurrentStart: true" else ""+  -- Per-component @extraArgs:@ list (4-space indent), applied to master/volume/filer.+  extraArgsBlock :: Text+  extraArgsBlock+    | null seaweedFsServerExtraArgs = ""+    | otherwise = "\n    extraArgs:" <> mconcat ["\n    - \"" <> a <> "\"" | a <- seaweedFsServerExtraArgs]+  -- Per-component probe block, emitting only the timing fields the override sets.+  probeBlock :: Text -> Maybe SeaweedFSProbeOverride -> Text+  probeBlock _ Nothing = ""+  probeBlock key (Just p) =+    let field name sel = (\v -> "\n      " <> name <> ": " <> show v) <$> sel p+        fields = catMaybes [+            field "initialDelaySeconds" seaweedFsProbeInitialDelaySeconds+          , field "timeoutSeconds" seaweedFsProbeTimeoutSeconds+          , field "periodSeconds" seaweedFsProbePeriodSeconds+          , field "successThreshold" seaweedFsProbeSuccessThreshold+          , field "failureThreshold" seaweedFsProbeFailureThreshold+          ]+    in if null fields then "" else "\n    " <> key <> ":" <> mconcat fields+  raw = [__i|apiVersion: seaweed.seaweedfs.com/v1+             kind: Seaweed+             metadata:+               namespace: #{namespace}+               name: #{seaweedFsBaseName}+             spec:+               image: #{imageName}+               volumeServerDiskCount: #{seaweedFsVolumeServerDiskCount}+               hostSuffix: seaweed.abcdefg.com+               master:+                 replicas: #{seaweedFsMasterReplicas}#{concurrentStartBlock}#{extraArgsBlock}#{probeBlock "readinessProbe" seaweedFsMasterReadinessProbe}#{probeBlock "livenessProbe" seaweedFsMasterLivenessProbe}+                 volumeSizeLimitMB: #{seaweedFsVolumeSizeLimitMb}+               volume:+                 replicas: #{seaweedFsVolumeReplicas}#{extraArgsBlock}#{probeBlock "readinessProbe" seaweedFsVolumeReadinessProbe}#{probeBlock "livenessProbe" seaweedFsVolumeLivenessProbe}+                 requests:+                   storage: #{seaweedFsVolumeStorageRequest}+               filer:+                 replicas: #{seaweedFsFilerReplicas}#{extraArgsBlock}#{probeBlock "readinessProbe" seaweedFsFilerReadinessProbe}#{probeBlock "livenessProbe" seaweedFsFilerLivenessProbe}+                 config: |#{filerConfigBlock}#{s3Block}+             |] -    info [i|------------------ Creating SeaweedFS deployment ------------------|]+-- | A @Secret@ holding the SeaweedFS S3 identities config (the @-config@ file for @weed s3@),+-- with a single admin identity using the gateway's configured credentials. Referenced by the+-- standalone S3 gateway (see the @s3@ block in 'example').+s3ConfigSecretYaml :: Text -> Text -> SeaweedFSS3Options -> Text+s3ConfigSecretYaml namespace baseName (SeaweedFSS3Options {..}) = [i|apiVersion: v1+kind: Secret+metadata:+  name: #{baseName}-s3-config+  namespace: #{namespace}+type: Opaque+stringData:+  config.json: |+    {"identities":[{"name":"#{seaweedFsS3AccessKey}","credentials":[{"accessKey":"#{seaweedFsS3AccessKey}","secretKey":"#{seaweedFsS3SecretKey}"}],"actions":["Admin"]}]}+|] -    let val = decodeUtf8 $ A.encode $ example namespace options-    createProcessWithFileLoggingAndStdin' "seaweedfs-kubectl-create" ((shell [i|#{kubectlBinary} create -f -|]) { env = Just env }) val+-- | Extract the filer JWT signing keys (write, read) from a security.toml: the @key@ under+-- @[jwt.filer_signing]@ and @[jwt.filer_signing.read]@ respectively. Either is 'Nothing' if its+-- table/key is absent or the document doesn't parse.+parseFilerJwtKeys :: Text -> (Maybe Text, Maybe Text)+parseFilerJwtKeys tomlText = case Toml.parse tomlText of+  Left _ -> (Nothing, Nothing)+  Right table ->+    ( lookupString table ["jwt", "filer_signing", "key"]+    , lookupString table ["jwt", "filer_signing", "read", "key"]+    )+  where+    -- Follow a dotted path of TOML tables to a final string value.+    lookupString :: Table' a -> [Text] -> Maybe Text+    lookupString _ [] = Nothing+    lookupString (MkTable m) [k] = case snd <$> Map.lookup k m of+      Just (Text' _ s) -> Just s+      _ -> Nothing+    lookupString (MkTable m) (k : ks) = case snd <$> Map.lookup k m of+      Just (Table' _ sub) -> lookupString sub ks+      _ -> Nothing++-- | Install the seaweedfs-csi-driver pointed at this filer, so PVCs on the @seaweedfs-storage@+-- 'StorageClass' provision against it. The @--filer@ flag takes the HTTP address, so we point it+-- at @\<baseName\>-filer.\<namespace\>:8888@. Waits for the driver to roll out.+installSeaweedFsCsiDriver :: (+  MonadUnliftIO m, MonadLoggerIO m, HasBaseContextMonad context m, MonadFail m+  )+  -- | Path to the @nix@ binary (used to fetch the CSI manifest)+  => FilePath+  -- | Pinned nixpkgs (the test's nix context) to fetch the manifest with+  -> NixpkgsDerivation+  -- | Path to the @kubectl@ binary+  -> FilePath+  -- | Environment to run @kubectl@ with+  -> [(String, String)]+  -- | Namespace the SeaweedFS filer lives in+  -> Text+  -- | SeaweedFS base name (the filer Service is @\<baseName\>-filer@)+  -> Text+  -> SeaweedFSCsiDriverOptions+  -> m ()+installSeaweedFsCsiDriver nixBinary nixpkgsDerivation kubectlBinary env namespace baseName (SeaweedFSCsiDriverOptions {..}) = do+  let manifestUrl = [i|https://raw.githubusercontent.com/seaweedfs/seaweedfs-csi-driver/#{seaweedFsCsiDriverVersion}/deploy/kubernetes/seaweedfs-csi.yaml|] :: Text+  let filerAddress = [i|#{baseName}-filer.#{namespace}:8888|] :: Text++  timeAction "Apply CSI manifest" $ do+    info [i|Applying seaweedfs-csi-driver #{seaweedFsCsiDriverVersion} manifest, pointing it at filer '#{filerAddress}'|]+    -- Bake the filer address into the manifest's SEAWEEDFS_FILER placeholder up front, so it's a+    -- single rollout. Patching it after @apply@ instead double-rolls the controller, whose+    -- single-replica anti-affinity then deadlocks the new pod on a single-node cluster.+    manifestPath <- nixBuildExprToPath nixBinary (toString (renderDerivationWithPkgs nixpkgsDerivation (nixFetchUrlExpr manifestUrl)))+    manifest <- decodeUtf8 <$> readFileBS (toString manifestPath)+    let substituted = T.replace "SEAWEEDFS_FILER:8888" filerAddress manifest+    createProcessWithFileLoggingAndStdin' "seaweedfs-csi-apply"+      ((proc kubectlBinary ["apply", "-n", seaweedFsCsiNamespace, "-f", "-"]) { env = Just env }) (toString substituted)       >>= waitForProcess >>= (`shouldBe` ExitSuccess) -    action $ SeaweedFSContext {-      seaweedFsOptions = options-      }+  -- Wait for the CSI controller and node plugin. We skip the seaweedfs-mount DaemonSet: it uses+  -- updateStrategy OnDelete, which @kubectl rollout status@ rejects; its pod is created anyway and+  -- the PVC mount exercises it.+  timeAction "Wait for CSI driver (controller/node)" $ do+    info [i|Waiting for the seaweedfs-csi-driver to be ready|]+    forM_ ([("deployment", "seaweedfs-controller"), ("daemonset", "seaweedfs-node")] :: [(String, String)]) $ \(kind, name) ->+      retryKubectl kubectlBinary env (toString ([i|seaweedfs-wait-#{name}|] :: Text))+        ["rollout", "status", "-n", seaweedFsCsiNamespace, [i|#{kind}/#{name}|], "--timeout=300s"] +-- | Run a @kubectl@ command, retrying on failure. Used for @rollout status@ on resources+-- the SeaweedFS operator creates asynchronously, which may not exist the instant we ask.+retryKubectl :: (+  MonadUnliftIO m, MonadLoggerIO m, HasBaseContextMonad context m+  ) => FilePath -> [(String, String)] -> String -> [String] -> m ()+retryKubectl kubectlBinary env name args = go (2400 :: Int)+  where+    go n = handleAny (handler n) $+      createProcessWithFileLogging' name ((proc kubectlBinary args) { env = Just env })+        >>= waitForProcess >>= (`shouldBe` ExitSuccess)+    handler n e+      | n <= 1 = throwIO e+      | otherwise = do+          debug [i|(#{name}) not ready yet (#{n - 1} attempts left): #{e}|]+          threadDelay 5_000_000+          go (n - 1) -example :: Text -> SeaweedFSOptions -> Yaml.Value-example namespace (SeaweedFSOptions {..}) = let Right x = Yaml.decodeEither' raw in x- where raw = [i|apiVersion: seaweed.seaweedfs.com/v1-kind: Seaweed-metadata:-  namespace: #{namespace}-  name: #{seaweedFsBaseName}-spec:-  image: #{seaweedFsImage}-  volumeServerDiskCount: #{seaweedFsVolumeServerDiskCount}-  hostSuffix: seaweed.abcdefg.com-  master:-    replicas: #{seaweedFsMasterReplicas}-    volumeSizeLimitMB: #{seaweedFsVolumeSizeLimitMb}-  volume:-    replicas: #{seaweedFsVolumeReplicas}-    requests:-      storage: #{seaweedFsVolumeStorageRequest}-  filer:-    replicas: #{seaweedFsFilerReplicas}-    config: |-      [leveldb2]-      enabled = true-      dir = "/data/filerldb2"-|]+-- | Run @nix build --expr@ on a Nix expression and return the resulting store path.+nixBuildExprToPath :: (+  MonadUnliftIO m, HasBaseContextMonad context m+  ) => FilePath -> String -> m Text+nixBuildExprToPath nixBinary expr = do+  let cp = proc nixBinary [+        "build", "--impure"+        , "--extra-experimental-features", "nix-command"+        , "--expr", expr+        , "--no-link"+        , "--json"+        ]+  out <- withFile "/dev/null" WriteMode $ \hNull ->+    readCreateProcess (cp { std_err = UseHandle hNull }) ""+  case A.eitherDecodeStrict (encodeUtf8 out) of+    Right (A.Array (V.toList -> ((A.Object (aesonLookup "outputs" -> Just (A.Object (aesonLookup "out" -> Just (A.String p))))):_))) -> pure p+    x -> expectationFailure [i|Couldn't parse nix build output: #{x}|] -seaweedFsOperatorDerivation = [__i|with import <nixpkgs> {}; fetchFromGitHub {-                                     owner = "seaweedfs";-                                     repo = "seaweedfs-operator";-                                     rev = "6fa4c24d47c57daa10a084e3a5598efbb8d808c8";-                                     sha256 = "sha256-gFFIG2tglzvXoqzUvbzWAG2Bg2RwCCsuX0tXwV95D/0=";-                                   }-                                  |]+-- | Fetch a URL to a store path so we can tweak the contents before applying. Expects @pkgs@ in+-- scope (wrapped by 'renderDerivationWithPkgs'). Impure -- fine under @--impure@.+nixFetchUrlExpr :: Text -> Text+nixFetchUrlExpr url = [i|pkgs.runCommand "fetched" {} "cp ${builtins.fetchurl "#{url}"} $out"|]++-- | The pinned seaweedfs-operator source, as a @pkgs.fetchFromGitHub@ expression (expects @pkgs@+-- in scope -- see 'renderDerivationWithPkgs'). Points at our @codedownio@ fork, which adds the+-- per-component probe-timing CR fields the @\*ReadinessProbe@\/@\*LivenessProbe@ options use, on+-- top of an upstream release. The CRD schema matches what 'example' produces. When bumping the+-- rev/sha256, also bump 'seaweedFsOperatorVendorHash'.+seaweedFsOperatorSrc :: Text+seaweedFsOperatorSrc = [__i|pkgs.fetchFromGitHub {+                              owner = "codedownio";+                              repo = "seaweedfs-operator";+                              rev = "79173edd2b07f9a6eb7eab842eb028f429bd0fc5";+                              sha256 = "sha256-8lYc2vzGpwr7q0UJ5JdyiPifrKR95pHZGFXMLq/QJik=";+                            }|]++-- | @go.sum@ vendor hash for the operator at 'seaweedFsOperatorSrc'. Bump together with the rev.+seaweedFsOperatorVendorHash :: Text+seaweedFsOperatorVendorHash = "sha256-NGL69t6vOL7ayrYOoStkU+fWm2zMv5MW6Fc1lQVeeMs="++-- | Builds the operator manager image with Nix (mirrors the upstream Dockerfile: a static+-- @manager@ binary at @/manager@, run as nonroot), output as a tarball loaded via+-- 'ImageLoadSpecTarball'. Expects @pkgs@ in scope. The manager is built with a dedicated pinned+-- nixpkgs because the operator needs Go 1.26.+defaultSeaweedFsOperatorImageExpr :: Text+defaultSeaweedFsOperatorImageExpr = [__i|+  let+    goPkgs = import (pkgs.fetchFromGitHub {+      owner = "NixOS";+      repo = "nixpkgs";+      rev = "3e41b24abd260e8f71dbe2f5737d24122f972158";+      sha256 = "sha256-rxO+uc/KFbSJp+pgyXRuAX6QlG9hJdnt0BXpEQRXY+U=";+    }) { system = pkgs.system; };+    manager = goPkgs.buildGo126Module {+      pname = "seaweedfs-operator-manager";+      version = "1.0.28";+      src = #{seaweedFsOperatorSrc};+      vendorHash = "#{seaweedFsOperatorVendorHash}";+      subPackages = [ "cmd" ];+      env.CGO_ENABLED = 0;+      postInstall = "mv $out/bin/cmd $out/bin/manager";+    };+  in+  pkgs.dockerTools.buildImage {+    name = "seaweedfs/seaweedfs-operator";+    tag = "nix";+    copyToRoot = pkgs.runCommand "seaweedfs-operator-manager-root" {} "mkdir -p $out; cp ${manager}/bin/manager $out/manager";+    config = {+      Entrypoint = [ "/manager" ];+      User = "65532:65532";+    };+  }+  |]++-- | Renders the operator's CRD and controller manifests with kustomize at build time, so at test+-- time we just @kubectl apply@ them. Expects @pkgs@ in scope. Bakes in the @:nix@ operator image,+-- strips invalid OpenAPI int32/int64 format fields from the CRDs, and outputs @crd.yaml@ ++-- @operator.yaml@.+seaweedFsOperatorManifestsExpr :: Text+seaweedFsOperatorManifestsExpr = [__i|+  pkgs.runCommand "seaweedfs-operator-manifests" { nativeBuildInputs = [ pkgs.kustomize pkgs.perl ]; } ''+    cp -r ${#{seaweedFsOperatorSrc}} src && chmod -R u+w src && cd src+    perl -i -pe 's/\\s+format: int32\\n//g; s/\\s+format: int64\\n//g' config/crd/bases/*.yaml+    (cd config/manager && kustomize edit set image controller:latest=seaweedfs/seaweedfs-operator:nix)+    mkdir -p $out+    kustomize build config/crd > $out/crd.yaml+    kustomize build config/default > $out/operator.yaml+  ''+|]
+ lib/Test/Sandwich/Contexts/Kubernetes/SeaweedFSMini.hs view
@@ -0,0 +1,279 @@+{-# LANGUAGE ConstraintKinds #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE TypeOperators #-}+{-# OPTIONS_GHC -fno-warn-missing-signatures #-}+{-# OPTIONS_GHC -fno-warn-incomplete-uni-patterns #-}++{-|++Install a single-pod [SeaweedFS](https://github.com/seaweedfs/seaweedfs) on a Kubernetes cluster,+without the operator: one @weed server@ process runs master + volume + filer (+ optional S3) in a+single pod. Comes up much faster than "Test.Sandwich.Contexts.Kubernetes.SeaweedFS" (no CRDs, no+operator image build, no controller-manager wait), at the cost of being single-node only. Produces+the same 'SeaweedFSContext', so consumers don't change.++-}++module Test.Sandwich.Contexts.Kubernetes.SeaweedFSMini (+  introduceSeaweedFSMini++  -- * Bracket-style variants+  , withSeaweedFSMini+  , withSeaweedFSMini'++  -- * Options+  , defaultSeaweedFSMiniOptions+  , SeaweedFSMiniOptions(..)++  -- * Re-exports+  , SeaweedFSContext(..)+  , HasSeaweedFSContext+  , seaweedFs+  ) where++import qualified Data.List as L+import Data.String.Interpolate+import qualified Data.Text as T+import Relude+import System.Exit+import Test.Sandwich+import Test.Sandwich.Contexts.Files+import Test.Sandwich.Contexts.Kubernetes.Images (loadImage', loadImageIfNecessary')+import Test.Sandwich.Contexts.Kubernetes.SeaweedFS+import Test.Sandwich.Contexts.Kubernetes.Types+import Test.Sandwich.Contexts.Nix+import UnliftIO.Environment+import UnliftIO.Process+++-- | Options for the single-pod \"mini\" SeaweedFS (see 'introduceSeaweedFSMini'). Unlike+-- 'SeaweedFSOptions', there's no operator, no replicas, and no per-component probe tuning: one+-- @weed server@ process runs master + volume + filer (+ optional S3) in a single pod.+data SeaweedFSMiniOptions = SeaweedFSMiniOptions {+  seaweedFsMiniImage :: ImageLoadSpec+  -- | Name prefix for the created resources. The all-in-one @Deployment@ is @\<baseName\>-mini@,+  -- and the Services are @\<baseName\>-master@ \/ @\<baseName\>-filer@ \/ @\<baseName\>-s3@, matching+  -- the operator-based names so consumers are the same.+  , seaweedFsMiniBaseName :: Text+  -- | Extra args appended to @weed server@. Defaults to @[\"-ip.bind=0.0.0.0\"]@ (avoids the+  -- startup DNS bind crash-loop), matching 'fastSeaweedFSOptions'.+  , seaweedFsMiniExtraArgs :: [Text]+  , seaweedFsMiniVolumeSizeLimitMb :: Int+  -- | If 'Just', run the embedded S3 gateway (@weed server -s3@) with a single admin identity+  -- using these credentials. Defaults to 'Just' 'defaultSeaweedFSS3Options'.+  , seaweedFsMiniS3 :: Maybe SeaweedFSS3Options+  -- | Whether to install the seaweedfs-csi-driver pointed at this pod's filer, providing the+  -- @seaweedfs-storage@ 'StorageClass'. Defaults to 'Just' 'defaultSeaweedFSCsiDriverOptions'.+  , seaweedFsMiniCsiDriver :: Maybe SeaweedFSCsiDriverOptions+  } deriving (Show)++defaultSeaweedFSMiniOptions :: SeaweedFSMiniOptions+defaultSeaweedFSMiniOptions = SeaweedFSMiniOptions {+  seaweedFsMiniImage = ImageLoadSpecDocker "chrislusf/seaweedfs:4.33" IfNotPresent+  , seaweedFsMiniBaseName = "seaweed1"+  , seaweedFsMiniExtraArgs = ["-ip.bind=0.0.0.0"]+  , seaweedFsMiniVolumeSizeLimitMb = 1024+  , seaweedFsMiniS3 = Just defaultSeaweedFSS3Options+  , seaweedFsMiniCsiDriver = Just defaultSeaweedFSCsiDriverOptions+  }+++-- | Introduce a single-pod [SeaweedFS](https://github.com/seaweedfs/seaweedfs) on the Kubernetes+-- cluster, in a given namespace, using @weed server@ (master + volume + filer + optional S3) in one+-- pod. Unlike 'introduceSeaweedFS' this skips the operator entirely -- no CRDs, no operator image+-- build, no controller-manager wait -- so it comes up much faster, at the cost of being single-node+-- only. Produces the same 'SeaweedFSContext' (including the CSI 'StorageClass'), so consumers don't+-- change.+introduceSeaweedFSMini :: (+  KubernetesClusterBasicWithoutReader context m, HasNixContext context+  )+  -- | Namespace+  => Text+  -> SeaweedFSMiniOptions+  -> SpecFree (ContextWithSeaweedFS context) m ()+  -> SpecFree context m ()+introduceSeaweedFSMini namespace options = introduceBinaryViaNixPackage @"kubectl" "kubectl" . introduceWith "introduce SeaweedFS (mini)" seaweedFs (void . withSeaweedFSMini namespace options)++-- | Bracket-style version of 'introduceSeaweedFSMini'.+withSeaweedFSMini :: forall context m a. (+  HasCallStack, MonadFail m, KubectlBasic context m, HasNixContext context+  )+  -- | Namespace+  => Text+  -> SeaweedFSMiniOptions+  -> (SeaweedFSContext -> m a)+  -> m a+withSeaweedFSMini namespace options action = do+  kcc <- getContext kubernetesCluster+  kubectlBinary <- askFile @"kubectl"+  withSeaweedFSMini' kcc kubectlBinary namespace options action++-- | Same as 'withSeaweedFSMini', but allows you to pass in the 'KubernetesClusterContext' and+-- @kubectl@ binary path.+withSeaweedFSMini' :: forall context m a. (+  HasCallStack, MonadFail m, NixContextBasic context m+  )+  -- | Cluster context+  => KubernetesClusterContext+  -- | Path to @kubectl@ binary+  -> FilePath+  -- | Namespace+  -> Text+  -> SeaweedFSMiniOptions+  -> (SeaweedFSContext -> m a)+  -> m a+withSeaweedFSMini' kcc@(KubernetesClusterContext {kubernetesClusterKubeConfigPath}) kubectlBinary namespace options@(SeaweedFSMiniOptions {..}) action = do+  baseEnv <- getEnvironment++  NixContext {..} <- getContext nixContext++  let env = baseEnv+          & (("KUBECONFIG", kubernetesClusterKubeConfigPath) :)+          & L.nubBy (\x y -> fst x == fst y)++  storageClass <- timeAction "SeaweedFS mini setup" $ do+    info [i|------------------ Preloading SeaweedFS server image ------------------|]+    imageName <- timeAction "Preload SeaweedFS server image" $+      loadImageIfNecessary' kcc seaweedFsMiniImage++    -- The S3 gateway reads its identities from this secret; create it before the pod so the mount+    -- resolves. Done with @apply@ so a re-run against an existing namespace is fine.+    whenJust seaweedFsMiniS3 $ \s3Options -> timeAction "Create S3 config secret" $+      createProcessWithFileLoggingAndStdin' "seaweedfs-s3-secret" ((proc kubectlBinary ["apply", "-f", "-"]) { env = Just env }) (toString (s3ConfigSecretYaml namespace seaweedFsMiniBaseName s3Options))+        >>= waitForProcess >>= (`shouldBe` ExitSuccess)++    info [i|------------------ Creating SeaweedFS (mini) deployment ------------------|]+    timeAction "Apply SeaweedFS mini manifests" $+      createProcessWithFileLoggingAndStdin' "seaweedfs-mini-apply" ((proc kubectlBinary ["apply", "-f", "-"]) { env = Just env }) (toString (miniManifestsYaml namespace imageName options))+        >>= waitForProcess >>= (`shouldBe` ExitSuccess)++    timeAction "Wait for SeaweedFS mini deployment" $ do+      info [i|Waiting for the SeaweedFS (mini) deployment to be ready|]+      retryKubectl kubectlBinary env "seaweedfs-mini-wait"+        ["rollout", "status", "-n", toString namespace, toString ([i|deployment/#{seaweedFsMiniBaseName}-mini|] :: Text), "--timeout=300s"]++    case seaweedFsMiniCsiDriver of+      Nothing -> do+        info [i|Skipping SeaweedFS CSI driver installation|]+        pure Nothing+      Just csiOptions -> timeAction "Install CSI driver" $ do+        info [i|------------------ Preloading SeaweedFS CSI driver images ------------------|]+        forM_ (seaweedFsCsiDriverImages csiOptions) $ \spec -> do+          loaded <- loadImage' kcc spec+          info [i|Preloaded CSI image: #{loaded}|]+        info [i|------------------ Installing SeaweedFS CSI driver ------------------|]+        installSeaweedFsCsiDriver nixContextNixBinary nixContextNixpkgsDerivation kubectlBinary env namespace seaweedFsMiniBaseName csiOptions+        pure (Just seaweedFsStorageClassName)++  -- Map the mini options onto a 'SeaweedFSOptions' for the context's @seaweedFsOptions@ field, so a+  -- consumer reading the base name / S3 credentials / CSI setting off the context works the same as+  -- with the operator-based 'withSeaweedFS'. The mini pod runs no JWT security.toml, so both filer+  -- JWT keys are 'Nothing'.+  let equivalentOptions = defaultSeaweedFSOptions {+        seaweedFsImage = seaweedFsMiniImage+        , seaweedFsBaseName = seaweedFsMiniBaseName+        , seaweedFsMasterReplicas = 1+        , seaweedFsFilerReplicas = 1+        , seaweedFsVolumeReplicas = 1+        , seaweedFsServerExtraArgs = seaweedFsMiniExtraArgs+        , seaweedFsVolumeSizeLimitMb = seaweedFsMiniVolumeSizeLimitMb+        , seaweedFsS3 = seaweedFsMiniS3+        , seaweedFsCsiDriver = seaweedFsMiniCsiDriver+        }++  action $ SeaweedFSContext {+    seaweedFsOptions = equivalentOptions+    , seaweedFsCsiStorageClass = storageClass+    , seaweedFsFilerJwtWriteKey = Nothing+    , seaweedFsFilerJwtReadKey = Nothing+    }+++-- | Manifests for the single-pod SeaweedFS: an all-in-one @Deployment@ running @weed server@, plus+-- @master@\/@filer@\/@s3@ Services selecting it (named to match the operator-based deployment). Data+-- lives on an @emptyDir@ -- fine for ephemeral tests, and it means no PVC provisioning to wait on.+miniManifestsYaml :: Text -> Text -> SeaweedFSMiniOptions -> Text+miniManifestsYaml namespace imageName (SeaweedFSMiniOptions {..}) =+  T.intercalate "\n---\n" (deployment : services)+ where+  appLabel = seaweedFsMiniBaseName <> "-mini"+  s3Enabled = isJust seaweedFsMiniS3++  -- @weed server@ runs master + volume by default; @-filer@ adds the filer, @-s3@ the S3 gateway.+  args :: [Text]+  args = ["server", "-dir=/data", [i|-master.volumeSizeLimitMB=#{seaweedFsMiniVolumeSizeLimitMb}|], "-filer"]+         <> (if s3Enabled then ["-s3", "-s3.config=/etc/seaweedfs/s3/config.json"] else [])+         <> seaweedFsMiniExtraArgs+  argsYaml = "[" <> T.intercalate ", " ["\"" <> a <> "\"" | a <- args] <> "]"++  readinessCheck :: Text+  readinessCheck = if s3Enabled then "tcpSocket: { port: 8333 }" else "httpGet: { path: /, port: 8888 }"++  s3PortLine, s3VolumeMount, s3Volume :: Text+  s3PortLine = if s3Enabled then "\n        - { containerPort: 8333 }" else ""+  s3VolumeMount = if s3Enabled then "\n        - name: s3-config\n          mountPath: /etc/seaweedfs/s3\n          readOnly: true" else ""+  s3Volume = if s3Enabled then "\n      - name: s3-config\n        secret:\n          secretName: " <> seaweedFsMiniBaseName <> "-s3-config" else ""++  deployment = [__i|apiVersion: apps/v1+                    kind: Deployment+                    metadata:+                      name: #{appLabel}+                      namespace: #{namespace}+                      labels:+                        app: #{appLabel}+                    spec:+                      replicas: 1+                      selector:+                        matchLabels:+                          app: #{appLabel}+                      template:+                        metadata:+                          labels:+                            app: #{appLabel}+                        spec:+                          containers:+                          - name: seaweedfs+                            image: #{imageName}+                            command: ["weed"]+                            args: #{argsYaml}+                            ports:+                            - { containerPort: 9333 }+                            - { containerPort: 19333 }+                            - { containerPort: 8080 }+                            - { containerPort: 18080 }+                            - { containerPort: 8888 }+                            - { containerPort: 18888 }#{s3PortLine}+                            readinessProbe:+                              #{readinessCheck}+                              initialDelaySeconds: 2+                              periodSeconds: 2+                            volumeMounts:+                            - name: data+                              mountPath: /data#{s3VolumeMount}+                          volumes:+                          - name: data+                            emptyDir: {}#{s3Volume}|]++  -- @<baseName>-filer@ exposes both the filer HTTP (8888) and gRPC (18888) ports; the CSI driver+  -- (see 'installSeaweedFsCsiDriver') resolves this Service by that exact name.+  services = [+      svc (seaweedFsMiniBaseName <> "-master") (portItem "master-http" 9333 <> portItem "master-grpc" 19333)+    , svc (seaweedFsMiniBaseName <> "-filer") (portItem "filer-http" 8888 <> portItem "filer-grpc" 18888)+    ] <> [svc (seaweedFsMiniBaseName <> "-s3") (portItem "s3" 8333) | s3Enabled]++  portItem :: Text -> Int -> Text+  portItem name port = "\n  - { name: " <> name <> ", port: " <> show port <> ", targetPort: " <> show port <> " }"++  svc :: Text -> Text -> Text+  svc name ports = [__i|apiVersion: v1+                        kind: Service+                        metadata:+                          name: #{name}+                          namespace: #{namespace}+                        spec:+                          selector:+                            app: #{appLabel}+                          ports:#{ports}|]
lib/Test/Sandwich/Contexts/Kubernetes/Types.hs view
@@ -11,6 +11,7 @@  import Control.Monad.IO.Unlift import Control.Monad.Logger+import qualified Data.List as L import Kubernetes.OpenAPI.Core as Kubernetes import Network.HTTP.Client import Relude@@ -18,8 +19,23 @@ import Test.Sandwich.Contexts.Files import Test.Sandwich.Contexts.Nix import qualified Text.Show+import UnliftIO.Environment (getEnvironment)  +-- | Append extra environment variables over a base environment, with the extras superseding any+-- base entry of the same name (and later duplicates within either list dropped). This is the+-- list-at-a-time analogue of an @addOrReplace@ over an association list.+addOrReplaceEnv :: [(String, String)] -> [(String, String)] -> [(String, String)]+addOrReplaceEnv extra base = L.nubBy ((==) `on` fst) (extra <> base)++-- | Build the @env@ for a subprocess by appending the given extra variables over the current ambient+-- environment. Returns 'Nothing' when there are no extras, so callers pass @env = Nothing@ and inherit+-- the environment unchanged (behaviour identical to not touching @env@ at all).+minikubeProcEnv :: MonadIO m => [(String, String)] -> m (Maybe [(String, String)])+minikubeProcEnv [] = pure Nothing+minikubeProcEnv extra = Just . addOrReplaceEnv extra <$> getEnvironment++ instance Show Manager where   show _ = "<HTTP manager>" @@ -34,6 +50,13 @@   | KubernetesClusterMinikube { kubernetesClusterTypeMinikubeBinary :: FilePath                               , kubernetesClusterTypeMinikubeProfileName :: Text                               , kubernetesClusterTypeMinikubeFlags :: [Text]+                              -- | Extra environment variables to add to every @minikube@ invocation+                              -- for this cluster (image loads, service forwards, @ssh@, delete).+                              -- These are appended over the ambient process environment at call time,+                              -- superseding any ambient variable of the same name (see 'addOrReplaceEnv').+                              -- Use this to scope e.g. @MINIKUBE_HOME@ to a single cluster without+                              -- mutating the global process environment.+                              , kubernetesClusterTypeMinikubeExtraEnvironment :: [(String, String)]                               }   deriving (Show, Eq) 
+ lib/Test/Sandwich/Contexts/Kubernetes/Util/KubectlTop.hs view
@@ -0,0 +1,76 @@+{-|++Helpers for @kubectl top pods@ output and namespace selection, shared by the+resource watcher ("Test.Sandwich.Contexts.Kubernetes.ResourceWatcher") and the OOM+watcher ("Test.Sandwich.Contexts.Kubernetes.OOMWatcher").++-}++module Test.Sandwich.Contexts.Kubernetes.Util.KubectlTop (+  namespaceArgs+  , scopeLabel+  , parseTop+  , parseCpu+  , parseMem+  ) where++import Data.String.Interpolate+import qualified Data.Text as T+import Relude+++-- | @kubectl@ args selecting a namespace, or all namespaces when 'Nothing'.+namespaceArgs :: Maybe Text -> [String]+namespaceArgs = maybe ["--all-namespaces"] (\ns -> ["-n", toString ns])++-- | Human-readable description of a watched namespace scope, for log lines and+-- failure messages.+scopeLabel :: Maybe Text -> Text+scopeLabel = maybe "all namespaces" (\ns -> [i|namespace '#{ns}'|])++-- | Parse @kubectl top pods --no-headers@ output into @(key, cpuMillicores,+-- memoryBytes)@ triples. The last two columns are always CPU and memory; every+-- leading column is part of the identifier, joined with @\/@. This handles all+-- shapes without extra flags:+--+--   * @pod@                              (default)+--   * @pod\/container@                   (@--containers@)+--   * @namespace\/pod@                   (@--all-namespaces@)+--   * @namespace\/pod\/container@        (@--all-namespaces --containers@)+--+-- Rows whose CPU or memory column doesn't parse are dropped. @kubectl top@ prints+-- @\<unknown\>@ for both while metrics-server is still warming up (and sometimes for+-- an individual pod), and we'd rather skip those than record bogus zero samples.+parseTop :: Text -> [(Text, Integer, Integer)]+parseTop = mapMaybe parseLine . lines+  where+    parseLine l = case reverse (words l) of+      (mem : cpu : ident@(_ : _)) ->+        (T.intercalate "/" (reverse ident),,) <$> parseCpu cpu <*> parseMem mem+      _ -> Nothing++-- | Parse a kubectl CPU quantity (e.g. @12m@, @1@) into millicores, or 'Nothing'+-- if it doesn't look like a CPU quantity (e.g. @\<unknown\>@).+parseCpu :: Text -> Maybe Integer+parseCpu t = case T.stripSuffix "m" t of+  Just n -> readMaybe (toString n)+  Nothing -> (\d -> round (d * 1000)) <$> (readMaybe (toString t) :: Maybe Double)++-- | Parse a kubectl memory quantity (e.g. @345Mi@, @1Gi@, @512Ki@) into bytes, or+-- 'Nothing' if it doesn't look like a memory quantity (e.g. @\<unknown\>@).+parseMem :: Text -> Maybe Integer+parseMem t = asum [+  parseWith "Ki" 1024+  , parseWith "Mi" (1024 * 1024)+  , parseWith "Gi" (1024 * 1024 * 1024)+  , parseWith "Ti" (1024 * 1024 * 1024 * 1024)+  , parseWith "k" 1000+  , parseWith "M" 1000000+  , parseWith "G" 1000000000+  , readMaybe (toString t)  -- plain bytes+  ]+  where+    parseWith suf mult = do+      n <- T.stripSuffix suf t+      d <- readMaybe (toString n) :: Maybe Double+      Just (round (d * mult))
+ lib/Test/Sandwich/Contexts/Kubernetes/Util/SeriesPlot.hs view
@@ -0,0 +1,105 @@+{-# LANGUAGE QuasiQuotes #-}++{-|++Render a simple, dependency-free SVG line chart of per-pod time series. Used by+the resource watcher (see "Test.Sandwich.Contexts.Kubernetes.ResourceWatcher") to+plot per-pod CPU and memory over time.++-}++module Test.Sandwich.Contexts.Kubernetes.Util.SeriesPlot (+  renderSeriesSvg+  ) where++import qualified Data.Map as M+import Data.String.Interpolate+import qualified Data.Text as T+import Relude+++-- | Render an SVG line chart. The input maps each series name (e.g. a pod) to a+-- time series of @(elapsedSeconds, value)@ samples, where @value@ is already in+-- the desired display units. One colored polyline is drawn per series, with axes+-- and a legend. Returns the SVG document as 'Text'.+renderSeriesSvg ::+  -- | Chart title (include the unit, e.g. @"Pod memory usage over time (MiB)"@)+  Text+  -- | Message to show when no samples were collected+  -> Text+  -- | @seriesName -> [(elapsedSeconds, value)]@+  -> Map Text [(Double, Double)]+  -> Text+renderSeriesSvg title emptyMessage samples+  | M.null nonEmptySeries = emptySvg+  | otherwise = svg+  where+    nonEmptySeries = M.filter (not . null) samples++    series :: [(Text, [(Double, Double)])] -- (name, [(t, value)])+    series = [ (name, sortOn fst pts) | (name, pts) <- M.toList nonEmptySeries ]++    allTs = [t | (_, pts) <- series, (t, _) <- pts]+    allMs = [m | (_, pts) <- series, (_, m) <- pts]+    maxT = let x = foldl' max 0 allTs in if x <= 0 then 1 else x+    maxM = let x = foldl' max 0 allMs in if x <= 0 then 1 else x++    -- Layout+    width, height, left, right, top, bottom :: Double+    width = 960; height = 540+    left = 70; right = 230; top = 30; bottom = 50+    plotW = width - left - right+    plotH = height - top - bottom++    sx t = left + (t / maxT) * plotW+    sy m = top + plotH - (m / maxM) * plotH++    px :: Double -> Text+    px v = show (round v :: Int)++    palette :: [Text]+    palette = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd"+              , "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"]+    colorFor n = fromMaybe "#000000" (palette !!? (n `mod` length palette))++    -- Horizontal gridlines + y labels+    gridDivs = 4 :: Int+    gridlines = T.concat [ let frac = fromIntegral k / fromIntegral gridDivs+                               y = top + plotH - frac * plotH+                               label = round (frac * maxM) :: Int+                           in [i|<line x1="#{px left}" y1="#{px y}" x2="#{px (left + plotW)}" y2="#{px y}" stroke="\#eee" />+<text x="#{px (left - 8)}" y="#{px (y + 4)}" text-anchor="end" font-size="11" fill="\#555">#{label}</text>+|]+                         | k <- [0 .. gridDivs] ]++    -- X axis ticks at 0, mid, max+    xticks = T.concat [ let x = sx t+                        in [i|<text x="#{px x}" y="#{px (top + plotH + 18)}" text-anchor="middle" font-size="11" fill="\#555">#{round t :: Int}s</text>+|]+                      | t <- [0, maxT / 2, maxT] ]++    polylines = T.concat [ let pts = T.intercalate " " [[i|#{px (sx t)},#{px (sy m)}|] | (t, m) <- ser]+                           in [i|<polyline fill="none" stroke="#{colorFor idx}" stroke-width="1.5" points="#{pts}" />+|]+                         | (idx, (_name, ser)) <- zip [0 ..] series ]++    legend = T.concat [ let y = top + 6 + fromIntegral idx * 18+                            nm = T.take 38 name+                        in [i|<rect x="#{px (left + plotW + 16)}" y="#{px (y - 9)}" width="11" height="11" fill="#{colorFor idx}" />+<text x="#{px (left + plotW + 32)}" y="#{px y}" font-size="11" fill="\#333">#{nm}</text>+|]+                      | (idx, (name, _)) <- zip [0 :: Int ..] series ]++    svg = [i|<svg xmlns="http://www.w3.org/2000/svg" width="#{px width}" height="#{px height}" font-family="sans-serif">+<rect width="100%" height="100%" fill="white" />+<text x="#{px left}" y="18" font-size="14" fill="\#222">#{title}</text>+#{gridlines}<line x1="#{px left}" y1="#{px top}" x2="#{px left}" y2="#{px (top + plotH)}" stroke="\#999" />+<line x1="#{px left}" y1="#{px (top + plotH)}" x2="#{px (left + plotW)}" y2="#{px (top + plotH)}" stroke="\#999" />+#{xticks}#{polylines}#{legend}</svg>+|]++    emptySvg = [i|<svg xmlns="http://www.w3.org/2000/svg" width="480" height="80" font-family="sans-serif">+<rect width="100%" height="100%" fill="white" />+<text x="12" y="44" font-size="14" fill="\#555">#{emptyMessage}</text>+</svg>+|]
sandwich-contexts-kubernetes.cabal view
@@ -5,14 +5,18 @@ -- see: https://github.com/sol/hpack  name:           sandwich-contexts-kubernetes-version:        0.1.3.0+version:        0.2.0.0 synopsis:       Sandwich test contexts for Kubernetes-description:    Please see README.md+description:    Contexts for creating Kubernetes clusters (kind or Minikube) in Sandwich tests, and for running services on them such as MinIO, SeaweedFS, Postgres and Typesense. Please see the <https://codedownio.github.io/sandwich/docs/context-libraries/sandwich-contexts-kubernetes/ documentation>.+category:       Testing author:         Tom McLaughlin maintainer:     tom@codedown.io-copyright:      2025 Tom McLaughlin+copyright:      2026 Tom McLaughlin license:        BSD3+license-file:   LICENSE build-type:     Simple+extra-source-files:+    CHANGELOG.md  library   exposed-modules:@@ -20,12 +24,16 @@       Test.Sandwich.Contexts.Kubernetes.Images       Test.Sandwich.Contexts.Kubernetes.KataContainers       Test.Sandwich.Contexts.Kubernetes.KindCluster+      Test.Sandwich.Contexts.Kubernetes.MetricsServer       Test.Sandwich.Contexts.Kubernetes.MinikubeCluster       Test.Sandwich.Contexts.Kubernetes.MinioOperator       Test.Sandwich.Contexts.Kubernetes.MinioS3Server       Test.Sandwich.Contexts.Kubernetes.Namespace+      Test.Sandwich.Contexts.Kubernetes.OOMWatcher       Test.Sandwich.Contexts.Kubernetes.PostgresServer+      Test.Sandwich.Contexts.Kubernetes.ResourceWatcher       Test.Sandwich.Contexts.Kubernetes.SeaweedFS+      Test.Sandwich.Contexts.Kubernetes.SeaweedFSMini       Test.Sandwich.Contexts.Kubernetes.Typesense   other-modules:       Test.Sandwich.Contexts.Kubernetes.FindImages@@ -43,6 +51,7 @@       Test.Sandwich.Contexts.Kubernetes.Longhorn       Test.Sandwich.Contexts.Kubernetes.MinikubeCluster.Forwards       Test.Sandwich.Contexts.Kubernetes.MinikubeCluster.Images+      Test.Sandwich.Contexts.Kubernetes.MinikubeCluster.Remove       Test.Sandwich.Contexts.Kubernetes.MinioS3Server.Parsing       Test.Sandwich.Contexts.Kubernetes.Run       Test.Sandwich.Contexts.Kubernetes.Types@@ -50,8 +59,10 @@       Test.Sandwich.Contexts.Kubernetes.Util.Container       Test.Sandwich.Contexts.Kubernetes.Util.Exception       Test.Sandwich.Contexts.Kubernetes.Util.Images+      Test.Sandwich.Contexts.Kubernetes.Util.KubectlTop       Test.Sandwich.Contexts.Kubernetes.Util.Nix       Test.Sandwich.Contexts.Kubernetes.Util.Ports+      Test.Sandwich.Contexts.Kubernetes.Util.SeriesPlot       Test.Sandwich.Contexts.Kubernetes.Util.SocketUtil       Test.Sandwich.Contexts.Kubernetes.Util.UUID       Test.Sandwich.Contexts.Kubernetes.Waits@@ -95,11 +106,13 @@     , retry     , safe     , sandwich >=0.3.1.0-    , sandwich-contexts+    , sandwich-contexts >=0.3.1.0     , sandwich-contexts-minio     , string-interpolate     , temporary     , text+    , time+    , toml-parser     , unliftio     , unliftio-core     , vector