beads/internal/testutil/testdoltserver.go
Julian Knutsen 671715bb8b
test(testutil): opt-in local dolt sql-server backend for Dolt-backed tests (#6891)
* test(testutil): local dolt sql-server backend behind the Dolt test server API

Add a second backend to internal/testutil behind the unchanged container
API (EnsureDoltContainerForTestMain, RequireDoltContainer,
StartIsolatedDoltContainer[Handle], NewContainerProvider,
RestartSharedDoltContainer, DoltContainerCrashed, IsolatedDoltContainer
Stop/Start/CurrentPort/Exec): the test process spawns `dolt sql-server`
from the pinned dolt CLI instead of a dolthub/dolt-sql-server container.

- BEADS_TEST_DOLT_SERVER=local|container selects it; unset keeps plain
  `go test` on the container (no behavior change) and makes `bazel test`
  use the local backend. Other values fail instead of guessing.
- The CLI (BEADS_TEST_DOLT_BINARY, else PATH) must be the image's version.
- Provisioned like testcontainers' dolt module: root@% (DOLT_ROOT_HOST=%),
  database beads_test, user test/test. Clean env, TZ=UTC, GOMAXPROCS=4,
  own dolt global config with metrics and the version check disabled.
- Loopback port picked here (dolt rejects -P 0), never 3307, retried when
  another process wins the port; readiness requires the server's own
  "Server ready" line plus a bounded ping, so a foreign listener on a
  contested port cannot pass for it.
- State lives under the TMPDIR captured at package init, outside every
  PinSuiteTempRoot root, so suite leak sweeps never see it. The server
  stays in the test's process group (bazel's group kill reaps it) with
  Pdeathsig on Linux.
- BEADS_TEST_REQUIRE_DOLT_CONTAINER=1 now also makes every TestMain that
  only warned about an unavailable server exit 1
  (DoltUnavailableForTestMain), plus the shared proxied harness.
- dolt_benchmark_purge_test finds .dolt_dropped_databases relative to
  Exec's working directory (the data dir in both backends).
- TestDoltServerFingerprint checks each available backend against one
  checked-in fingerprint (users, grants, databases, server variables);
  local-backend tests cover the bind-race retry, 3307, crash detection,
  Stop/Start, Exec cwd, state outside the suite root, and teardown.
- Bazel: the requires-docker variants pin BEADS_TEST_DOLT_SERVER=container
  so the docker lane stays the container A/B control; the test wrapper's
  dolt global config disables metrics and the version check.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(testutil): select the local Dolt test server only when asked for

Under Bazel an unset BEADS_TEST_DOLT_SERVER used to mean the local
backend, so every non-ci `bazel test` started servers for Dolt suites no
lane runs with one (//internal/storage/dolt:dolt_test went from a 16 s
skip to a timeout). Unset now means container everywhere: in a Bazel
action without docker that is the pre-existing warn+skip, and only a
target's env or --test_env=BEADS_TEST_DOLT_SERVER=local starts local
servers. Plain `go test` is unchanged.

The docker variants keep their container pin: a rule env beats
--test_env, so a local-backend invocation cannot flip the docker lane.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(testutil): harden the local Dolt test server's host footprint

- DOLT_DISABLE_EVENT_FLUSH=1 for every dolt the backend runs (and in the
  Bazel test wrapper): the metrics/versioncheck keys stop network calls
  but not the detached `dolt send-metrics` child each command forks on
  exit, which re-created the version probe's removed HOME (one leaked
  bdt-doltver-* per test process) and raced terminate's RemoveAll.
- Every bdt-dolt-*/bdt-doltver-* root records its owner PID, and the
  first use of the backend in a process removes this user's roots whose
  owner is dead (the SweepDeadSuiteRoots rule; a copy, since doltserver's
  tests import testutil). A panicking, timed-out or killed test binary,
  or a package whose TestMain never terminates the singleton, no longer
  leaks a 40-100 MB state dir per run.
- secure_file_priv is the state root's sfp/ directory, set through a
  per-launch --config file (dolt ignores other flags with --config): a
  local server runs as the test user on the host with a passwordless
  root@%, so LOAD_FILE / INTO OUTFILE must not reach the user's files.
  The fingerprint treats that path as the container's "".
- Fingerprint: character_set_server, collation_server,
  max_allowed_packet, transaction_isolation, lower_case_table_names,
  lower_case_file_system (compared on Linux only: APFS reports ON),
  wait_timeout, innodb_lock_wait_timeout.
- The local backend's own tests skip off Linux (no Pdeathsig, so a
  killed test binary would orphan servers on the macOS runners) unless
  BEADS_TEST_DOLT_SERVER=local asks for them.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* ci: compare the container and local Dolt test servers in the domain+uow job

TestDoltServerFingerprint's container half never ran in CI: only the
test-domain-uow job has both the pulled image and the pinned dolt CLI,
and it never ran ./internal/testutil. Run the fingerprint there (with
BEADS_TEST_REQUIRE_DOLT_CONTAINER=1 so the container half cannot skip)
so an image bump that drifts the container side fails in the PR.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 04:06:49 -07:00

594 lines
19 KiB
Go

//go:build !windows
package testutil
import (
"context"
"database/sql"
"fmt"
"io"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"testing"
"time"
_ "github.com/go-sql-driver/mysql" // required by testcontainers Dolt module
"github.com/testcontainers/testcontainers-go"
tcexec "github.com/testcontainers/testcontainers-go/exec"
"github.com/testcontainers/testcontainers-go/modules/dolt"
)
// doltServer represents a running test Dolt container instance.
type doltServer struct {
container *dolt.DoltContainer
local *localDoltServer // set instead of container by the local backend
}
// serverStartTimeout is the max time to wait for the test Dolt server to accept connections.
const serverStartTimeout = 60 * time.Second
// Module-level singleton state.
var (
doltServerOnce sync.Once
doltServerMu sync.Mutex
doltServerErr error
doltTestPort string
doltSingletonSrv *doltServer
doltTerminateOnce sync.Once
dockerOnce sync.Once
dockerAvail bool
doltCheckOnce sync.Once
doltCached doltReadiness
)
// doltReadiness describes why Dolt integration tests can or cannot run.
type doltReadiness int
// doltDockerRepo is the repository portion of DoltDockerImage (without the tag).
var doltDockerRepo, _, _ = strings.Cut(DoltDockerImage, ":")
const (
doltNoDocker doltReadiness = iota // Docker daemon not reachable
doltNoImage // no Dolt image at all
doltWrongVersion // image exists but wrong tag
doltSkipped // explicit opt-out via BEADS_TEST_SKIP
doltReady // ready to start containers
doltNoLocalCLI // local backend: pinned dolt CLI missing or wrong version, or a bad backend name
)
// doltLocalCLIErr explains doltNoLocalCLI.
var doltLocalCLIErr error
func (d doltReadiness) String() string {
switch d {
case doltNoDocker:
return "Docker not available"
case doltNoImage:
return fmt.Sprintf("Docker image %s not cached locally (run 'docker pull %s')", DoltDockerImage, DoltDockerImage)
case doltWrongVersion:
return fmt.Sprintf("Docker image %s cached but wrong version (run 'docker pull %s')", doltDockerRepo, DoltDockerImage)
case doltSkipped:
return "Dolt tests skipped (BEADS_TEST_SKIP=dolt)"
case doltReady:
return "Dolt ready"
case doltNoLocalCLI:
return fmt.Sprintf("local Dolt test server backend unavailable: %v", doltLocalCLIErr)
default:
return fmt.Sprintf("unknown dolt readiness state: %d", int(d))
}
}
// isDockerAvailable returns true if the Docker daemon is reachable.
// The result is cached after the first call.
func isDockerAvailable() bool {
dockerOnce.Do(func() {
dockerAvail = exec.Command("docker", "info").Run() == nil
})
return dockerAvail
}
// hasTestSkip returns true if the given service appears in the BEADS_TEST_SKIP
// env var (comma-separated list). Example: BEADS_TEST_SKIP=dolt,slow
func hasTestSkip(service string) bool {
val := os.Getenv("BEADS_TEST_SKIP")
if val == "" {
return false
}
for _, s := range strings.Split(val, ",") {
if strings.TrimSpace(s) == service {
return true
}
}
return false
}
func skipOrFailDoltUnavailable(t *testing.T, state doltReadiness) {
t.Helper()
if os.Getenv(EnvRequireDoltContainer) == "1" {
t.Fatalf("Dolt test container unavailable (%s) but %s=1; this lane must not skip", state, EnvRequireDoltContainer)
}
t.Skipf("skipping test: %s", state)
}
// checkDolt returns the readiness state for Dolt integration tests.
// It composes hasTestSkip, isDockerAvailable, isDoltImageCached, and
// isDoltRepoImageCached, caching the result.
func checkDolt() doltReadiness {
doltCheckOnce.Do(func() {
// Explicit skip checked first to avoid ~1s docker info cost.
if hasTestSkip("dolt") {
doltCached = doltSkipped
return
}
if err := doltBackendErr(); err != nil {
doltLocalCLIErr = err
doltCached = doltNoLocalCLI
return
}
if useLocalDoltServer() {
if _, err := resolveLocalDoltBinary(); err != nil {
doltLocalCLIErr = err
doltCached = doltNoLocalCLI
return
}
doltCached = doltReady
return
}
if !isDockerAvailable() {
return // doltCached zero value is doltNoDocker
}
if isDoltImageCached() {
doltCached = doltReady
return
}
if isDoltRepoImageCached() {
doltCached = doltWrongVersion
return
}
doltCached = doltNoImage
})
return doltCached
}
// isDoltImageCached returns true if the exact Dolt Docker image (repo:tag)
// is available locally, avoiding unnecessary network calls to Docker Hub.
func isDoltImageCached() bool {
return exec.Command("docker", "image", "inspect", DoltDockerImage).Run() == nil
}
// isDoltRepoImageCached returns true if ANY version of the Dolt image repo
// exists locally (e.g. dolthub/dolt-sql-server with a different tag).
func isDoltRepoImageCached() bool {
out, err := exec.Command("docker", "images", doltDockerRepo, "-q").Output()
return err == nil && len(strings.TrimSpace(string(out))) > 0
}
// startDoltContainer starts the singleton Dolt container.
func startDoltContainer() error {
if useLocalDoltServer() {
s, err := startLocalDoltServer()
if err != nil {
return fmt.Errorf("starting local Dolt server: %w", err)
}
doltTestPort = strconv.Itoa(s.Port())
doltSingletonSrv = &doltServer{local: s}
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), serverStartTimeout)
defer cancel()
ctr, err := dolt.Run(ctx, DoltDockerImage,
dolt.WithDatabase("beads_test"),
// Docker port-forwarding makes connections appear as non-localhost
// (e.g., 172.17.0.1). The entrypoint defaults DOLT_ROOT_HOST to
// "localhost", so root@localhost won't match external connections.
// Set to "%" so root can connect from any host.
testcontainers.WithEnv(map[string]string{"DOLT_ROOT_HOST": "%"}),
)
if err != nil {
return fmt.Errorf("starting Dolt container: %w", err)
}
p, err := ctr.MappedPort(ctx, "3306/tcp")
if err != nil {
_ = testcontainers.TerminateContainer(ctr)
return fmt.Errorf("getting mapped port: %w", err)
}
if _, err := strconv.Atoi(p.Port()); err != nil {
_ = testcontainers.TerminateContainer(ctr)
return fmt.Errorf("parsing port %q: %w", p.Port(), err)
}
doltTestPort = p.Port()
if err := waitForDoltReady(doltTestPort); err != nil {
_ = testcontainers.TerminateContainer(ctr)
return fmt.Errorf("waiting for Dolt server to be query-ready: %w", err)
}
doltSingletonSrv = &doltServer{
container: ctr,
}
return nil
}
// doltReadyProbeTimeout bounds how long waitForDoltReady polls before giving up.
const doltReadyProbeTimeout = 30 * time.Second
// waitForDoltReady polls the server with a trivial query until it responds
// or doltReadyProbeTimeout elapses.
//
// The testcontainers wait strategy above only matches a log line ("Server
// ready. Accepting connections."), which confirms the TCP listener is up but
// not that Dolt's SQL engine can actually serve a query yet. In that narrow
// startup window, a query issued with an unbounded context (as several test
// helpers do) can block indefinitely instead of erroring, because nothing
// ever cancels it to unstick the read — confirmed via goroutine dump during
// be-fgd round-2 triage: the connection sat in mysqlConn.readWithTimeout /
// net.Read for 2+ minutes after the container had already logged ready. Each
// probe attempt here uses its own short bounded context, so a still-warming
// server fails an attempt fast and gets retried, rather than wedging.
func waitForDoltReady(port string) error {
dsn := fmt.Sprintf("root@tcp(127.0.0.1:%s)/", port)
deadline := time.Now().Add(doltReadyProbeTimeout)
var lastErr error
for {
lastErr = pingDoltOnce(dsn)
if lastErr == nil {
return nil
}
if time.Now().After(deadline) {
return fmt.Errorf("dolt server at port %s did not become query-ready within %s: %w", port, doltReadyProbeTimeout, lastErr)
}
time.Sleep(200 * time.Millisecond)
}
}
// pingDoltOnce opens a short-lived connection and pings it with a bounded
// context so a non-responsive server fails this attempt instead of hanging.
func pingDoltOnce(dsn string) error {
db, err := sql.Open("mysql", dsn)
if err != nil {
return err
}
defer db.Close()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
return db.PingContext(ctx)
}
// terminateSharedContainer stops and removes the shared Dolt container.
// Safe to call concurrently or multiple times (sync.Once).
func terminateSharedContainer() {
doltTerminateOnce.Do(func() {
doltServerMu.Lock()
defer doltServerMu.Unlock()
stopSharedContainerLocked()
})
}
// stopSharedContainerLocked drops the current singleton container. The caller
// holds doltServerMu. It does not consume doltTerminateOnce, so a later
// replacement can still be removed by TerminateDoltContainer.
func stopSharedContainerLocked() {
if doltSingletonSrv != nil && doltSingletonSrv.local != nil {
doltSingletonSrv.local.terminate()
doltSingletonSrv.local = nil
}
if doltSingletonSrv != nil && doltSingletonSrv.container != nil {
_ = testcontainers.TerminateContainer(doltSingletonSrv.container)
doltSingletonSrv.container = nil
}
doltSingletonSrv = nil
}
// RestartSharedDoltContainer replaces the shared test container with a new
// one and returns its host port. A package that keeps one container for the
// whole TestMain (tracker, and the same shape elsewhere) otherwise turns a
// single server death into a failure for every later test: each dial reports
// "Dolt server unreachable" and the job goes red dozens of times. The
// replacement is empty; the caller re-creates its shared database.
func RestartSharedDoltContainer() (int, error) {
if state := checkDolt(); state != doltReady {
return 0, fmt.Errorf("%s", state)
}
doltServerMu.Lock()
defer doltServerMu.Unlock()
stopSharedContainerLocked()
if err := startDoltContainer(); err != nil {
doltServerErr = err
return 0, err
}
if err := os.Setenv("BEADS_DOLT_PORT", doltTestPort); err != nil {
doltServerErr = fmt.Errorf("set BEADS_DOLT_PORT: %w", err)
return 0, doltServerErr
}
if err := os.Setenv("BEADS_DOLT_SERVER_PORT", doltTestPort); err != nil {
doltServerErr = fmt.Errorf("set BEADS_DOLT_SERVER_PORT: %w", err)
return 0, doltServerErr
}
doltServerErr = nil
return DoltContainerPortInt(), nil
}
// ServerUnreachable reports whether err is a shared Dolt server that is gone,
// as opposed to a query the server refused. Connection refused and the
// "Dolt server unreachable" dial error are the shapes left behind when the
// singleton container exits; unexpected EOF is the MySQL driver watching that
// exit mid-handshake.
func ServerUnreachable(err error) bool {
if err == nil {
return false
}
if DoltContainerCrashed() {
return true
}
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "connection refused") ||
strings.Contains(msg, "dolt server unreachable") ||
strings.Contains(msg, "unexpected eof")
}
// IsolatedDoltContainer is a per-test Dolt container together with the
// accessors a test needs to inspect it from the inside.
type IsolatedDoltContainer struct {
// Port is the mapped host port of the container's Dolt server.
Port string
ctr *dolt.DoltContainer
local *localDoltServer // local backend instead of ctr
}
// Stop pauses the container while retaining its data volume.
func (c *IsolatedDoltContainer) Stop(ctx context.Context) error {
if c != nil && c.local != nil {
return c.local.stop()
}
if c == nil || c.ctr == nil {
return fmt.Errorf("no Dolt container running")
}
return c.ctr.Stop(ctx, nil)
}
// Start resumes a container previously stopped with Stop.
func (c *IsolatedDoltContainer) Start(ctx context.Context) error {
if c != nil && c.local != nil {
return c.local.restart()
}
if c == nil || c.ctr == nil {
return fmt.Errorf("no Dolt container running")
}
return c.ctr.Start(ctx)
}
// CurrentPort returns the container's currently mapped SQL port. Container
// runtimes may assign a new host port after Stop/Start.
func (c *IsolatedDoltContainer) CurrentPort(ctx context.Context) (string, error) {
if c != nil && c.local != nil {
return strconv.Itoa(c.local.Port()), nil
}
if c == nil || c.ctr == nil {
return "", fmt.Errorf("no Dolt container running")
}
p, err := c.ctr.MappedPort(ctx, "3306/tcp")
if err != nil {
return "", err
}
return p.Port(), nil
}
// Exec runs cmd inside the container and returns its exit code and combined
// output, demultiplexed (see containerExec). Its working directory is the
// server's data directory (the image's WORKDIR, /var/lib/dolt); with the local
// backend cmd runs on the host in the local server's data directory, so
// commands must address the data through relative paths.
func (c *IsolatedDoltContainer) Exec(ctx context.Context, cmd []string) (int, string, error) {
if c != nil && c.local != nil {
return c.local.execInDataDir(ctx, cmd)
}
if c == nil || c.ctr == nil {
return 0, "", fmt.Errorf("no Dolt container running")
}
return containerExec(ctx, c.ctr, cmd)
}
// StartIsolatedDoltContainerHandle starts a per-test Dolt container and
// returns a handle to it. The container is terminated automatically when the
// test finishes.
//
// Unlike StartIsolatedDoltContainer this does NOT touch BEADS_DOLT_PORT or
// BEADS_DOLT_SERVER_PORT: those are process-wide, so a test that only wants
// its own server should not perturb sibling tests sharing the process.
func StartIsolatedDoltContainerHandle(t *testing.T) *IsolatedDoltContainer {
t.Helper()
if state := checkDolt(); state != doltReady {
skipOrFailDoltUnavailable(t, state)
}
if useLocalDoltServer() {
return startIsolatedLocalDoltServer(t)
}
return startIsolatedDoltContainer(t)
}
// startIsolatedLocalDoltServer is StartIsolatedDoltContainerHandle for the
// local backend, without the readiness gate.
func startIsolatedLocalDoltServer(t *testing.T) *IsolatedDoltContainer {
t.Helper()
s, err := startLocalDoltServer()
if err != nil {
t.Fatalf("starting local Dolt server: %v", err)
}
t.Cleanup(s.terminate)
return &IsolatedDoltContainer{Port: strconv.Itoa(s.Port()), local: s}
}
// startIsolatedDoltContainer is StartIsolatedDoltContainerHandle for the
// container backend, without the readiness gate.
func startIsolatedDoltContainer(t *testing.T) *IsolatedDoltContainer {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), serverStartTimeout)
defer cancel()
ctr, err := dolt.Run(ctx, DoltDockerImage,
dolt.WithDatabase("beads_test"),
testcontainers.WithEnv(map[string]string{"DOLT_ROOT_HOST": "%"}),
)
if err != nil {
t.Fatalf("starting Dolt container: %v", err)
}
t.Cleanup(func() {
if err := testcontainers.TerminateContainer(ctr); err != nil {
t.Logf("terminating Dolt container: %v", err)
}
})
port, err := ctr.MappedPort(ctx, "3306/tcp")
if err != nil {
t.Fatalf("getting mapped port: %v", err)
}
return &IsolatedDoltContainer{Port: port.Port(), ctr: ctr}
}
// StartIsolatedDoltContainer starts a per-test Dolt container and returns the
// mapped host port, additionally pointing BEADS_DOLT_PORT and
// BEADS_DOLT_SERVER_PORT at it for the duration of the test.
func StartIsolatedDoltContainer(t *testing.T) string {
t.Helper()
c := StartIsolatedDoltContainerHandle(t)
t.Setenv("BEADS_DOLT_PORT", c.Port)
t.Setenv("BEADS_DOLT_SERVER_PORT", c.Port)
return c.Port
}
// ensureSharedContainer starts the singleton container and sets
// BEADS_DOLT_PORT and BEADS_DOLT_SERVER_PORT.
func ensureSharedContainer() {
doltServerOnce.Do(func() {
doltServerMu.Lock()
defer doltServerMu.Unlock()
doltServerErr = startDoltContainer()
if doltServerErr == nil && doltTestPort != "" {
if err := os.Setenv("BEADS_DOLT_PORT", doltTestPort); err != nil {
doltServerErr = fmt.Errorf("set BEADS_DOLT_PORT: %w", err)
} else if err := os.Setenv("BEADS_DOLT_SERVER_PORT", doltTestPort); err != nil {
doltServerErr = fmt.Errorf("set BEADS_DOLT_SERVER_PORT: %w", err)
}
}
})
}
// EnsureDoltContainerForTestMain starts a shared Dolt container for use in
// TestMain functions. Call TerminateDoltContainer() after m.Run() to clean up.
// Sets BEADS_DOLT_PORT and BEADS_DOLT_SERVER_PORT process-wide.
func EnsureDoltContainerForTestMain() error {
if state := checkDolt(); state != doltReady {
return fmt.Errorf("%s", state)
}
ensureSharedContainer()
return doltServerErr
}
// RequireDoltContainer ensures a shared Dolt container is running. Skips the
// test if Docker is not available.
func RequireDoltContainer(t *testing.T) {
t.Helper()
if state := checkDolt(); state != doltReady {
skipOrFailDoltUnavailable(t, state)
}
ensureSharedContainer()
if doltServerErr != nil {
t.Fatalf("Dolt container setup failed: %v", doltServerErr)
}
}
// DoltContainerAddr returns the address (host:port) of the Dolt container.
func DoltContainerAddr() string {
return "127.0.0.1:" + doltTestPort
}
// DoltContainerPort returns the mapped host port of the Dolt container.
func DoltContainerPort() string {
return doltTestPort
}
// DoltContainerPortInt returns the mapped host port as an int.
func DoltContainerPortInt() int {
p, _ := strconv.Atoi(doltTestPort)
return p
}
// TerminateDoltContainer stops and removes the shared Dolt container.
// Called from TestMain after m.Run().
func TerminateDoltContainer() {
terminateSharedContainer()
}
// DoltContainerCrashed returns true if the shared container has exited unexpectedly.
// Returns false if no container was started.
func DoltContainerCrashed() bool {
if doltSingletonSrv != nil && doltSingletonSrv.local != nil {
gone, _ := doltSingletonSrv.local.exited()
return gone
}
if doltSingletonSrv == nil || doltSingletonSrv.container == nil {
return false
}
state, err := doltSingletonSrv.container.State(context.Background())
if err != nil {
return true // can't check state — assume crashed
}
return !state.Running
}
// DoltContainerCrashError returns an error if the shared container has exited
// unexpectedly, nil otherwise.
func DoltContainerCrashError() error {
if doltSingletonSrv != nil && doltSingletonSrv.local != nil {
if gone, err := doltSingletonSrv.local.exited(); gone {
return fmt.Errorf("local Dolt server exited (%v); log: %s", err, doltSingletonSrv.local.logSince(0))
}
return nil
}
if doltSingletonSrv == nil || doltSingletonSrv.container == nil {
return nil
}
state, err := doltSingletonSrv.container.State(context.Background())
if err != nil {
return fmt.Errorf("failed to check container state: %w", err)
}
if !state.Running {
return fmt.Errorf("Dolt container exited (status=%s, exit=%d)", state.Status, state.ExitCode)
}
return nil
}
// containerExec runs cmd inside ctr and returns its exit code and combined
// output. Used by tests that need to inspect a container's filesystem (e.g.
// the .dolt_dropped_databases/ directory), which has no host-visible path
// since the containers are started without a bind-mounted data dir.
//
// tcexec.Multiplexed() is load-bearing, not decorative. Without it Exec hands
// back the raw hijacked Docker stream and io.ReadAll glues the 8-byte stdcopy
// frame header onto the payload: `echo hello` returns
// "\x01\x00\x00\x00\x00\x00\x00\x06hello\n". A caller that feeds such
// a string back into the container — a path read out of find(1), say — then
// fails with "invalid argument" on a prefix it cannot see.
func containerExec(ctx context.Context, ctr *dolt.DoltContainer, cmd []string) (int, string, error) {
code, reader, err := ctr.Exec(ctx, cmd, tcexec.Multiplexed())
if err != nil {
return 0, "", fmt.Errorf("exec in Dolt container: %w", err)
}
out, err := io.ReadAll(reader)
if err != nil {
return code, "", fmt.Errorf("reading exec output: %w", err)
}
return code, string(out), nil
}