commit d0cdfdc13949a7d87066495aabf527c4f369989c Author: bot Date: Thu Nov 5 02:54:22 2026 +0000 初始版本:從 feather-vault 搬出 diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml new file mode 100644 index 0000000..3ce21ff --- /dev/null +++ b/.gitea/workflows/ci.yaml @@ -0,0 +1,22 @@ +name: ci +on: + push: + branches: [main] + pull_request: +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true +jobs: + test: + runs-on: docker-ubuntu + steps: + - uses: actions/checkout@v4 + - name: shellcheck + run: | + curl -fsSL https://github.com/koalaman/shellcheck/releases/download/v0.10.0/shellcheck-v0.10.0.linux.x86_64.tar.xz | tar -xJ -C "$RUNNER_TEMP" --strip-components=1 + "$RUNNER_TEMP/shellcheck" -x -S warning ./*.sh + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + - name: 腳本黑箱測試 + run: go vet ./... && go test ./test/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..02e0b96 --- /dev/null +++ b/README.md @@ -0,0 +1,64 @@ +# deploy + +三個步驟:檢查環境 → `go install` 指定版本 → 安裝與啟動服務;健康檢查沒通過就換回上一版。composite action,要在目標主機的 runner 上執行。 + +## 用法 + +版本由呼叫端的 Gitea Actions 變數決定(例如 `vars.ACTION_DEPLOY_VERSION`),不要用分支名稱:runner 依 ref 重用舊映像檔,改了腳本不會生效,所以每次改動都發新標籤。 + +```yaml +- uses: https://gitea.jsc.idv.tw/actions/deploy@${{ vars.ACTION_DEPLOY_VERSION }} + with: + version: ... + go_version: ... +``` + +## 輸入 + +|名稱|必填|預設|說明| +|---|---|---|---| +|`version`|是||要部署的確切版本,例如 v0.4.9 或 v0.5.0-dev.2| +|`token`|||套件庫需要驗證時的權杖(需要 read:package)| +|`go_version`|是||需要的 Go 版本(通常是 vars.GO_VERSION);主機的 Go 不足就下載安裝| +|`addr`|||服務不存在、要安裝時的監聽位址(通常是 vars.DEPLOY_ADDR;空=預設 0.0.0.0:8080)| +|`data`|||服務不存在、要安裝時的資料目錄(通常是 vars.DEPLOY_DATA;空=預設 /var/lib/<名稱>)| +|`name`|||應用程式名稱,決定執行檔(/usr/local/bin/<名稱>)、服務名稱、go install 的 cmd/<名稱> 與資料目錄;預設是儲存庫名稱| +|`gitea_url`||`${{ github.server_url }}`|Gitea 網址,預設是目前的 Gitea(github.server_url)| +|`gitea_repo`||`${{ github.repository }}`|Gitea 儲存庫 <擁有者>/<名稱>,預設是目前的儲存庫(github.repository)| + +## 開發 + +`ci.yaml` 跑 shellcheck、`test/` 的腳本黑箱測試(`go test ./test/`)。 + +圖示:`icon.svg`(Gitea 儲存庫頭像用 `icon.png`)。 + +## 在沒有 git 的主機上使用 + +主機沒有 git 時不能 `uses`(取得 action 需要 git clone),改用 curl 抓腳本再執行: + +```yaml +runs-on: <部署主機的 runner 標籤> +steps: + - env: + GITEA_TOKEN: ${{ secrets.TOKEN || github.token }} + GO_VERSION: ${{ vars.GO_VERSION }} + DEPLOY_NAME: myapp + RAW_URL: ${{ github.server_url }}/api/v1/repos/actions/deploy/raw + REF: ${{ vars.ACTION_DEPLOY_VERSION }} + run: | + set -euo pipefail + dir=$(mktemp -d); trap 'rm -rf "$dir"' EXIT + for f in common.sh check-env.sh install-binary.sh activate.sh run.sh; do + curl -fsSL -H "Authorization: token $GITEA_TOKEN" -o "$dir/$f" "$RAW_URL/$f?ref=$REF" + done + bash "$dir/run.sh" "<版本>" +``` + +## 對應用程式的要求 + +- Go 模組路徑是「Gitea 主機/擁有者/名稱」,主程式在 `cmd/<名稱>`(可用 `DEPLOY_PACKAGE` 改)。 +- `<執行檔> version` 輸出的第二個欄位是版本(不含 `v`),例如 `myapp 1.2.3 (commit abc1234)`。 +- 服務不存在時用 `<執行檔> install-service --addr <位址> --data <資料目錄>` 安裝並啟動。 +- 健康檢查(預設 `http://127.0.0.1:8080/api/health`,可用 `DEPLOY_HEALTH_URL` 改)回 JSON,`status` 是 `ok` 且 `version` 等於目標版本。 + +其他環境變數見 `common.sh` 開頭。 diff --git a/action.yml b/action.yml new file mode 100644 index 0000000..225efe1 --- /dev/null +++ b/action.yml @@ -0,0 +1,55 @@ +name: deploy +description: "把 Go 應用程式的指定版本部署到這台主機(composite action,三個步驟:檢查環境 → go install 指定版本 → 安裝與啟動服務,失敗換回上一版)。要在目標主機的 runner 上執行,且主機要有 git 才能 uses;沒有 git 的主機改用 curl 抓本 repo 的 run.sh 再執行(見 README)。版本一定要明確傳入,不會拿 @latest" +inputs: + version: + description: "要部署的確切版本,例如 v0.4.9 或 v0.5.0-dev.2" + required: true + token: + description: "套件庫需要驗證時的權杖(需要 read:package)" + default: "" + go_version: + description: "需要的 Go 版本(通常是 vars.GO_VERSION);主機的 Go 不足就下載安裝" + required: true + addr: + description: "服務不存在、要安裝時的監聽位址(通常是 vars.DEPLOY_ADDR;空=預設 0.0.0.0:8080)" + default: "" + data: + description: "服務不存在、要安裝時的資料目錄(通常是 vars.DEPLOY_DATA;空=預設 /var/lib/<名稱>)" + default: "" + name: + description: "應用程式名稱,決定執行檔(/usr/local/bin/<名稱>)、服務名稱、go install 的 cmd/<名稱> 與資料目錄;預設是儲存庫名稱" + default: "" + gitea_url: + description: "Gitea 網址,預設是目前的 Gitea(github.server_url)" + default: ${{ github.server_url }} + gitea_repo: + description: "Gitea 儲存庫 <擁有者>/<名稱>,預設是目前的儲存庫(github.repository)" + default: ${{ github.repository }} +runs: + using: composite + steps: + - name: 1. 檢查環境 + shell: bash + env: + DEPLOY_NAME: ${{ inputs.name }} + GITEA_URL: ${{ inputs.gitea_url }} + GITEA_REPO: ${{ inputs.gitea_repo }} + GO_VERSION: ${{ inputs.go_version }} + run: bash "${{ github.action_path }}/check-env.sh" + - name: 2. go install 指定版本 + shell: bash + env: + DEPLOY_NAME: ${{ inputs.name }} + GITEA_TOKEN: ${{ inputs.token }} + GITEA_URL: ${{ inputs.gitea_url }} + GITEA_REPO: ${{ inputs.gitea_repo }} + run: bash "${{ github.action_path }}/install-binary.sh" "${{ inputs.version }}" + - name: 3. 安裝與啟動服務 + shell: bash + env: + DEPLOY_NAME: ${{ inputs.name }} + GITEA_URL: ${{ inputs.gitea_url }} + GITEA_REPO: ${{ inputs.gitea_repo }} + DEPLOY_ADDR: ${{ inputs.addr }} + DEPLOY_DATA: ${{ inputs.data }} + run: bash "${{ github.action_path }}/activate.sh" "${{ inputs.version }}" diff --git a/activate.sh b/activate.sh new file mode 100755 index 0000000..a820186 --- /dev/null +++ b/activate.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# 部署步驟 3:安裝與啟動服務。備份上一版 → 把 install-binary 放好的 <執行檔>.new 改名換上 → 重啟(服務不存在就 install-service)→ +# 輪詢 GET /api/health,status 要是 ok 且 version 等於指定版本 → 失敗就換回上一版、重啟,並以非 0 結束。資料庫遷移只往前,不回滾。 +# .gitea/actions/deploy/activate.sh <版本,例如 v0.4.9> +set -euo pipefail +. "$(dirname "$0")/common.sh" +version=${1:?用法:activate.sh <版本,例如 v0.4.9>} +want=${version#v} +addr=${DEPLOY_ADDR:-0.0.0.0:8080} +data=${DEPLOY_DATA:-/var/lib/$name} + +[ -f "$staged" ] || { echo "找不到 $staged:先執行 install-binary.sh" >&2; exit 1; } + +# 健康檢查:等到服務回報目標版本(舊程序還在回應時不算通過) +wait_healthy() { + local expect=$1 deadline=$((SECONDS + timeout)) body + while [ "$SECONDS" -lt "$deadline" ]; do + if body=$(curl -fsS --max-time 3 "$health" 2>/dev/null) && + printf %s "$body" | grep -Eq '"status" *: *"ok"' && + printf %s "$body" | grep -Eq "\"version\" *: *\"$expect\""; then + return 0 + fi + sleep 1 + done + return 1 +} + +# 1. 備份上一版 +had_prev=0 +if [ -f "$bin" ]; then + $sudo cp -p "$bin" "$prev" + had_prev=1 + log "已備份上一版到 $prev" +else + log "沒有上一版($bin 不存在),失敗時無法回滾" +fi + +# 2. 換執行檔(同目錄改名,原子替換;服務正在執行時直接覆寫會失敗 Text file busy) +$sudo mv -f "$staged" "$bin" + +# 3. 重啟並檢查。收到 SIGTERM 時進行中的子任務會放回 pending,重啟後重做 +if $sudo systemctl cat "$service.service" >/dev/null 2>&1; then + log "重啟 $service" + $sudo systemctl restart "$service" || true +else + # 第一次部署:服務還不存在。install-service 會建立服務檔、enable 並啟動 + log "服務 $service 不存在,安裝(監聽 $addr,資料目錄 $data)" + $sudo "$bin" install-service --addr "$addr" --data "$data" || true +fi +if wait_healthy "$want"; then + log "部署完成:$version 在 $timeout 秒內通過健康檢查" + exit 0 +fi + +# 4. 回滾 +echo "新版 $version 在 $timeout 秒內沒有通過健康檢查($health)" >&2 +if [ "$had_prev" = 1 ]; then + log "換回上一版並重啟" + $sudo cp -p "$prev" "$bin.new" + $sudo mv -f "$bin.new" "$bin" + $sudo systemctl restart "$service" || true + echo "已換回上一版;資料庫遷移不回滾" >&2 +else + echo "沒有上一版可以換回" >&2 +fi +$sudo journalctl -u "$service" -n 30 --no-pager 2>/dev/null >&2 || true +exit 1 diff --git a/check-env.sh b/check-env.sh new file mode 100755 index 0000000..474743c --- /dev/null +++ b/check-env.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# 部署步驟 1:檢查環境,工具與 Go 版本缺少或不足就安裝(curl、tar、systemctl、Go)。 +# .gitea/actions/deploy/check-env.sh +# 需要 GO_VERSION;其他環境變數見 common.sh。 +set -euo pipefail +. "$(dirname "$0")/common.sh" + +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +go_want=${GO_VERSION:?沒有指定 Go 版本:請在 Gitea 設定 Actions 變數 GO_VERSION(例如 1.27.1)} +go_want=${go_want#go} +go_dl=${GO_DL_URL:-https://go.dev/dl} + +missing=() +for tool in curl tar; do command -v "$tool" >/dev/null || missing+=("$tool"); done +[ ${#missing[@]} -eq 0 ] || install_pkgs "${missing[@]}" ca-certificates + +command -v systemctl >/dev/null || { echo "這台主機沒有 systemctl(systemd),無法部署服務" >&2; exit 1; } + +go_have=$(go env GOVERSION 2>/dev/null | sed 's/^go//' || true) +if [ -z "$go_have" ] || older "$go_have" "$go_want"; then + log "Go 版本不足(目前:${go_have:-沒有},需要:$go_want),下載安裝到 $go_root/go" + case "$(uname -m)" in + x86_64) goarch=amd64 ;; + aarch64 | arm64) goarch=arm64 ;; + *) echo "不支援的架構:$(uname -m)" >&2; exit 1 ;; + esac + curl -fsSL -o "$work/go.tgz" "$go_dl/go$go_want.linux-$goarch.tar.gz" + gosudo=$sudo + [ ! -w "$go_root" ] || gosudo= + $gosudo rm -rf "$go_root/go" + $gosudo tar -C "$go_root" -xzf "$work/go.tgz" + go_have=$(go env GOVERSION | sed 's/^go//') + older "$go_have" "$go_want" && { echo "安裝後 Go 版本仍不足:$go_have" >&2; exit 1; } +fi +log "環境檢查通過:Go $go_have" diff --git a/common.sh b/common.sh new file mode 100755 index 0000000..b34d61b --- /dev/null +++ b/common.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# shellcheck disable=SC2034 # 變數是給 source 它的步驟腳本用的 +# 部署各步驟共用的設定與小工具(被 source,不單獨執行)。環境變數: +# DEPLOY_NAME 應用程式名稱(預設是儲存庫名稱);執行檔、服務、套件、資料目錄的預設值都由它組出 +# DEPLOY_BIN 執行檔路徑(預設 /usr/local/bin/<名稱>) +# DEPLOY_SERVICE systemd 服務名稱(預設 <名稱>) +# DEPLOY_HEALTH_URL 健康檢查網址(預設 http://127.0.0.1:8080/api/health) +# DEPLOY_TIMEOUT 健康檢查最多等幾秒(預設 60) +# DEPLOY_PACKAGE go install 的套件(預設 <模組>/cmd/<名稱>) +# GITEA_URL Gitea 網址(預設 GITHUB_SERVER_URL;在 Actions 以外執行必填) +# GITEA_REPO Gitea 儲存庫 <擁有者>/<名稱>(預設 GITHUB_REPOSITORY;在 Actions 以外執行必填)。 +# 模組路徑是「Gitea 主機/擁有者/名稱」,GOPROXY 是「Gitea 網址/api/packages/擁有者/go」 +# DEPLOY_GOPROXY GOPROXY(預設由 GITEA_URL、GITEA_REPO 組出;不用主機自己的 GOPROXY) +# GO_VERSION 需要的 Go 版本,例如 1.27.1(check-env 必填) +# GO_DL_URL Go 下載網址(預設 https://go.dev/dl);GO_ROOT 安裝位置(預設 /usr/local) +# DEPLOY_ADDR 服務不存在、要安裝時的監聽位址(預設 0.0.0.0:8080) +# DEPLOY_DATA 服務不存在、要安裝時的資料目錄(預設 /var/lib/<名稱>) +# GITEA_TOKEN 套件庫需要驗證時的權杖(寫進臨時的 netrc,結束即刪除) +# 不是 root 時用 sudo -n。 + +# runner 的非互動 shell 不讀 ~/.profile,README 安裝 Go 的位置(/usr/local/go/bin)不在 PATH 裡 +go_root=${GO_ROOT:-/usr/local} +PATH=$PATH:$go_root/go/bin:$HOME/go/bin:/usr/local/bin +export PATH + +gitea_url=${GITEA_URL:-${GITHUB_SERVER_URL:?請設定 GITEA_URL(Gitea 網址)}} +gitea_repo=${GITEA_REPO:-${GITHUB_REPOSITORY:?請設定 GITEA_REPO(<擁有者>/<名稱>)}} +gitea_host=${gitea_url#*://}; gitea_host=${gitea_host%%/*} +module=$gitea_host/$gitea_repo +name=${DEPLOY_NAME:-${gitea_repo#*/}} +bin=${DEPLOY_BIN:-/usr/local/bin/$name} +staged="$bin.new" # install-binary 放新版的位置(和執行檔同目錄,activate 用改名原子替換) +prev="$bin.prev" +service=${DEPLOY_SERVICE:-$name} +health=${DEPLOY_HEALTH_URL:-http://127.0.0.1:8080/api/health} +timeout=${DEPLOY_TIMEOUT:-60} +package=${DEPLOY_PACKAGE:-$module/cmd/$name} +proxy=${DEPLOY_GOPROXY:-${gitea_url%/}/api/packages/${gitea_repo%%/*}/go} + +sudo= +[ "$(id -u)" = 0 ] || sudo="sudo -n" + +log() { echo "[deploy] $*"; } + +# $1 比 $2 舊就回傳 0 +older() { [ "$1" != "$2" ] && [ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | head -n 1)" = "$1" ]; } + +install_pkgs() { + log "安裝缺少的工具:$*" + if command -v apt-get >/dev/null; then + $sudo apt-get update -qq && $sudo apt-get install -y -qq "$@" + elif command -v dnf >/dev/null; then + $sudo dnf install -y -q "$@" + elif command -v yum >/dev/null; then + $sudo yum install -y -q "$@" + else + echo "找不到 apt-get、dnf、yum,請手動安裝:$*" >&2 + return 1 + fi +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..2ea5b40 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module gitea.jsc.idv.tw/actions/deploy + +go 1.27.1 diff --git a/icon.png b/icon.png new file mode 100644 index 0000000..f1857a5 Binary files /dev/null and b/icon.png differ diff --git a/icon.svg b/icon.svg new file mode 100644 index 0000000..5576a34 --- /dev/null +++ b/icon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/install-binary.sh b/install-binary.sh new file mode 100755 index 0000000..3513f37 --- /dev/null +++ b/install-binary.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# 部署步驟 2:用 go install 裝指定的版本(確切版本,不用 @latest),驗證執行檔回報的版本相同,放到 <執行檔>.new 等待 activate。 +# .gitea/actions/deploy/install-binary.sh <版本,例如 v0.4.9 或 v0.5.0-dev.2> +# 不碰正在執行的執行檔與服務,失敗時什麼都沒改。 +set -euo pipefail +. "$(dirname "$0")/common.sh" +version=${1:?用法:install-binary.sh <版本,例如 v0.4.9>} +want=${version#v} + +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +# 私有套件庫:不經公開的校驗資料庫 +if [ -n "${GITEA_TOKEN:-}" ]; then + host=$(printf %s "$proxy" | sed -E 's#^[a-z]+://([^/:]+).*#\1#') + printf 'machine %s login oauth2 password %s\n' "$host" "$GITEA_TOKEN" >"$work/netrc" + chmod 600 "$work/netrc" + export NETRC="$work/netrc" +fi +log "go install $package@$version" +GOBIN="$work/bin" GOPROXY="$proxy" GONOSUMDB="$gitea_host/*" GOTOOLCHAIN=local \ + go install "$package@$version" +new="$work/bin/$(basename "$package")" +[ -x "$new" ] || { echo "go install 沒有產生執行檔 $new" >&2; exit 1; } +got=$("$new" version) || { echo "新執行檔無法執行 version" >&2; exit 1; } +installed=$(printf %s "$got" | awk '{print $2}') +[ "$installed" = "$want" ] || { echo "新執行檔的版本不符:要 $want,實際是「$got」" >&2; exit 1; } + +$sudo mkdir -p "$(dirname "$bin")" +$sudo install -m 755 "$new" "$staged" +log "已安裝 $version 到 $staged" diff --git a/run.sh b/run.sh new file mode 100755 index 0000000..40f7afb --- /dev/null +++ b/run.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# 依序執行部署的三個步驟:check-env → install-binary → activate。版本是必填的確切版本,不會去拿 @latest。 +# .gitea/actions/deploy/run.sh <版本,例如 v0.4.9 或 v0.5.0-dev.2> +# 每個步驟都能單獨執行(見各檔案開頭),環境變數見 common.sh。CD 在沒有 git 的主機上用 curl 抓這個目錄的檔案再執行。 +set -euo pipefail +dir=$(cd "$(dirname "$0")" && pwd) +version=${1:?用法:run.sh <版本,例如 v0.4.9>} +case "$version" in v[0-9]*.[0-9]*.[0-9]*) ;; *) echo "版本格式不對:$version(要像 v0.4.9 或 v0.5.0-dev.2)" >&2; exit 1 ;; esac +bash "$dir/check-env.sh" +bash "$dir/install-binary.sh" "$version" +bash "$dir/activate.sh" "$version" diff --git a/test/deploy_host_test.go b/test/deploy_host_test.go new file mode 100644 index 0000000..9830f40 --- /dev/null +++ b/test/deploy_host_test.go @@ -0,0 +1,369 @@ +// .gitea/actions/deploy/ 部署腳本的黑箱測試:假的 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) + } +}