Files
deploy-go/test/deploy_host_test.go
T
2026-11-05 03:22:15 +00:00

370 lines
13 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 部署腳本的黑箱測試:假的 go、systemctl、sudo 與真的 HTTP 健康端點,檢查換版與回滾。
package test
import (
"archive/tar"
"bytes"
"compress/gzip"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync/atomic"
"testing"
)
type deployHost struct {
t *testing.T
fakes string
bin string // 部署的執行檔路徑
state string // 假服務目前「執行中」的版本
calls string // systemctl 呼叫紀錄
env []string // 額外的環境變數(覆寫預設)
goRoot string // 假的 Go 安裝根目錄(GO_ROOT)
health *httptest.Server
healthy atomic.Bool
}
// binary 產生假的 feathervault:version 印出版本;起不來的版本(broken)讓假服務不回應健康檢查。
func binary(version string, broken bool) string {
return fmt.Sprintf("#!/bin/sh\n# broken=%v\n[ \"$1\" = version ] && echo \"feathervault %s (commit abc1234)\"\n", broken, version)
}
func newDeployHost(t *testing.T, newVersion string, newBroken bool) *deployHost {
d := &deployHost{t: t, fakes: t.TempDir()}
dir := t.TempDir()
d.bin = filepath.Join(dir, "feathervault")
d.state = filepath.Join(dir, "running")
d.calls = filepath.Join(dir, "calls")
d.goRoot = t.TempDir()
d.healthy.Store(true)
d.health = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := os.ReadFile(d.state)
if len(b) == 0 || !d.healthy.Load() {
http.Error(w, "down", http.StatusServiceUnavailable)
return
}
fmt.Fprintf(w, `{"status":"ok","version":%q,"commit":"abc1234"}`, strings.TrimSpace(string(b)))
}))
t.Cleanup(d.health.Close)
// 假 go install:把新版寫到 GOBIN
d.fake("go", fmt.Sprintf(`if [ "$1" = env ]; then
# 下載安裝後(GO_ROOT/go/bin/go 存在)才回報夠新的版本
if [ -x "$GO_ROOT/go/bin/go" ]; then echo go1.27.1; else echo "go${FAKE_GO_OLD:-1.27.1}"; fi
exit 0
fi
[ "$1" = install ] || exit 1
mkdir -p "$GOBIN"
cat > "$GOBIN/feathervault" <<'BIN'
%sBIN
chmod 755 "$GOBIN/feathervault"
echo "$GOPROXY $2" > "$GOBIN/../go-args"
cp "$GOBIN/../go-args" %q`, binary(newVersion, newBroken), filepath.Join(dir, "go-args")))
// 假 systemctl restart:執行目前的執行檔;有 broken 標記就讓服務不起來,否則回報它的版本
d.fake("systemctl", fmt.Sprintf(`echo "$@" >> %[1]q
[ "$1" = restart ] || exit 0
if grep -q 'broken=true' %[2]q; then : > %[3]q; else %[2]q version | awk '{print $2}' > %[3]q; fi`, d.calls, d.bin, d.state))
d.fake("journalctl", "exit 0")
d.fake("sleep", "exit 0") // 不真的等
return d
}
func (d *deployHost) fake(name, script string) {
d.t.Helper()
if err := os.WriteFile(filepath.Join(d.fakes, name), []byte("#!/bin/sh\n"+script+"\n"), 0o755); err != nil {
d.t.Fatal(err)
}
}
func (d *deployHost) installOld(version string) {
d.t.Helper()
if err := os.WriteFile(d.bin, []byte(binary(version, false)), 0o755); err != nil {
d.t.Fatal(err)
}
if err := os.WriteFile(d.state, []byte(version+"\n"), 0o644); err != nil {
d.t.Fatal(err)
}
}
func (d *deployHost) deploy(version string) (string, error) {
cmd := exec.Command("bash", "../run.sh", version)
cmd.Env = d.cmdEnv()
out, err := cmd.CombinedOutput()
return string(out), err
}
func (d *deployHost) cmdEnv() []string {
env := append(os.Environ(),
"PATH="+d.fakes+":"+os.Getenv("PATH"),
"DEPLOY_BIN="+d.bin,
"DEPLOY_SERVICE=feathervault",
"DEPLOY_NAME=feathervault",
"GITEA_URL=https://gitea.jsc.idv.tw",
"GITEA_REPO=jiantw83/feather-vault",
"DEPLOY_HEALTH_URL="+d.health.URL+"/api/health",
"DEPLOY_TIMEOUT=3",
"GITEA_TOKEN=tok",
"GO_VERSION=1.27.1",
"GO_ROOT="+d.goRoot,
)
return append(env, d.env...)
}
func (d *deployHost) version() string {
d.t.Helper()
out, err := exec.Command(d.bin, "version").CombinedOutput()
if err != nil {
d.t.Fatalf("執行 %s 失敗:%v", d.bin, err)
}
return strings.TrimSpace(string(out))
}
func TestDeployReplacesBinaryAndRestarts(t *testing.T) {
d := newDeployHost(t, "1.1.0", false)
d.installOld("1.0.0")
out, err := d.deploy("v1.1.0")
if err != nil {
t.Fatalf("部署失敗:%v\n%s", err, out)
}
if got := d.version(); !strings.Contains(got, "1.1.0") {
t.Fatalf("部署後的執行檔是 %q,應該是 1.1.0", got)
}
if b, _ := os.ReadFile(d.state); strings.TrimSpace(string(b)) != "1.1.0" {
t.Fatalf("服務執行的版本是 %q,應該是 1.1.0", b)
}
if prev, err := exec.Command(d.bin+".prev", "version").Output(); err != nil || !strings.Contains(string(prev), "1.0.0") {
t.Fatalf("上一版沒有備份:%q %v", prev, err)
}
args, _ := os.ReadFile(filepath.Join(filepath.Dir(d.bin), "go-args"))
if !strings.Contains(string(args), "/cmd/feathervault@v1.1.0") || !strings.Contains(string(args), "/api/packages/jiantw83/go") {
t.Fatalf("go install 的參數不對:%q", args)
}
}
func TestDeployRollsBackWhenNewVersionIsUnhealthy(t *testing.T) {
d := newDeployHost(t, "1.1.0", true)
d.installOld("1.0.0")
out, err := d.deploy("v1.1.0")
if err == nil {
t.Fatalf("新版起不來時部署應該失敗\n%s", out)
}
if got := d.version(); !strings.Contains(got, "1.0.0") {
t.Fatalf("回滾後的執行檔是 %q,應該換回 1.0.0", got)
}
if b, _ := os.ReadFile(d.state); strings.TrimSpace(string(b)) != "1.0.0" {
t.Fatalf("回滾後服務執行的版本是 %q,應該是 1.0.0", b)
}
calls, _ := os.ReadFile(d.calls)
if n := strings.Count(string(calls), "restart"); n != 2 {
t.Fatalf("應該重啟兩次(換新版、回滾),實際 %d 次:%q", n, calls)
}
}
func TestDeployFailsWhenServiceReportsOldVersion(t *testing.T) {
// 重啟後仍回報舊版(例如服務沒有真的重啟)不能算通過
d := newDeployHost(t, "1.1.0", false)
d.installOld("1.0.0")
d.fake("systemctl", fmt.Sprintf(`echo "$@" >> %q`, d.calls)) // restart 什麼都不做
if out, err := d.deploy("v1.1.0"); err == nil {
t.Fatalf("服務仍是舊版時部署應該失敗\n%s", out)
}
if got := d.version(); !strings.Contains(got, "1.0.0") {
t.Fatalf("失敗後的執行檔是 %q,應該換回 1.0.0", got)
}
}
func TestDeployRejectsBinaryOfWrongVersion(t *testing.T) {
d := newDeployHost(t, "1.0.5", false) // 套件庫裝出來的版本和要部署的不同
d.installOld("1.0.0")
if out, err := d.deploy("v1.1.0"); err == nil {
t.Fatalf("版本不符時應該失敗\n%s", out)
}
if got := d.version(); !strings.Contains(got, "1.0.0") {
t.Fatalf("版本不符時不應該換掉執行檔,現在是 %q", got)
}
if calls, _ := os.ReadFile(d.calls); len(calls) != 0 {
t.Fatalf("版本不符時不應該重啟服務:%q", calls)
}
}
func TestDeployFirstInstallWithoutPreviousBinary(t *testing.T) {
d := newDeployHost(t, "1.1.0", false)
if out, err := d.deploy("v1.1.0"); err != nil {
t.Fatalf("首次部署失敗:%v\n%s", err, out)
}
if got := d.version(); !strings.Contains(got, "1.1.0") {
t.Fatalf("部署後的執行檔是 %q", got)
}
}
func TestDeployInstallsGoWhenTooOld(t *testing.T) {
var gz bytes.Buffer
zw := gzip.NewWriter(&gz)
tw := tar.NewWriter(zw)
body := "#!/bin/sh\necho go1.27.1\n"
tw.WriteHeader(&tar.Header{Name: "go/bin/go", Mode: 0o755, Size: int64(len(body))})
tw.Write([]byte(body))
tw.Close()
zw.Close()
var asked string
dl := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
asked = r.URL.Path
w.Write(gz.Bytes())
}))
defer dl.Close()
d := newDeployHost(t, "1.1.0", false)
d.installOld("1.0.0")
d.env = []string{"FAKE_GO_OLD=1.20.0", "GO_DL_URL=" + dl.URL}
if out, err := d.deploy("v1.1.0"); err != nil {
t.Fatalf("部署失敗:%v\n%s", err, out)
}
if want := "/go1.27.1.linux-" + runtime.GOARCH + ".tar.gz"; asked != want {
t.Fatalf("下載了 %q,預期 %q", asked, want)
}
if _, err := os.Stat(filepath.Join(d.goRoot, "go", "bin", "go")); err != nil {
t.Fatalf("Go 沒有裝到 GO_ROOT:%v", err)
}
}
func TestDeployDoesNotReinstallGoWhenNewEnough(t *testing.T) {
d := newDeployHost(t, "1.1.0", false)
d.installOld("1.0.0")
d.env = []string{"GO_DL_URL=http://127.0.0.1:1"} // 要下載就會失敗
if out, err := d.deploy("v1.1.0"); err != nil {
t.Fatalf("Go 夠新卻去下載:%v\n%s", err, out)
}
}
func TestDeployRequiresGoVersionVariable(t *testing.T) {
d := newDeployHost(t, "1.1.0", false)
d.installOld("1.0.0")
d.env = []string{"GO_VERSION="}
out, err := d.deploy("v1.1.0")
if err == nil || !strings.Contains(out, "GO_VERSION") {
t.Fatalf("沒有 Go 版本變數時應該失敗並指出 GO_VERSION:%v\n%s", err, out)
}
}
func TestDeployInstallsServiceWhenMissing(t *testing.T) {
d := newDeployHost(t, "1.1.0", false)
d.installOld("1.0.0")
// 假 systemctl:服務不存在(cat 失敗);新執行檔的 install-service 記錄參數並讓服務「起來」
d.fake("systemctl", fmt.Sprintf(`echo "$@" >> %q
[ "$1" = cat ] && exit 1
exit 0`, d.calls))
log := filepath.Join(t.TempDir(), "install-service")
newBin := fmt.Sprintf("#!/bin/sh\n[ \"$1\" = version ] && echo \"feathervault 1.1.0 (commit abc1234)\"\n[ \"$1\" = install-service ] && { echo \"$@\" > %q; echo 1.1.0 > %q; }\nexit 0\n", log, d.state)
d.fake("go", fmt.Sprintf(`[ "$1" = env ] && { echo go1.27.1; exit 0; }
mkdir -p "$GOBIN"
cat > "$GOBIN/feathervault" <<'BIN'
%sBIN
chmod 755 "$GOBIN/feathervault"`, newBin))
d.env = []string{"DEPLOY_ADDR=0.0.0.0:9000", "DEPLOY_DATA=/srv/fv"}
if out, err := d.deploy("v1.1.0"); err != nil {
t.Fatalf("部署失敗:%v\n%s", err, out)
}
got, _ := os.ReadFile(log)
if strings.TrimSpace(string(got)) != "install-service --addr 0.0.0.0:9000 --data /srv/fv" {
t.Fatalf("install-service 的參數不對:%q", got)
}
if calls, _ := os.ReadFile(d.calls); strings.Contains(string(calls), "restart") {
t.Fatalf("服務不存在時應該由 install-service 啟動,不是 systemctl restart:%q", calls)
}
}
// dev 版也一樣:go install 指定確切版本,並以該版本做健康檢查。
func TestDeployDevVersionInstallsExactVersion(t *testing.T) {
d := newDeployHost(t, "1.1.0-dev.3", false)
d.installOld("1.0.0")
out, err := d.deploy("v1.1.0-dev.3")
if err != nil {
t.Fatalf("部署失敗:%v\n%s", err, out)
}
args, _ := os.ReadFile(filepath.Join(filepath.Dir(d.bin), "go-args"))
if !strings.Contains(string(args), "/cmd/feathervault@v1.1.0-dev.3") {
t.Fatalf("go install 應指定 dev 版本:%q", args)
}
if b, _ := os.ReadFile(d.state); strings.TrimSpace(string(b)) != "1.1.0-dev.3" {
t.Fatalf("服務執行的版本是 %q,應該是 1.1.0-dev.3", b)
}
}
// Gitea 網址與儲存庫從環境變數來(CD 傳入 github.server_url、github.repository),模組路徑與 GOPROXY 都跟著變。
func TestDeployUsesGiteaFromEnvironment(t *testing.T) {
d := newDeployHost(t, "1.1.0", false)
d.installOld("1.0.0")
d.env = append(d.env, "GITEA_URL=https://git.example.org", "GITEA_REPO=acme/vault")
if out, err := d.deploy("v1.1.0"); err != nil {
t.Fatalf("部署失敗:%v\n%s", err, out)
}
args, _ := os.ReadFile(filepath.Join(filepath.Dir(d.bin), "go-args"))
if !strings.Contains(string(args), "https://git.example.org/api/packages/acme/go") || !strings.Contains(string(args), "git.example.org/acme/vault/cmd/feathervault@v1.1.0") {
t.Fatalf("go install 的參數沒有跟著環境變數:%q", args)
}
}
// 版本一定要明確傳入:不再支援 latest,也不會去拿 @latest。
func TestDeployRequiresExplicitVersion(t *testing.T) {
d := newDeployHost(t, "1.1.0", false)
d.installOld("1.0.0")
for _, v := range []string{"latest", "1.1.0", ""} {
if out, err := d.deploy(v); err == nil {
t.Fatalf("版本 %q 應該被拒絕\n%s", v, out)
}
}
if args, _ := os.ReadFile(filepath.Join(filepath.Dir(d.bin), "go-args")); len(args) != 0 {
t.Fatalf("版本不對時不應該執行 go install:%q", args)
}
}
// 三個步驟可以單獨執行:install-binary 只把新版放到 .new,不動執行檔與服務;activate 才換上並重啟。
func TestDeployStepsRunSeparately(t *testing.T) {
d := newDeployHost(t, "1.1.0", false)
d.installOld("1.0.0")
step := func(name string, args ...string) {
t.Helper()
cmd := exec.Command("bash", append([]string{"../" + name}, args...)...)
cmd.Env = d.cmdEnv()
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("%s 失敗:%v\n%s", name, err, out)
}
}
step("check-env.sh")
step("install-binary.sh", "v1.1.0")
if got := d.version(); !strings.Contains(got, "1.0.0") {
t.Fatalf("install-binary 不應該換掉執行檔,現在是 %q", got)
}
if staged, err := exec.Command(d.bin+".new", "version").Output(); err != nil || !strings.Contains(string(staged), "1.1.0") {
t.Fatalf("新版沒有放到 .new:%q %v", staged, err)
}
if calls, _ := os.ReadFile(d.calls); len(calls) != 0 {
t.Fatalf("install-binary 不應該重啟服務:%q", calls)
}
step("activate.sh", "v1.1.0")
if got := d.version(); !strings.Contains(got, "1.1.0") {
t.Fatalf("activate 後的執行檔是 %q,應該是 1.1.0", got)
}
}
func TestActivateRequiresStagedBinary(t *testing.T) {
d := newDeployHost(t, "1.1.0", false)
d.installOld("1.0.0")
cmd := exec.Command("bash", "../activate.sh", "v1.1.0")
cmd.Env = d.cmdEnv()
if out, err := cmd.CombinedOutput(); err == nil {
t.Fatalf("沒有 install-binary 放好的新版時 activate 應該失敗\n%s", out)
}
}