feat: create standalone native fnOS repository
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
package updater
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Client 通过共享 Unix Socket 调用 havline-updater sidecar。
|
||||
type Client struct {
|
||||
socketPath string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
func NewClient(socketPath string) *Client {
|
||||
socketPath = strings.TrimSpace(socketPath)
|
||||
transport := &http.Transport{
|
||||
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
var dialer net.Dialer
|
||||
return dialer.DialContext(ctx, "unix", socketPath)
|
||||
},
|
||||
}
|
||||
return &Client{
|
||||
socketPath: socketPath,
|
||||
http: &http.Client{Transport: transport, Timeout: 15 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) Enabled() bool {
|
||||
if c == nil || c.socketPath == "" {
|
||||
return false
|
||||
}
|
||||
info, err := os.Stat(c.socketPath)
|
||||
return err == nil && !info.IsDir()
|
||||
}
|
||||
|
||||
func (c *Client) Status(ctx context.Context) (Status, error) {
|
||||
var status Status
|
||||
if err := c.request(ctx, http.MethodGet, "/status", nil, &status); err != nil {
|
||||
return Status{}, err
|
||||
}
|
||||
return status, nil
|
||||
}
|
||||
|
||||
func (c *Client) Apply(ctx context.Context) (Status, error) {
|
||||
var status Status
|
||||
if err := c.request(ctx, http.MethodPost, "/apply", map[string]string{}, &status); err != nil {
|
||||
return Status{}, err
|
||||
}
|
||||
return status, nil
|
||||
}
|
||||
|
||||
func (c *Client) request(ctx context.Context, method, path string, payload any, result any) error {
|
||||
if !c.Enabled() {
|
||||
return fmt.Errorf("一键升级服务未启用")
|
||||
}
|
||||
var body io.Reader
|
||||
if payload != nil {
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
body = bytes.NewReader(data)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, "http://unix"+path, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if payload != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("updater 返回 HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(data)))
|
||||
}
|
||||
if result == nil {
|
||||
return nil
|
||||
}
|
||||
if err := json.Unmarshal(data, result); err != nil {
|
||||
return fmt.Errorf("updater 响应格式无效: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package updater
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Phase string
|
||||
|
||||
const (
|
||||
PhaseIdle Phase = "idle"
|
||||
PhaseScheduled Phase = "scheduled"
|
||||
PhaseRunning Phase = "running"
|
||||
PhaseSuccess Phase = "success"
|
||||
PhaseFailed Phase = "failed"
|
||||
)
|
||||
|
||||
// Status 是主程序与 havline-updater sidecar 共享的更新状态。
|
||||
type Status struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Mode string `json:"mode"`
|
||||
CurrentVersion string `json:"current_version,omitempty"`
|
||||
LatestVersion string `json:"latest_version,omitempty"`
|
||||
UpdateAvailable bool `json:"update_available"`
|
||||
Busy bool `json:"busy"`
|
||||
Phase Phase `json:"phase"`
|
||||
Message string `json:"message"`
|
||||
Log []string `json:"log,omitempty"`
|
||||
CheckedAt string `json:"checked_at,omitempty"`
|
||||
}
|
||||
|
||||
func busyPhase(phase Phase) bool {
|
||||
return phase == PhaseScheduled || phase == PhaseRunning
|
||||
}
|
||||
|
||||
// CompareVersions 比较形如 1.2.3、v1.2.3 的版本号;返回值大于 0 表示 a 更新。
|
||||
func CompareVersions(a, b string) int {
|
||||
left := parseVersion(a)
|
||||
right := parseVersion(b)
|
||||
length := len(left)
|
||||
if len(right) > length {
|
||||
length = len(right)
|
||||
}
|
||||
for index := 0; index < length; index++ {
|
||||
var lv, rv int
|
||||
if index < len(left) {
|
||||
lv = left[index]
|
||||
}
|
||||
if index < len(right) {
|
||||
rv = right[index]
|
||||
}
|
||||
if lv != rv {
|
||||
if lv > rv {
|
||||
return 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func parseVersion(value string) []int {
|
||||
clean := strings.TrimSpace(strings.TrimPrefix(value, "v"))
|
||||
if index := strings.IndexAny(clean, "-+"); index >= 0 {
|
||||
clean = clean[:index]
|
||||
}
|
||||
parts := strings.Split(clean, ".")
|
||||
out := make([]int, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
number, err := strconv.Atoi(part)
|
||||
if err != nil {
|
||||
out = append(out, 0)
|
||||
continue
|
||||
}
|
||||
out = append(out, number)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func validateSemver(value string) error {
|
||||
if value == "" {
|
||||
return fmt.Errorf("版本号为空")
|
||||
}
|
||||
parts := strings.Split(strings.TrimPrefix(value, "v"), ".")
|
||||
if len(parts) != 3 {
|
||||
return fmt.Errorf("版本号格式无效: %s", value)
|
||||
}
|
||||
for _, part := range parts {
|
||||
if _, err := strconv.Atoi(part); err != nil {
|
||||
return fmt.Errorf("版本号格式无效: %s", value)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package updater
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCompareVersions(t *testing.T) {
|
||||
cases := []struct {
|
||||
left string
|
||||
right string
|
||||
want int
|
||||
}{
|
||||
{"1.2.20", "1.2.19", 1},
|
||||
{"v1.2.19", "1.2.20", -1},
|
||||
{"1.3.0", "1.3.0", 0},
|
||||
{"1.2.21-beta.1", "1.2.21", 0},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got := CompareVersions(tc.left, tc.right)
|
||||
if got != tc.want {
|
||||
t.Fatalf("CompareVersions(%q, %q) = %d, want %d", tc.left, tc.right, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSemver(t *testing.T) {
|
||||
if err := validateSemver("1.2.21"); err != nil {
|
||||
t.Fatalf("合法版本被拒绝: %v", err)
|
||||
}
|
||||
for _, value := range []string{"", "1.2", "main", "1.2.x"} {
|
||||
if err := validateSemver(value); err == nil {
|
||||
t.Fatalf("非法版本未被拒绝: %q", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package updater
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRemoteVersionURLs(t *testing.T) {
|
||||
urls, err := remoteVersionURLs("http://example.com/mrlee/Havline.git", "main")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(urls) == 0 || !strings.Contains(urls[0], "/api/v1/repos/mrlee/Havline/contents/VERSION") {
|
||||
t.Fatalf("缺少 Gitea API 候选地址: %#v", urls)
|
||||
}
|
||||
if !strings.Contains(urls[1], "/mrlee/Havline/raw/branch/main/VERSION") {
|
||||
t.Fatalf("缺少 Gitea raw 候选地址: %#v", urls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRemoteVersion(t *testing.T) {
|
||||
if got, err := parseRemoteVersion([]byte("1.3.2\n")); err != nil || got != "1.3.2" {
|
||||
t.Fatalf("文本版本解析失败: got=%q err=%v", got, err)
|
||||
}
|
||||
payload, _ := json.Marshal(map[string]string{
|
||||
"encoding": "base64",
|
||||
"content": base64.StdEncoding.EncodeToString([]byte("1.3.2\n")),
|
||||
})
|
||||
if got, err := parseRemoteVersion(payload); err != nil || got != "1.3.2" {
|
||||
t.Fatalf("JSON 版本解析失败: got=%q err=%v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchRemoteVersionFromGiteaAPI(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v1/repos/mrlee/Havline/contents/VERSION" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{
|
||||
"encoding": "base64",
|
||||
"content": base64.StdEncoding.EncodeToString([]byte("1.3.2\n")),
|
||||
})
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
got, err := fetchRemoteVersion(context.Background(), server.URL+"/mrlee/Havline.git", "main")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != "1.3.2" {
|
||||
t.Fatalf("got %q, want 1.3.2", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
package updater
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const maxCommandOutput = 64 << 10
|
||||
|
||||
func (s *Server) runUpdate(ctx context.Context) error {
|
||||
s.mu.Lock()
|
||||
s.state.Phase = PhaseRunning
|
||||
s.state.Message = "正在准备升级"
|
||||
s.mu.Unlock()
|
||||
if err := s.ensureComposeFile(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
latest, err := s.latestVersion(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateSemver(latest); err != nil {
|
||||
return err
|
||||
}
|
||||
current, _ := readCurrentVersion(ctx, s.cfg.AppURL)
|
||||
if current != "" && CompareVersions(latest, current) <= 0 {
|
||||
return fmt.Errorf("当前已是最新版本 %s", current)
|
||||
}
|
||||
previousImage, _ := s.currentImage()
|
||||
s.logf("当前容器镜像:%s", previousImage)
|
||||
s.logf("目标版本:%s", latest)
|
||||
|
||||
if s.cfg.Mode == "local" {
|
||||
if err := s.prepareLocalSource(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := s.build(ctx, latest); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.recreate(ctx, latest); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.waitHealthy(ctx, latest); err != nil {
|
||||
s.rollback(previousImage)
|
||||
return fmt.Errorf("升级后健康检查失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) build(ctx context.Context, version string) error {
|
||||
s.logf("开始构建 havline:%s,这一步可能持续几分钟", version)
|
||||
buildCtx, cancel := context.WithTimeout(ctx, s.cfg.BuildTimeout)
|
||||
defer cancel()
|
||||
if _, err := s.compose(buildCtx, version, "build", s.cfg.Service); err != nil {
|
||||
return fmt.Errorf("docker compose build 失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) recreate(ctx context.Context, version string) error {
|
||||
s.logf("重建容器 %s", s.cfg.Service)
|
||||
upCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
|
||||
defer cancel()
|
||||
if _, err := s.compose(upCtx, version, "up", "-d", "--no-deps", "--force-recreate", s.cfg.Service); err != nil {
|
||||
return fmt.Errorf("docker compose up 失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) waitHealthy(ctx context.Context, expected string) error {
|
||||
s.logf("等待服务恢复并返回版本 %s", expected)
|
||||
deadline := time.Now().Add(s.cfg.HealthTimeout)
|
||||
for time.Now().Before(deadline) {
|
||||
checkCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
version, err := readCurrentVersion(checkCtx, s.cfg.AppURL)
|
||||
cancel()
|
||||
if err == nil && version == expected {
|
||||
s.logf("健康检查通过:%s", version)
|
||||
return nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(3 * time.Second):
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("等待 %s 超时", expected)
|
||||
}
|
||||
|
||||
func (s *Server) rollback(previousImage string) {
|
||||
version := imageTag(previousImage)
|
||||
if version == "" {
|
||||
s.logf("无法确定上一个镜像 tag,跳过自动回滚")
|
||||
return
|
||||
}
|
||||
s.logf("发现升级失败,尝试回滚到 havline:%s", version)
|
||||
rollbackCtx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
if _, err := s.compose(rollbackCtx, version, "up", "-d", "--no-deps", "--force-recreate", s.cfg.Service); err != nil {
|
||||
s.logf("自动回滚失败:%v", err)
|
||||
return
|
||||
}
|
||||
s.logf("已切回 havline:%s", version)
|
||||
}
|
||||
|
||||
func (s *Server) prepareLocalSource(ctx context.Context) error {
|
||||
if _, err := os.Stat(filepath.Join(s.cfg.ProjectDir, ".git")); err != nil {
|
||||
s.logf("项目目录不是 Git 仓库,跳过源码拉取")
|
||||
return nil
|
||||
}
|
||||
status, err := runCommand(ctx, s.cfg.ProjectDir, nil, "git", "status", "--porcelain")
|
||||
if err != nil {
|
||||
return fmt.Errorf("检查 Git 工作区失败:%w", err)
|
||||
}
|
||||
if strings.TrimSpace(status) != "" {
|
||||
return fmt.Errorf("本地源码存在未提交改动,已拒绝自动拉取")
|
||||
}
|
||||
s.logf("拉取远端源码")
|
||||
if _, err := runCommand(ctx, s.cfg.ProjectDir, nil, "git", "pull", "--ff-only", "origin", s.cfg.Branch); err != nil {
|
||||
return fmt.Errorf("git pull 失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) latestVersion(ctx context.Context) (string, error) {
|
||||
repoURL := strings.TrimSpace(s.cfg.RepoURL)
|
||||
if s.cfg.Mode == "local" {
|
||||
if remote, err := s.localRemoteURL(ctx); err == nil && strings.TrimSpace(remote) != "" {
|
||||
repoURL = remote
|
||||
}
|
||||
}
|
||||
localPath := filepath.Join(s.cfg.ProjectDir, "VERSION")
|
||||
if repoURL != "" {
|
||||
version, err := fetchRemoteVersion(ctx, repoURL, s.cfg.Branch)
|
||||
if err == nil {
|
||||
return version, nil
|
||||
}
|
||||
if s.cfg.Mode == "git" {
|
||||
return "", err
|
||||
}
|
||||
s.logf("读取远端版本失败,改用本地 VERSION:%v", err)
|
||||
}
|
||||
return readVersionFile(localPath)
|
||||
}
|
||||
|
||||
func (s *Server) localRemoteURL(ctx context.Context) (string, error) {
|
||||
if _, err := os.Stat(filepath.Join(s.cfg.ProjectDir, ".git")); err != nil {
|
||||
return "", err
|
||||
}
|
||||
checkCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
output, err := runCommand(checkCtx, s.cfg.ProjectDir, nil, "git", "config", "--get", "remote.origin.url")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(output), nil
|
||||
}
|
||||
|
||||
// fetchRemoteVersion 通过仓库 raw / API 地址读取 VERSION,避免为了检查版本克隆整个仓库。
|
||||
func fetchRemoteVersion(ctx context.Context, repoURL, branch string) (string, error) {
|
||||
urls, err := remoteVersionURLs(repoURL, branch)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var lastErr error
|
||||
for _, candidate := range urls {
|
||||
version, err := fetchVersionURL(ctx, candidate)
|
||||
if err == nil {
|
||||
return version, nil
|
||||
}
|
||||
lastErr = err
|
||||
}
|
||||
return "", fmt.Errorf("读取远端版本失败:%w", lastErr)
|
||||
}
|
||||
|
||||
func remoteVersionURLs(repoURL, branch string) ([]string, error) {
|
||||
parsed, err := url.Parse(strings.TrimSpace(repoURL))
|
||||
if err != nil || parsed.Host == "" {
|
||||
return nil, fmt.Errorf("仓库地址无效:%s", repoURL)
|
||||
}
|
||||
branch = strings.TrimSpace(branch)
|
||||
if branch == "" {
|
||||
branch = "main"
|
||||
}
|
||||
repoPath := strings.Trim(strings.TrimSuffix(parsed.Path, ".git"), "/")
|
||||
if repoPath == "" {
|
||||
return nil, fmt.Errorf("仓库地址缺少路径:%s", repoURL)
|
||||
}
|
||||
base := parsed.Scheme + "://" + parsed.Host
|
||||
urls := []string{
|
||||
fmt.Sprintf("%s/api/v1/repos/%s/contents/VERSION?ref=%s", base, repoPath, url.QueryEscape(branch)),
|
||||
fmt.Sprintf("%s/%s/raw/branch/%s/VERSION", base, repoPath, url.PathEscape(branch)),
|
||||
fmt.Sprintf("%s/%s/raw/%s/VERSION", base, repoPath, url.PathEscape(branch)),
|
||||
}
|
||||
if strings.EqualFold(parsed.Hostname(), "github.com") {
|
||||
urls = append([]string{fmt.Sprintf("https://raw.githubusercontent.com/%s/%s/VERSION", repoPath, url.PathEscape(branch))}, urls...)
|
||||
}
|
||||
return urls, nil
|
||||
}
|
||||
|
||||
func fetchVersionURL(ctx context.Context, rawURL string) (string, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return "", fmt.Errorf("%s: HTTP %d", rawURL, resp.StatusCode)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
version, err := parseRemoteVersion(data)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%s: %w", rawURL, err)
|
||||
}
|
||||
return version, nil
|
||||
}
|
||||
|
||||
func parseRemoteVersion(data []byte) (string, error) {
|
||||
text := strings.TrimSpace(string(data))
|
||||
if strings.HasPrefix(text, "{") {
|
||||
var payload struct {
|
||||
Content string `json:"content"`
|
||||
Encoding string `json:"encoding"`
|
||||
DownloadURL string `json:"download_url"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &payload); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if payload.Encoding == "base64" && payload.Content != "" {
|
||||
decoded, err := base64.StdEncoding.DecodeString(strings.TrimSpace(payload.Content))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
text = strings.TrimSpace(string(decoded))
|
||||
}
|
||||
}
|
||||
if err := validateSemver(text); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return text, nil
|
||||
}
|
||||
|
||||
func readVersionFile(path string) (string, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
version := strings.TrimSpace(string(data))
|
||||
if err := validateSemver(version); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return version, nil
|
||||
}
|
||||
|
||||
func readCurrentVersion(ctx context.Context, appURL string) (string, error) {
|
||||
url := strings.TrimRight(appURL, "/") + "/api/version"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
resp, err := (&http.Client{Timeout: 5 * time.Second}).Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return "", fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||
}
|
||||
var payload struct {
|
||||
Version string `json:"version"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&payload); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(payload.Version), nil
|
||||
}
|
||||
|
||||
func (s *Server) currentImage() (string, error) {
|
||||
output, err := runCommand(context.Background(), "", nil, "docker", "inspect", "--format", "{{.Config.Image}}", s.cfg.Service)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(output), nil
|
||||
}
|
||||
|
||||
func imageTag(image string) string {
|
||||
image = strings.TrimSpace(image)
|
||||
if image == "" {
|
||||
return ""
|
||||
}
|
||||
parts := strings.Split(image, ":")
|
||||
if len(parts) < 2 {
|
||||
return ""
|
||||
}
|
||||
return parts[len(parts)-1]
|
||||
}
|
||||
|
||||
func (s *Server) compose(ctx context.Context, version string, args ...string) (string, error) {
|
||||
plan, err := s.resolveComposePlan(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if plan.helper {
|
||||
return s.composeViaHelper(ctx, plan, version, args...)
|
||||
}
|
||||
fullArgs := append([]string{"compose", "--project-name", plan.projectName, "-f", plan.containerCompose}, args...)
|
||||
env := []string{"HAVLINE_VERSION=" + version}
|
||||
return runCommand(ctx, s.cfg.ProjectDir, env, "docker", fullArgs...)
|
||||
}
|
||||
|
||||
func (s *Server) composeViaHelper(ctx context.Context, plan composePlan, version string, args ...string) (string, error) {
|
||||
image, err := s.selfImage(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
helperArgs := []string{
|
||||
"run", "--rm", "--entrypoint", "docker",
|
||||
"-v", s.cfg.DockerSocket + ":/var/run/docker.sock",
|
||||
"-v", plan.hostProjectDir + ":/workspace",
|
||||
"-w", "/workspace",
|
||||
"-e", "HAVLINE_VERSION=" + version,
|
||||
image,
|
||||
"compose", "--project-name", plan.projectName, "-f", plan.helperComposePath,
|
||||
}
|
||||
helperArgs = append(helperArgs, args...)
|
||||
return runCommand(ctx, "", nil, "docker", helperArgs...)
|
||||
}
|
||||
|
||||
func (s *Server) selfImage(ctx context.Context) (string, error) {
|
||||
if s.cfg.SelfImage != "" {
|
||||
return s.cfg.SelfImage, nil
|
||||
}
|
||||
hostname, err := os.Hostname()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
output, err := runCommand(ctx, "", nil, "docker", "inspect", "--format", "{{.Config.Image}}", hostname)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("无法识别 updater 镜像:%w", err)
|
||||
}
|
||||
image := strings.TrimSpace(output)
|
||||
if image == "" {
|
||||
return "", fmt.Errorf("无法识别 updater 镜像")
|
||||
}
|
||||
return image, nil
|
||||
}
|
||||
|
||||
func runCommand(ctx context.Context, dir string, extraEnv []string, name string, args ...string) (string, error) {
|
||||
command := exec.CommandContext(ctx, name, args...)
|
||||
command.Dir = dir
|
||||
if len(extraEnv) > 0 {
|
||||
command.Env = append(os.Environ(), extraEnv...)
|
||||
}
|
||||
output, err := command.CombinedOutput()
|
||||
text := string(output)
|
||||
if len(text) > maxCommandOutput {
|
||||
text = text[len(text)-maxCommandOutput:]
|
||||
}
|
||||
if err != nil {
|
||||
return text, fmt.Errorf("%s: %w: %s", strings.Join(append([]string{name}, args...), " "), err, strings.TrimSpace(text))
|
||||
}
|
||||
return text, nil
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
package updater
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrBusy = errors.New("升级任务正在进行中")
|
||||
|
||||
var serviceNamePattern = regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`)
|
||||
|
||||
// Config 是 havline-updater sidecar 的运行配置。
|
||||
type Config struct {
|
||||
SocketPath string
|
||||
ProjectDir string
|
||||
ComposeFile string
|
||||
Service string
|
||||
Mode string
|
||||
RepoURL string
|
||||
Branch string
|
||||
AppURL string
|
||||
HostProjectDir string
|
||||
ProjectName string
|
||||
SelfImage string
|
||||
DockerSocket string
|
||||
BuildTimeout time.Duration
|
||||
HealthTimeout time.Duration
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
cfg Config
|
||||
logger *slog.Logger
|
||||
composePath string
|
||||
|
||||
mu sync.Mutex
|
||||
state Status
|
||||
lastChecked time.Time
|
||||
}
|
||||
|
||||
type composePlan struct {
|
||||
helper bool
|
||||
projectName string
|
||||
containerCompose string
|
||||
hostProjectDir string
|
||||
hostComposePath string
|
||||
helperComposePath string
|
||||
}
|
||||
|
||||
// NewServer 校验 sidecar 配置;参数不正确时拒绝启动。
|
||||
func NewServer(cfg Config, logger *slog.Logger) (*Server, error) {
|
||||
cfg.SocketPath = strings.TrimSpace(cfg.SocketPath)
|
||||
if cfg.SocketPath == "" {
|
||||
cfg.SocketPath = "/run/havline-updater/updater.sock"
|
||||
}
|
||||
if strings.TrimSpace(cfg.ProjectDir) == "" {
|
||||
cfg.ProjectDir = "/workspace"
|
||||
}
|
||||
if strings.TrimSpace(cfg.ComposeFile) == "" {
|
||||
cfg.ComposeFile = "docker-compose.yml"
|
||||
}
|
||||
if strings.TrimSpace(cfg.Service) == "" {
|
||||
cfg.Service = "havline"
|
||||
}
|
||||
if strings.TrimSpace(cfg.Mode) == "" {
|
||||
cfg.Mode = "local"
|
||||
}
|
||||
if strings.TrimSpace(cfg.Branch) == "" {
|
||||
cfg.Branch = "main"
|
||||
}
|
||||
if strings.TrimSpace(cfg.AppURL) == "" {
|
||||
cfg.AppURL = "http://havline:6893"
|
||||
}
|
||||
if strings.TrimSpace(cfg.DockerSocket) == "" {
|
||||
cfg.DockerSocket = "/var/run/docker.sock"
|
||||
}
|
||||
cfg.HostProjectDir = strings.TrimSpace(cfg.HostProjectDir)
|
||||
cfg.ProjectName = strings.TrimSpace(cfg.ProjectName)
|
||||
cfg.SelfImage = strings.TrimSpace(cfg.SelfImage)
|
||||
if cfg.BuildTimeout <= 0 {
|
||||
cfg.BuildTimeout = 30 * time.Minute
|
||||
}
|
||||
if cfg.HealthTimeout <= 0 {
|
||||
cfg.HealthTimeout = 3 * time.Minute
|
||||
}
|
||||
if cfg.Mode != "local" && cfg.Mode != "git" {
|
||||
return nil, fmt.Errorf("HAVLINE_UPDATE_MODE 只支持 local 或 git")
|
||||
}
|
||||
if !serviceNamePattern.MatchString(cfg.Service) {
|
||||
return nil, fmt.Errorf("HAVLINE_UPDATE_SERVICE 含非法字符")
|
||||
}
|
||||
composePath, err := resolveComposePath(cfg.ProjectDir, cfg.ComposeFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cfg.Mode == "git" && strings.TrimSpace(cfg.RepoURL) == "" {
|
||||
return nil, fmt.Errorf("git 模式必须设置 HAVLINE_UPDATE_REPO")
|
||||
}
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
return &Server{
|
||||
cfg: cfg,
|
||||
logger: logger,
|
||||
composePath: composePath,
|
||||
state: Status{
|
||||
Enabled: true,
|
||||
Mode: cfg.Mode,
|
||||
Phase: PhaseIdle,
|
||||
Message: "尚未检查更新",
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /status", s.handleStatus)
|
||||
mux.HandleFunc("POST /apply", s.handleApply)
|
||||
return mux
|
||||
}
|
||||
|
||||
// Serve 在共享 Unix Socket 上提供服务。
|
||||
func (s *Server) Serve(ctx context.Context) error {
|
||||
if err := os.MkdirAll(filepath.Dir(s.cfg.SocketPath), 0o750); err != nil {
|
||||
return err
|
||||
}
|
||||
_ = os.Remove(s.cfg.SocketPath)
|
||||
listener, err := net.Listen("unix", s.cfg.SocketPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
_ = listener.Close()
|
||||
_ = os.Remove(s.cfg.SocketPath)
|
||||
}()
|
||||
_ = os.Chmod(s.cfg.SocketPath, 0o660)
|
||||
|
||||
server := &http.Server{
|
||||
Handler: s.Handler(),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 30 * time.Second,
|
||||
}
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = server.Shutdown(shutdownCtx)
|
||||
}()
|
||||
err = server.Serve(listener)
|
||||
if errors.Is(err, http.ErrServerClosed) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, s.Status(r.Context()))
|
||||
}
|
||||
|
||||
func (s *Server) handleApply(w http.ResponseWriter, r *http.Request) {
|
||||
status, err := s.Apply(r.Context())
|
||||
if errors.Is(err, ErrBusy) {
|
||||
writeJSON(w, http.StatusConflict, status)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, status)
|
||||
}
|
||||
|
||||
func (s *Server) ensureComposeFile(ctx context.Context) error {
|
||||
_, err := s.resolveComposePlan(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Server) resolveComposePlan(ctx context.Context) (composePlan, error) {
|
||||
projectName, err := s.composeProjectName(ctx)
|
||||
if err != nil {
|
||||
return composePlan{}, err
|
||||
}
|
||||
info, err := os.Stat(s.composePath)
|
||||
if err == nil && !info.IsDir() {
|
||||
return composePlan{projectName: projectName, containerCompose: s.composePath}, nil
|
||||
}
|
||||
if err == nil && info.IsDir() {
|
||||
return composePlan{}, fmt.Errorf("Compose 路径是目录而不是文件:%s", s.composePath)
|
||||
}
|
||||
hostDir, hostComposePath, discoverErr := s.discoverHostCompose(ctx)
|
||||
if discoverErr == nil {
|
||||
helperPath, pathErr := helperComposePath(hostDir, hostComposePath)
|
||||
if pathErr == nil {
|
||||
return composePlan{
|
||||
helper: true,
|
||||
projectName: projectName,
|
||||
hostProjectDir: hostDir,
|
||||
hostComposePath: hostComposePath,
|
||||
helperComposePath: helperPath,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
return composePlan{}, fmt.Errorf("找不到 Compose 文件 %s,且无法自动定位宿主机目录;请设置 HAVLINE_UPDATE_HOST_DIR", s.composePath)
|
||||
}
|
||||
|
||||
func (s *Server) composeProjectName(ctx context.Context) (string, error) {
|
||||
projectName, err := s.dockerLabel(ctx, "com.docker.compose.project")
|
||||
projectName = strings.TrimSpace(projectName)
|
||||
if projectName != "" {
|
||||
return projectName, nil
|
||||
}
|
||||
if s.cfg.ProjectName != "" {
|
||||
return s.cfg.ProjectName, nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("无法读取现有容器的 Compose 项目标签:%w", err)
|
||||
}
|
||||
return "", fmt.Errorf("现有 havline 容器不是由 Compose 管理,无法安全一键升级;请按 Compose 方式重新部署")
|
||||
}
|
||||
|
||||
func (s *Server) discoverHostCompose(ctx context.Context) (string, string, error) {
|
||||
if s.cfg.HostProjectDir != "" && !isContainerPath(s.cfg.HostProjectDir, s.cfg.ProjectDir) {
|
||||
if !filepath.IsAbs(s.cfg.HostProjectDir) {
|
||||
return "", "", fmt.Errorf("HAVLINE_UPDATE_HOST_DIR 必须是绝对路径")
|
||||
}
|
||||
return s.cfg.HostProjectDir, filepath.Join(s.cfg.HostProjectDir, filepath.Base(s.cfg.ComposeFile)), nil
|
||||
}
|
||||
workingDir, _ := s.dockerLabel(ctx, "com.docker.compose.project.working_dir")
|
||||
configFiles, _ := s.dockerLabel(ctx, "com.docker.compose.project.config_files")
|
||||
hostDir := strings.TrimSpace(workingDir)
|
||||
hostCompose := chooseComposeFile(configFiles, filepath.Base(s.cfg.ComposeFile))
|
||||
if hostCompose == "" {
|
||||
if hostDir == "" || isContainerPath(hostDir, s.cfg.ProjectDir) {
|
||||
return "", "", fmt.Errorf("无法从容器标签读取宿主机 Compose 目录")
|
||||
}
|
||||
hostCompose = filepath.Join(hostDir, filepath.Base(s.cfg.ComposeFile))
|
||||
}
|
||||
if hostDir == "" || isContainerPath(hostDir, s.cfg.ProjectDir) {
|
||||
hostDir = filepath.Dir(hostCompose)
|
||||
}
|
||||
if !filepath.IsAbs(hostDir) || !filepath.IsAbs(hostCompose) {
|
||||
return "", "", fmt.Errorf("容器标签中的 Compose 路径不是绝对路径")
|
||||
}
|
||||
if isContainerPath(hostDir, s.cfg.ProjectDir) {
|
||||
return "", "", fmt.Errorf("容器标签只提供了容器内路径 %s,无法定位宿主机 Compose 目录", hostDir)
|
||||
}
|
||||
return filepath.Clean(hostDir), filepath.Clean(hostCompose), nil
|
||||
}
|
||||
|
||||
func isContainerPath(path, containerDir string) bool {
|
||||
path = filepath.Clean(strings.TrimSpace(path))
|
||||
containerDir = filepath.Clean(strings.TrimSpace(containerDir))
|
||||
if path == "" || containerDir == "" || path == "." {
|
||||
return false
|
||||
}
|
||||
return path == containerDir || strings.HasPrefix(path, containerDir+string(filepath.Separator))
|
||||
}
|
||||
|
||||
func (s *Server) dockerLabel(ctx context.Context, label string) (string, error) {
|
||||
format := fmt.Sprintf(`{{ index .Config.Labels %q }}`, label)
|
||||
checkCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
output, err := runCommand(checkCtx, "", nil, "docker", "inspect", "--format", format, s.cfg.Service)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(output), nil
|
||||
}
|
||||
|
||||
func chooseComposeFile(configFiles, expectedBase string) string {
|
||||
for _, item := range strings.Split(configFiles, ",") {
|
||||
path := strings.TrimSpace(item)
|
||||
if path == "" {
|
||||
continue
|
||||
}
|
||||
if filepath.Base(path) == expectedBase {
|
||||
return path
|
||||
}
|
||||
}
|
||||
for _, item := range strings.Split(configFiles, ",") {
|
||||
if path := strings.TrimSpace(item); path != "" {
|
||||
return path
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func helperComposePath(hostDir, hostCompose string) (string, error) {
|
||||
rel, err := filepath.Rel(hostDir, hostCompose)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
|
||||
return "", fmt.Errorf("Compose 文件不在宿主机项目目录内")
|
||||
}
|
||||
return filepath.Join("/workspace", rel), nil
|
||||
}
|
||||
|
||||
// Status 返回当前版本、远端版本和任务状态。
|
||||
func (s *Server) Status(ctx context.Context) Status {
|
||||
s.mu.Lock()
|
||||
if busyPhase(s.state.Phase) {
|
||||
status := cloneStatus(s.state)
|
||||
s.mu.Unlock()
|
||||
return status
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if err := s.ensureComposeFile(ctx); err != nil {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.state.UpdateAvailable = false
|
||||
s.state.Message = err.Error()
|
||||
s.state.CheckedAt = time.Now().UTC().Format(time.RFC3339)
|
||||
return cloneStatus(s.state)
|
||||
}
|
||||
s.mu.Lock()
|
||||
if !s.lastChecked.IsZero() && time.Since(s.lastChecked) < time.Minute {
|
||||
status := cloneStatus(s.state)
|
||||
s.mu.Unlock()
|
||||
return status
|
||||
}
|
||||
s.mu.Unlock()
|
||||
|
||||
checkCtx, cancel := context.WithTimeout(ctx, 20*time.Second)
|
||||
defer cancel()
|
||||
current, currentErr := readCurrentVersion(checkCtx, s.cfg.AppURL)
|
||||
latest, latestErr := s.latestVersion(checkCtx)
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.lastChecked = time.Now()
|
||||
s.state.CurrentVersion = current
|
||||
s.state.LatestVersion = latest
|
||||
s.state.UpdateAvailable = latest != "" && current != "" && CompareVersions(latest, current) > 0
|
||||
s.state.CheckedAt = time.Now().UTC().Format(time.RFC3339)
|
||||
switch {
|
||||
case currentErr != nil:
|
||||
s.state.Message = "无法读取当前运行版本:" + currentErr.Error()
|
||||
case latestErr != nil:
|
||||
s.state.Message = "无法读取远端最新版本:" + latestErr.Error()
|
||||
case s.state.UpdateAvailable:
|
||||
s.state.Message = fmt.Sprintf("发现新版本 %s,当前 %s", latest, current)
|
||||
default:
|
||||
s.state.Message = "当前已是最新版本"
|
||||
}
|
||||
return cloneStatus(s.state)
|
||||
}
|
||||
|
||||
// Apply 立即返回排队状态,后台完成构建、重建、健康检查和必要回滚。
|
||||
func (s *Server) Apply(_ context.Context) (Status, error) {
|
||||
s.mu.Lock()
|
||||
if busyPhase(s.state.Phase) {
|
||||
status := cloneStatus(s.state)
|
||||
s.mu.Unlock()
|
||||
return status, ErrBusy
|
||||
}
|
||||
s.state.Phase = PhaseScheduled
|
||||
s.state.Busy = true
|
||||
s.state.Message = "升级任务已排队,即将重启 Havline"
|
||||
s.state.Log = []string{"升级任务已排队"}
|
||||
status := cloneStatus(s.state)
|
||||
s.mu.Unlock()
|
||||
go s.runScheduled()
|
||||
return status, nil
|
||||
}
|
||||
|
||||
func (s *Server) runScheduled() {
|
||||
time.Sleep(2 * time.Second)
|
||||
if err := s.runUpdate(context.Background()); err != nil {
|
||||
s.logf("升级失败:%v", err)
|
||||
s.finish(PhaseFailed, err.Error())
|
||||
return
|
||||
}
|
||||
s.finish(PhaseSuccess, "升级完成")
|
||||
}
|
||||
|
||||
func (s *Server) finish(phase Phase, message string) {
|
||||
s.mu.Lock()
|
||||
s.state.Phase = phase
|
||||
s.state.Busy = false
|
||||
s.state.Message = message
|
||||
s.lastChecked = time.Time{}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Server) logf(format string, args ...any) {
|
||||
line := fmt.Sprintf(format, args...)
|
||||
s.logger.Info(line, "module", "UPDATER")
|
||||
s.mu.Lock()
|
||||
s.state.Log = append(s.state.Log, line)
|
||||
if len(s.state.Log) > 200 {
|
||||
s.state.Log = s.state.Log[len(s.state.Log)-200:]
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func cloneStatus(status Status) Status {
|
||||
status.Log = append([]string(nil), status.Log...)
|
||||
return status
|
||||
}
|
||||
|
||||
func resolveComposePath(projectDir, composeFile string) (string, error) {
|
||||
dir, err := filepath.Abs(strings.TrimSpace(projectDir))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
path := strings.TrimSpace(composeFile)
|
||||
if !filepath.IsAbs(path) {
|
||||
path = filepath.Join(dir, path)
|
||||
}
|
||||
path = filepath.Clean(path)
|
||||
rel, err := filepath.Rel(dir, path)
|
||||
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
|
||||
return "", fmt.Errorf("compose 文件必须位于项目目录内")
|
||||
}
|
||||
switch filepath.Base(path) {
|
||||
case "docker-compose.yml", "docker-compose.hub.yml", "docker-compose.host.yml":
|
||||
return path, nil
|
||||
default:
|
||||
return "", fmt.Errorf("不支持的 compose 文件:%s", filepath.Base(path))
|
||||
}
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package updater
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestResolveComposePath(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
got, err := resolveComposePath(dir, "docker-compose.hub.yml")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := filepath.Join(dir, "docker-compose.hub.yml")
|
||||
if got != want {
|
||||
t.Fatalf("got %q, want %q", got, want)
|
||||
}
|
||||
if _, err := resolveComposePath(dir, "../docker-compose.yml"); err == nil {
|
||||
t.Fatal("路径上跳应被拒绝")
|
||||
}
|
||||
if _, err := resolveComposePath(dir, "compose.yml"); err == nil {
|
||||
t.Fatal("不在白名单中的 compose 文件应被拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewServerDefaultsAndValidation(t *testing.T) {
|
||||
server, err := NewServer(Config{
|
||||
ProjectDir: t.TempDir(),
|
||||
ComposeFile: "docker-compose.yml",
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !server.state.Enabled || server.cfg.Mode != "local" {
|
||||
t.Fatalf("默认状态不正确: %#v", server.state)
|
||||
}
|
||||
if _, err := NewServer(Config{ProjectDir: t.TempDir(), Mode: "invalid"}, nil); err == nil {
|
||||
t.Fatal("非法 mode 应被拒绝")
|
||||
}
|
||||
if _, err := NewServer(Config{ProjectDir: t.TempDir(), Mode: "git"}, nil); err == nil {
|
||||
t.Fatal("git 模式缺少 RepoURL 应被拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureComposeFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
server, err := NewServer(Config{ProjectDir: dir, ComposeFile: "docker-compose.yml", ProjectName: "havline"}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := server.ensureComposeFile(context.Background()); err == nil {
|
||||
t.Fatal("缺少 compose 文件时应返回错误")
|
||||
}
|
||||
path := filepath.Join(dir, "docker-compose.yml")
|
||||
if err := os.WriteFile(path, []byte("services: {}\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := server.ensureComposeFile(context.Background()); err != nil {
|
||||
t.Fatalf("存在 compose 文件时不应报错: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveComposePlanUsesHostProjectDir(t *testing.T) {
|
||||
containerDir := t.TempDir()
|
||||
hostDir := t.TempDir()
|
||||
server, err := NewServer(Config{
|
||||
ProjectDir: containerDir,
|
||||
ComposeFile: "docker-compose.hub.yml",
|
||||
HostProjectDir: hostDir,
|
||||
ProjectName: "havline",
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plan, err := server.resolveComposePlan(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !plan.helper {
|
||||
t.Fatal("容器内看不到 Compose 文件时应使用 helper 模式")
|
||||
}
|
||||
if plan.helperComposePath != filepath.Join("/workspace", "docker-compose.hub.yml") {
|
||||
t.Fatalf("helper compose 路径不正确: %s", plan.helperComposePath)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsContainerPath(t *testing.T) {
|
||||
cases := []struct {
|
||||
path string
|
||||
want bool
|
||||
}{
|
||||
{"/workspace", true},
|
||||
{"/workspace/docker-compose.yml", true},
|
||||
{"/vol1/1000/Docker/mafrp", false},
|
||||
{"/vol1/1000/Docker/mafrp/docker-compose.yml", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := isContainerPath(tc.path, "/workspace"); got != tc.want {
|
||||
t.Fatalf("isContainerPath(%q) = %v, want %v", tc.path, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user