Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,551 @@
|
||||
package main
|
||||
|
||||
// Tests for the /v1/update/install build-and-swap pipeline. Hermetic by
|
||||
// construction: ADPANEL_NODE_GO_DIR redirects the toolchain state (and the
|
||||
// build staging area) into a scratch directory, and the scratch dataRoot is a
|
||||
// copy of this repo's own main.go/go.mod/go.sum with the NodeVersion const
|
||||
// bumped, plus a vendored module tree so `go build` never needs the network.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// bumpedUpdateVersion differs from the compile-time NodeVersion const of the
|
||||
// running test binary, so a binary built from the scratch sources reports a
|
||||
// provably different --version than the running one.
|
||||
const bumpedUpdateVersion = "9.9.9"
|
||||
|
||||
// nodeVersionConstRe matches the NodeVersion const declaration only (the
|
||||
// struct field, handler locals and normalizeNodeVersionTag references do not
|
||||
// have this shape).
|
||||
var nodeVersionConstRe = regexp.MustCompile(`(NodeVersion\s*=\s*)"[^"]*"`)
|
||||
|
||||
var (
|
||||
vendorOnce sync.Once
|
||||
vendorRoot string
|
||||
vendorErr error
|
||||
)
|
||||
|
||||
// copyBumpedSources copies this repo's package-main sources (every non-test
|
||||
// .go file in the repo root — package main spans main.go and docker_engine.go)
|
||||
// plus go.mod/go.sum into dir, with the NodeVersion const bumped to
|
||||
// bumpedUpdateVersion. With corrupt=true a syntax error is appended so the
|
||||
// build must fail.
|
||||
func copyBumpedSources(t *testing.T, dir string, corrupt bool) {
|
||||
t.Helper()
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("working dir: %v", err)
|
||||
}
|
||||
goFiles, err := filepath.Glob(filepath.Join(wd, "*.go"))
|
||||
if err != nil {
|
||||
t.Fatalf("glob repo sources: %v", err)
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o750); err != nil {
|
||||
t.Fatalf("mkdir scratch dataRoot: %v", err)
|
||||
}
|
||||
sawVersionConst := false
|
||||
for _, src := range goFiles {
|
||||
if strings.HasSuffix(src, "_test.go") {
|
||||
continue
|
||||
}
|
||||
b, err := os.ReadFile(src)
|
||||
if err != nil {
|
||||
t.Fatalf("read repo source %s: %v", src, err)
|
||||
}
|
||||
if nodeVersionConstRe.Match(b) {
|
||||
if n := len(nodeVersionConstRe.FindAllSubmatchIndex(b, -1)); n != 1 {
|
||||
t.Fatalf("expected exactly one NodeVersion const in %s, found %d", src, n)
|
||||
}
|
||||
sawVersionConst = true
|
||||
b = nodeVersionConstRe.ReplaceAll(b, []byte(`${1}"`+bumpedUpdateVersion+`"`))
|
||||
}
|
||||
if corrupt && strings.HasSuffix(src, "main.go") {
|
||||
b = append(b, []byte("\nfunc brokenForUpdateTest() {\n")...)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, filepath.Base(src)), b, 0o644); err != nil {
|
||||
t.Fatalf("write scratch source %s: %v", filepath.Base(src), err)
|
||||
}
|
||||
}
|
||||
if !sawVersionConst {
|
||||
t.Fatal("NodeVersion const not found in any repo source file")
|
||||
}
|
||||
for _, name := range []string{"go.mod", "go.sum"} {
|
||||
b, err := os.ReadFile(filepath.Join(wd, name))
|
||||
if err != nil {
|
||||
t.Fatalf("read repo %s: %v", name, err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, name), b, 0o644); err != nil {
|
||||
t.Fatalf("write scratch %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// prepareVendorTree runs `go mod vendor` once per test run in a scratch copy
|
||||
// of the repo sources (with the bumped version). It relies on the host module
|
||||
// cache, which is warm because this repo itself builds, so no network is
|
||||
// needed and the per-test scratch builds stay fully local.
|
||||
func prepareVendorTree(t *testing.T) string {
|
||||
t.Helper()
|
||||
vendorOnce.Do(func() {
|
||||
tmp, err := os.MkdirTemp("", "adnode-update-vendor-*")
|
||||
if err != nil {
|
||||
vendorErr = err
|
||||
return
|
||||
}
|
||||
copyBumpedSources(t, tmp, false)
|
||||
goBin, err := goBinaryPath()
|
||||
if err != nil {
|
||||
vendorErr = err
|
||||
return
|
||||
}
|
||||
cmd := exec.Command(goBin, "mod", "vendor")
|
||||
cmd.Dir = tmp
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
vendorErr = err
|
||||
t.Logf("go mod vendor failed: %v: %s", err, strings.TrimSpace(string(out)))
|
||||
return
|
||||
}
|
||||
vendorRoot = tmp
|
||||
})
|
||||
if vendorErr != nil {
|
||||
t.Fatalf("prepare vendor tree: %v", vendorErr)
|
||||
}
|
||||
return vendorRoot
|
||||
}
|
||||
|
||||
// newUpdateScratchAgent returns an Agent whose dataRoot contains the bumped
|
||||
// update sources plus a vendored module tree, with ADPANEL_NODE_GO_DIR pointed
|
||||
// at a scratch toolchain dir. It returns the agent, the toolchain dir and the
|
||||
// dataRoot.
|
||||
func newUpdateScratchAgent(t *testing.T, corrupt bool) (*Agent, string, string) {
|
||||
t.Helper()
|
||||
goDir := t.TempDir()
|
||||
t.Setenv("ADPANEL_NODE_GO_DIR", goDir)
|
||||
dataRoot := t.TempDir()
|
||||
copyBumpedSources(t, dataRoot, corrupt)
|
||||
vendor := filepath.Join(dataRoot, "vendor")
|
||||
if err := os.CopyFS(vendor, os.DirFS(filepath.Join(prepareVendorTree(t), "vendor"))); err != nil {
|
||||
t.Fatalf("copy vendor tree into scratch dataRoot: %v", err)
|
||||
}
|
||||
return &Agent{dataRoot: dataRoot}, goDir, dataRoot
|
||||
}
|
||||
|
||||
// TestNodeUpdateInstallBuildVerifySwap is the happy path: the build succeeds,
|
||||
// the staged binary verifies at the target version via its --version
|
||||
// self-check (which also exercises the --version flag handling in main()), and
|
||||
// the swap replaces a placeholder active file with the staged file gone after
|
||||
// the rename.
|
||||
func TestNodeUpdateInstallBuildVerifySwap(t *testing.T) {
|
||||
if _, err := goBinaryPath(); err != nil {
|
||||
t.Skipf("no go toolchain available, skipping build-dependent test: %v", err)
|
||||
}
|
||||
a, goDir, _ := newUpdateScratchAgent(t, false)
|
||||
|
||||
staging, err := a.buildAdaemonBinary(context.Background(), bumpedUpdateVersion)
|
||||
if err != nil {
|
||||
t.Fatalf("buildAdaemonBinary: %v", err)
|
||||
}
|
||||
if st, err := os.Stat(staging); err != nil || st.IsDir() {
|
||||
t.Fatalf("staged binary missing after build: %v", err)
|
||||
}
|
||||
|
||||
// Indirect --version flag check: the staged binary must print the bumped
|
||||
// version, proving the const bump took effect and main() answers the flag
|
||||
// before any config is loaded. exec.Command().Output() fails on a non-zero
|
||||
// exit, so err==nil also pins exit status 0.
|
||||
out, err := exec.Command(staging, "--version").Output()
|
||||
if err != nil {
|
||||
t.Fatalf("staged binary --version: %v: %s", err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
// Exactly one line, nothing else: the update verifier reads the whole
|
||||
// stdout, so extra log lines would corrupt the comparison.
|
||||
lines := strings.Split(strings.TrimRight(string(out), "\n"), "\n")
|
||||
if len(lines) != 1 || lines[0] != "v"+bumpedUpdateVersion {
|
||||
t.Fatalf("staged binary --version must be exactly one line %q, got %d lines: %q", "v"+bumpedUpdateVersion, len(lines), string(out))
|
||||
}
|
||||
|
||||
// Swap the staged binary over a placeholder active file, mirroring what
|
||||
// handleNodeUpdateInstall does to the real /proc/self/exe target.
|
||||
active := filepath.Join(t.TempDir(), "adnode-active")
|
||||
if err := os.WriteFile(active, []byte("placeholder-old-image"), 0o755); err != nil {
|
||||
t.Fatalf("write placeholder active file: %v", err)
|
||||
}
|
||||
if err := os.Rename(staging, active); err != nil {
|
||||
t.Fatalf("swap rename: %v", err)
|
||||
}
|
||||
if err := os.Chmod(active, 0o755); err != nil {
|
||||
t.Fatalf("swap chmod: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(staging); !os.IsNotExist(err) {
|
||||
t.Fatalf("staged file still present after swap (err=%v)", err)
|
||||
}
|
||||
out, err = exec.Command(active, "--version").Output()
|
||||
if err != nil {
|
||||
t.Fatalf("swapped binary --version: %v: %s", err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
if got := strings.TrimSpace(string(out)); got != "v"+bumpedUpdateVersion {
|
||||
t.Fatalf("swapped binary --version = %q, want %q", got, "v"+bumpedUpdateVersion)
|
||||
}
|
||||
|
||||
// The scratch toolchain dir must have been used for the build caches.
|
||||
if _, err := os.Stat(filepath.Join(goDir, "gocache")); err != nil {
|
||||
t.Fatalf("expected scratch gocache under %s to be used: %v", goDir, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNodeUpdateInstallFailClosedOnBuildError injects a syntax error into the
|
||||
// scratch sources: the build must fail with go-build output, nothing may be
|
||||
// staged, and the active file must stay byte-identical to before.
|
||||
func TestNodeUpdateInstallFailClosedOnBuildError(t *testing.T) {
|
||||
if _, err := goBinaryPath(); err != nil {
|
||||
t.Skipf("no go toolchain available, skipping build-dependent test: %v", err)
|
||||
}
|
||||
a, goDir, _ := newUpdateScratchAgent(t, true)
|
||||
|
||||
active := filepath.Join(t.TempDir(), "adnode-active")
|
||||
if err := os.WriteFile(active, []byte("old-running-image"), 0o755); err != nil {
|
||||
t.Fatalf("write placeholder active file: %v", err)
|
||||
}
|
||||
before, err := os.ReadFile(active)
|
||||
if err != nil {
|
||||
t.Fatalf("read active before: %v", err)
|
||||
}
|
||||
|
||||
staging, err := a.buildAdaemonBinary(context.Background(), bumpedUpdateVersion)
|
||||
if err == nil {
|
||||
t.Fatal("expected build error from corrupted sources")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "go build failed") {
|
||||
t.Fatalf("build error should carry go build output, got: %v", err)
|
||||
}
|
||||
|
||||
// Fail closed: no staging artifact left behind, active file untouched.
|
||||
if staging != "" {
|
||||
t.Fatalf("staging path returned on failure: %q", staging)
|
||||
}
|
||||
if leftovers, _ := filepath.Glob(filepath.Join(goDir, "adnode.update-*")); len(leftovers) != 0 {
|
||||
t.Fatalf("staging leftovers after failed build: %v", leftovers)
|
||||
}
|
||||
after, err := os.ReadFile(active)
|
||||
if err != nil {
|
||||
t.Fatalf("read active after: %v", err)
|
||||
}
|
||||
if !bytes.Equal(before, after) {
|
||||
t.Fatal("active file changed even though the build failed")
|
||||
}
|
||||
}
|
||||
|
||||
// TestReadNodeInformationVersionHonesty pins the version-honesty contract: a
|
||||
// persisted NodeVersion (array or legacy object form) must never override the
|
||||
// compile-time const of the running binary, while architecture, auto-update
|
||||
// and updatedAt keep being honored.
|
||||
func TestReadNodeInformationVersionHonesty(t *testing.T) {
|
||||
a := &Agent{dataRoot: t.TempDir()}
|
||||
|
||||
arr := []NodeInformation{{
|
||||
NodeVersion: "v9.9.9-never-activated",
|
||||
NodeArchitecture: "mips/pretend",
|
||||
NodeAutoUpdate: true,
|
||||
UpdatedAt: "2020-01-01T00:00:00Z",
|
||||
}}
|
||||
b, err := json.Marshal(arr)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(a.nodeInformationPath(), b, 0o644); err != nil {
|
||||
t.Fatalf("write node information: %v", err)
|
||||
}
|
||||
info := a.readNodeInformation()
|
||||
if want := normalizeNodeVersionTag(NodeVersion); info.NodeVersion != want {
|
||||
t.Fatalf("persisted version leaked through array form: got %q, want compile-time %q", info.NodeVersion, want)
|
||||
}
|
||||
if info.NodeArchitecture != "mips/pretend" {
|
||||
t.Fatalf("architecture override must stay honored, got %q", info.NodeArchitecture)
|
||||
}
|
||||
if !info.NodeAutoUpdate {
|
||||
t.Fatal("auto-update flag must stay honored")
|
||||
}
|
||||
if info.UpdatedAt != "2020-01-01T00:00:00Z" {
|
||||
t.Fatalf("updatedAt must stay honored, got %q", info.UpdatedAt)
|
||||
}
|
||||
|
||||
// Legacy single-object form must be equally ignored for the version.
|
||||
obj := map[string]any{"node-version": "v0.0.1-failed-update", "node-architecture": "arm64/other", "node-auto-update": true}
|
||||
b, err = json.Marshal(obj)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(a.nodeInformationPath(), b, 0o644); err != nil {
|
||||
t.Fatalf("write node information: %v", err)
|
||||
}
|
||||
info = a.readNodeInformation()
|
||||
if want := normalizeNodeVersionTag(NodeVersion); info.NodeVersion != want {
|
||||
t.Fatalf("persisted version leaked through object form: got %q, want compile-time %q", info.NodeVersion, want)
|
||||
}
|
||||
if info.NodeArchitecture != "arm64/other" {
|
||||
t.Fatalf("architecture override must stay honored (object form), got %q", info.NodeArchitecture)
|
||||
}
|
||||
|
||||
// Missing file: defaults to the honest compile-time version.
|
||||
if err := os.Remove(a.nodeInformationPath()); err != nil {
|
||||
t.Fatalf("remove node information: %v", err)
|
||||
}
|
||||
if info := a.readNodeInformation(); info.NodeVersion != normalizeNodeVersionTag(NodeVersion) {
|
||||
t.Fatalf("default version = %q, want compile-time %q", info.NodeVersion, normalizeNodeVersionTag(NodeVersion))
|
||||
}
|
||||
}
|
||||
|
||||
// TestNodeUpdateInstallVersionMismatchFailClosedAndTagNormalization pins the
|
||||
// verify gate: a staged binary that does not report the target version must
|
||||
// fail closed (no artifact returned, staging removed, nothing left behind),
|
||||
// while a target that merely normalizes differently — the panel sends
|
||||
// "v9.9.9", a hand-built payload might say "9.9.9" — must be accepted because
|
||||
// normalizeNodeVersionTag is applied on BOTH sides of the comparison.
|
||||
func TestNodeUpdateInstallVersionMismatchFailClosedAndTagNormalization(t *testing.T) {
|
||||
if _, err := goBinaryPath(); err != nil {
|
||||
t.Skipf("no go toolchain available, skipping build-dependent test: %v", err)
|
||||
}
|
||||
a, goDir, _ := newUpdateScratchAgent(t, false)
|
||||
|
||||
// Mismatch: the built binary reports v9.9.9, the target says 9.9.8.
|
||||
staging, err := a.buildAdaemonBinary(context.Background(), "9.9.8")
|
||||
if err == nil {
|
||||
t.Fatal("expected the version mismatch to fail the build gate")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "does not report the target version") {
|
||||
t.Fatalf("mismatch error should name the verify gate, got: %v", err)
|
||||
}
|
||||
if staging != "" {
|
||||
t.Fatalf("staging path returned on version mismatch: %q", staging)
|
||||
}
|
||||
if leftovers, _ := filepath.Glob(filepath.Join(goDir, "adnode.update-*")); len(leftovers) != 0 {
|
||||
t.Fatalf("staging leftovers after version mismatch: %v", leftovers)
|
||||
}
|
||||
|
||||
// Both sides normalize: the staged binary prints "v9.9.9" (the --version
|
||||
// flag normalizes), the target arrives as "9.9.9" or "v9.9.9". Each
|
||||
// acceptance proves one side of the equality; the warm build cache makes
|
||||
// the repeats cheap.
|
||||
for _, target := range []string{"9.9.9", "v9.9.9"} {
|
||||
staging, err := a.buildAdaemonBinary(context.Background(), target)
|
||||
if err != nil {
|
||||
t.Fatalf("buildAdaemonBinary(target %q) must pass the verify gate: %v", target, err)
|
||||
}
|
||||
if err := os.Remove(staging); err != nil {
|
||||
t.Fatalf("remove staged artifact between iterations: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// signedNodeInstallRequest builds a POST /v1/update/install request exactly
|
||||
// the way the panel does: bearer auth plus the admin signing envelope whose
|
||||
// subject is the NORMALIZED version (the panel's payload.version is always
|
||||
// the "v"-prefixed form, and the daemon signs the same normalized value).
|
||||
func signedNodeInstallRequest(t *testing.T, a *Agent, version string, files []nodeUpdateFilePayload) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
ts := strconv.FormatInt(time.Now().UnixMilli(), 10)
|
||||
nonce := "0123456789abcdef0123456789abcdef"
|
||||
body, err := json.Marshal(nodeUpdateInstallRequest{Version: version, Files: files})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal install body: %v", err)
|
||||
}
|
||||
base := strings.Join([]string{a.uuid, "node-update-install", normalizeNodeVersionTag(version), "admin", ts, nonce}, "|")
|
||||
r := httptest.NewRequest("POST", "/v1/update/install", bytes.NewReader(body))
|
||||
r.Header.Set("Authorization", "Bearer "+a.token)
|
||||
r.Header.Set("x-panel-role", "admin")
|
||||
r.Header.Set("x-panel-ts", ts)
|
||||
r.Header.Set("x-panel-nonce", nonce)
|
||||
r.Header.Set("x-panel-sign", hmacHex(a.panelHMAC, base))
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
a.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
// TestNodeUpdateInstallHandlerFailClosedOnBrokenToolchain drives the real
|
||||
// handler end-to-end with a signed panel request and a `go` stub that exits
|
||||
// non-zero (proving exec.LookPath precedence: PATH wins over the fallbacks).
|
||||
// The install must fail closed at the HTTP layer: a 500 with ok:false and no
|
||||
// success fields, the running (test) binary untouched, the reported version
|
||||
// still the honest compile-time one, and no staging leftovers.
|
||||
func TestNodeUpdateInstallHandlerFailClosedOnBrokenToolchain(t *testing.T) {
|
||||
if _, err := goBinaryPath(); err != nil {
|
||||
t.Skipf("no go toolchain available, skipping build-dependent test: %v", err)
|
||||
}
|
||||
a, goDir, dataRoot := newUpdateScratchAgent(t, false)
|
||||
a.uuid = "node-uuid"
|
||||
a.token = "tok"
|
||||
a.panelHMAC = "test-secret"
|
||||
|
||||
// A broken `go` stub on PATH must be the toolchain the build uses.
|
||||
brokenBin := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(brokenBin, "go"), []byte("#!/bin/sh\necho 'injected toolchain failure' >&2\nexit 7\n"), 0o755); err != nil {
|
||||
t.Fatalf("write broken go stub: %v", err)
|
||||
}
|
||||
t.Setenv("PATH", brokenBin)
|
||||
|
||||
mainGo, err := os.ReadFile(filepath.Join(dataRoot, "main.go"))
|
||||
if err != nil {
|
||||
t.Fatalf("read scratch main.go: %v", err)
|
||||
}
|
||||
files := []nodeUpdateFilePayload{{
|
||||
Path: "main.go",
|
||||
ContentBase64: base64.StdEncoding.EncodeToString(mainGo),
|
||||
}}
|
||||
w := signedNodeInstallRequest(t, a, "9.9.9", files)
|
||||
|
||||
if w.Code != 500 {
|
||||
t.Fatalf("broken toolchain install must fail with 500, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var respBody map[string]any
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &respBody); err != nil {
|
||||
t.Fatalf("response is not JSON: %v", err)
|
||||
}
|
||||
if respBody["ok"] != false {
|
||||
t.Fatalf("fail-closed response must carry ok:false, got: %v", respBody["ok"])
|
||||
}
|
||||
errMsg, _ := respBody["error"].(string)
|
||||
if !strings.Contains(errMsg, "go build failed") || !strings.Contains(errMsg, "injected toolchain failure") {
|
||||
t.Fatalf("error should carry the injected toolchain failure, got: %q", errMsg)
|
||||
}
|
||||
if _, success := respBody["version"]; success {
|
||||
t.Fatalf("fail-closed response must not claim a version: %v", respBody)
|
||||
}
|
||||
if _, success := respBody["restartCommand"]; success {
|
||||
t.Fatalf("fail-closed response must not carry restartCommand: %v", respBody)
|
||||
}
|
||||
if got, _ := respBody["filesUpdated"].(float64); got != 1 {
|
||||
t.Fatalf("filesUpdated should report the one written file, got: %v", respBody["filesUpdated"])
|
||||
}
|
||||
|
||||
// No staging artifact may survive, and the version the daemon reports
|
||||
// must still be the OLD (compile-time) one so the panel re-offers.
|
||||
if leftovers, _ := filepath.Glob(filepath.Join(goDir, "adnode.update-*")); len(leftovers) != 0 {
|
||||
t.Fatalf("staging leftovers after handler-level failure: %v", leftovers)
|
||||
}
|
||||
infoReq := httptest.NewRequest("GET", "/v1/update/info", nil)
|
||||
infoReq.Header.Set("Authorization", "Bearer "+a.token)
|
||||
infoW := httptest.NewRecorder()
|
||||
a.ServeHTTP(infoW, infoReq)
|
||||
if infoW.Code != 200 {
|
||||
t.Fatalf("update/info after failed install: %d %s", infoW.Code, infoW.Body.String())
|
||||
}
|
||||
var infoBody map[string]any
|
||||
if err := json.Unmarshal(infoW.Body.Bytes(), &infoBody); err != nil {
|
||||
t.Fatalf("info response is not JSON: %v", err)
|
||||
}
|
||||
if want := normalizeNodeVersionTag(NodeVersion); infoBody["version"] != want {
|
||||
t.Fatalf("after a failed install /v1/update/info must still report the running version %q, got %v", want, infoBody["version"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestRenameOverRunningBinaryIsLegal proves the OS premise of the swap: a
|
||||
// rename over a RUNNING executable succeeds on Linux, the old image keeps
|
||||
// executing from the now-unlinked inode, and the path immediately serves the
|
||||
// new image. This is why the pipeline never needs a window where the daemon
|
||||
// is down, and why it must never write the active file in place (ETXTBSY).
|
||||
func TestRenameOverRunningBinaryIsLegal(t *testing.T) {
|
||||
sleepBin, err := exec.LookPath("sleep")
|
||||
if err != nil {
|
||||
t.Skipf("no sleep binary available: %v", err)
|
||||
}
|
||||
scratch := t.TempDir()
|
||||
running := filepath.Join(scratch, "adnode")
|
||||
b, err := os.ReadFile(sleepBin)
|
||||
if err != nil {
|
||||
t.Fatalf("read sleep binary: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(running, b, 0o755); err != nil {
|
||||
t.Fatalf("write running placeholder: %v", err)
|
||||
}
|
||||
cmd := exec.Command(running, "30")
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatalf("start running placeholder: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
_ = cmd.Process.Kill()
|
||||
_, _ = cmd.Process.Wait()
|
||||
}()
|
||||
|
||||
// Wait until the process image is actually live.
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
if link, lerr := os.Readlink(fmt.Sprintf("/proc/%d/exe", cmd.Process.Pid)); lerr == nil && strings.HasSuffix(link, "adnode") {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("running placeholder never came up")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
|
||||
replacement := filepath.Join(scratch, "adnode.update-1")
|
||||
if err := os.WriteFile(replacement, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
|
||||
t.Fatalf("write replacement: %v", err)
|
||||
}
|
||||
if err := os.Rename(replacement, running); err != nil {
|
||||
t.Fatalf("rename over a running binary must succeed on Linux: %v", err)
|
||||
}
|
||||
|
||||
// The old image keeps executing (from the unlinked inode)...
|
||||
if link, lerr := os.Readlink(fmt.Sprintf("/proc/%d/exe", cmd.Process.Pid)); lerr == nil {
|
||||
if !strings.HasSuffix(link, " (deleted)") {
|
||||
t.Fatalf("running process should reference the unlinked old image, got %q", link)
|
||||
}
|
||||
}
|
||||
// ...while the same path now serves the NEW image.
|
||||
if err := exec.Command(running, "0").Run(); err != nil {
|
||||
t.Fatalf("active path must execute the replacement after the swap: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestActivateUpdatedDaemonExecFailureFallsBack proves the last row of the
|
||||
// fail-closed matrix: when syscall.Exec cannot start the new image (and,
|
||||
// with no systemctl reachable, the fallback restart fails too), the daemon
|
||||
// must survive, log both failures, and keep serving the OLD image — never
|
||||
// crash and never claim success it did not earn.
|
||||
func TestActivateUpdatedDaemonExecFailureFallsBack(t *testing.T) {
|
||||
// Empty PATH: no systemctl, so the fallback restart fails instantly and
|
||||
// hermetically instead of touching the host's init system.
|
||||
t.Setenv("PATH", t.TempDir())
|
||||
a := &Agent{dataRoot: t.TempDir()}
|
||||
missing := filepath.Join(t.TempDir(), "missing-adnode")
|
||||
|
||||
oldStderr := os.Stderr
|
||||
pr, pw, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatalf("pipe: %v", err)
|
||||
}
|
||||
os.Stderr = pw
|
||||
start := time.Now()
|
||||
a.activateUpdatedDaemon(missing) // must spawn the goroutine and return immediately
|
||||
if elapsed := time.Since(start); elapsed > 900*time.Millisecond {
|
||||
t.Fatalf("activateUpdatedDaemon blocked the handler for %v", elapsed)
|
||||
}
|
||||
time.Sleep(1600 * time.Millisecond) // drain window + failed exec + failed fallback
|
||||
_ = pw.Close()
|
||||
os.Stderr = oldStderr
|
||||
logged, _ := io.ReadAll(pr)
|
||||
_ = pr.Close()
|
||||
if !strings.Contains(string(logged), "in-place re-exec") || !strings.Contains(string(logged), "falling back to systemctl restart adaemon") {
|
||||
t.Fatalf("failed exec must log the fallback, got stderr: %q", string(logged))
|
||||
}
|
||||
// Reaching this point proves the failed exec/fallback did not exit or
|
||||
// replace this process: the test binary is still running its own image.
|
||||
}
|
||||
Reference in new issue
Block a user