fix: use panel Python common catalog and track install jobs
This commit is contained in:
1 parent
248badd33e
commit
d7c007adc4
12 files changed
+202
-22
No files matched your search
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -17,6 +18,7 @@ import (
|
||||
"sea-vhost/internal/store"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -118,6 +120,49 @@ func TestResourceCRUDMySQL(t *testing.T) {
|
||||
must(e)
|
||||
must(db.UpdateRuntimeJob(ctx, last.ID, "completed", "verified", "test"))
|
||||
})
|
||||
t.Run("Python submission returns its job and uses only the source isolator", func(t *testing.T) {
|
||||
p := &pythonInstallPanel{Mock: panel.NewMock()}
|
||||
isolator := pythonInstallIsolation{Mock: isolation.Mock{Root: root}, panel: p}
|
||||
svc := service.NewProjects(db, p, isolator, "hosts.example.invalid", root, true, secret, "control.example.invalid")
|
||||
api := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour}, db, svc)
|
||||
r := httptest.NewRequest("POST", "https://control.example.invalid/api/v1/admin/runtime-environments/Python/install", strings.NewReader(`{"version":"3.13.1"}`))
|
||||
r.Header.Set("Origin", "https://control.example.invalid")
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
r.AddCookie(&http.Cookie{Name: "sea_session", Value: token})
|
||||
w := httptest.NewRecorder()
|
||||
api.Handler().ServeHTTP(w, r)
|
||||
var submitted struct {
|
||||
OK bool `json:"ok"`
|
||||
JobID uint64 `json:"jobId"`
|
||||
}
|
||||
if w.Code != 202 || json.Unmarshal(w.Body.Bytes(), &submitted) != nil || !submitted.OK || submitted.JobID == 0 {
|
||||
t.Fatalf("missing correlated installation task: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
workerCtx, stop := context.WithCancel(ctx)
|
||||
done := make(chan struct{})
|
||||
go func() { defer close(done); svc.RunRuntimeMaintenance(workerCtx) }()
|
||||
defer func() { stop(); <-done }()
|
||||
deadline := time.Now().Add(7 * time.Second)
|
||||
for {
|
||||
job, e := db.RuntimeJob(ctx, submitted.JobID)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if job.Status == "completed" {
|
||||
p.mu.Lock()
|
||||
calls, installed := p.sourceCalls, p.installed
|
||||
p.mu.Unlock()
|
||||
if calls != 1 || !installed || job.TargetVersion != "3.13.1" || !strings.Contains(job.Message, "已安装并核验") {
|
||||
t.Fatalf("unexpected Python installation result: %#v", job)
|
||||
}
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) || job.Status == "failed" || job.Status == "interrupted" {
|
||||
t.Fatalf("Python installation did not complete through isolator: %#v", job)
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
})
|
||||
account, err := db.CreateTenant(ctx, store.NewTenant{Slug: "crud-customer", Name: "CRUD 用户", Email: "crud-customer@example.invalid", DisplayName: "测试联系人", Password: "crud-customer-password-123", PlanID: 1})
|
||||
must(err)
|
||||
user, err := db.UserByLogin(ctx, "crud-customer@example.invalid")
|
||||
@@ -485,6 +530,47 @@ type pendingStatePanel struct {
|
||||
states map[int64]bool
|
||||
}
|
||||
|
||||
type pythonInstallPanel struct {
|
||||
*panel.Mock
|
||||
mu sync.Mutex
|
||||
installed bool
|
||||
sourceCalls int
|
||||
}
|
||||
|
||||
func (p *pythonInstallPanel) RuntimeEnvironments(ctx context.Context) ([]panel.RuntimeEnvironment, error) {
|
||||
items, err := p.Mock.RuntimeEnvironments(ctx)
|
||||
p.mu.Lock()
|
||||
installed := p.installed
|
||||
p.mu.Unlock()
|
||||
if installed {
|
||||
for i := range items {
|
||||
if items[i].Name == "Python" {
|
||||
items[i].Installed = append(items[i].Installed, "3.13.1")
|
||||
}
|
||||
}
|
||||
}
|
||||
return items, err
|
||||
}
|
||||
func (p *pythonInstallPanel) InstallRuntimeEnvironment(context.Context, string, string) error {
|
||||
return fmt.Errorf("unexpected panel installer; Python must use the source isolator")
|
||||
}
|
||||
|
||||
type pythonInstallIsolation struct {
|
||||
isolation.Mock
|
||||
panel *pythonInstallPanel
|
||||
}
|
||||
|
||||
func (i pythonInstallIsolation) InstallPythonRuntime(_ context.Context, version string) error {
|
||||
if version != "3.13.1" {
|
||||
return fmt.Errorf("unexpected Python version")
|
||||
}
|
||||
i.panel.mu.Lock()
|
||||
defer i.panel.mu.Unlock()
|
||||
i.panel.installed = true
|
||||
i.panel.sourceCalls++
|
||||
return nil
|
||||
}
|
||||
|
||||
type busyPatchPanel struct {
|
||||
*panel.Mock
|
||||
entered chan struct{}
|
||||
|
||||
@@ -49,11 +49,12 @@ func (s *Server) adminInstallRuntimeEnvironment(w http.ResponseWriter, r *http.R
|
||||
}
|
||||
input.Version = strings.TrimSpace(input.Version)
|
||||
user := currentUser(r)
|
||||
if err := s.projects.InstallRuntimeEnvironment(r.Context(), runtimeName, input.Version); err != nil {
|
||||
jobID, err := s.projects.SubmitRuntimeInstallation(r.Context(), runtimeName, input.Version)
|
||||
if err != nil {
|
||||
s.store.Log(r.Context(), nil, user.ID, "install", "runtime_environment", runtimeName+"/"+input.Version, requestClientIP(r), false, err.Error())
|
||||
writeError(w, http.StatusBadGateway, "运行环境安装任务提交失败")
|
||||
return
|
||||
}
|
||||
s.store.Log(r.Context(), nil, user.ID, "install", "runtime_environment", runtimeName+"/"+input.Version, requestClientIP(r), true, "提交 "+runtimeName+" "+input.Version+" 安装任务")
|
||||
writeJSON(w, http.StatusAccepted, map[string]bool{"ok": true})
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "jobId": jobID})
|
||||
}
|
||||
@@ -430,11 +430,9 @@ func (c *Client) pythonInstallations(ctx context.Context) ([]pythonInstallation,
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *Client) pythonLatestAvailableVersions(ctx context.Context) ([]string, error) {
|
||||
// The legacy Python manager list contains the first patch releases of many
|
||||
// branches (for example 3.12.0) and is not updated consistently. aaPanel's
|
||||
// project SDK catalog tracks the current stable patch of each branch even
|
||||
// when its bundled installer cannot fetch that release.
|
||||
func (c *Client) pythonCommonAvailableVersions(ctx context.Context) ([]string, error) {
|
||||
// Match Websites -> Python Project -> Common Versions exactly. The full
|
||||
// archive is not a fallback: it may advertise a different patch or branch.
|
||||
body, err := c.request(ctx, http.MethodPost, "/project/python/list_py_version/stype", nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read latest Python versions: %w", err)
|
||||
@@ -444,7 +442,6 @@ func (c *Client) pythonLatestAvailableVersions(ctx context.Context) ([]string, e
|
||||
Msg string `json:"msg"`
|
||||
SDK struct {
|
||||
Streamline []runtimeSDK `json:"streamline"`
|
||||
All []runtimeSDK `json:"all"`
|
||||
} `json:"sdk"`
|
||||
}
|
||||
if err = json.Unmarshal(body, &response); err != nil {
|
||||
@@ -453,13 +450,13 @@ func (c *Client) pythonLatestAvailableVersions(ctx context.Context) ([]string, e
|
||||
if failed(response.Status) {
|
||||
return nil, fmt.Errorf("read latest Python versions: %s", safeMessage(response.Msg))
|
||||
}
|
||||
versions := make([]string, 0, len(response.SDK.Streamline)+len(response.SDK.All))
|
||||
for _, item := range append(response.SDK.Streamline, response.SDK.All...) {
|
||||
versions := make([]string, 0, len(response.SDK.Streamline))
|
||||
for _, item := range response.SDK.Streamline {
|
||||
versions = append(versions, item.Version)
|
||||
}
|
||||
versions = latestPythonBranchVersions(versions)
|
||||
if len(versions) == 0 {
|
||||
return nil, errors.New("latest Python branch catalog is empty")
|
||||
return nil, errors.New("宝塔 Python 项目的常用版本列表为空,请在面板刷新版本后重试")
|
||||
}
|
||||
return versions, nil
|
||||
}
|
||||
@@ -813,7 +810,7 @@ func (c *Client) RuntimeEnvironments(ctx context.Context) ([]RuntimeEnvironment,
|
||||
items[2].ComponentInstallable = items[2].ComponentUpdateAvailable
|
||||
}
|
||||
installations, installedErr := c.pythonInstallations(ctx)
|
||||
available, availableErr := c.pythonLatestAvailableVersions(ctx)
|
||||
available, availableErr := c.pythonCommonAvailableVersions(ctx)
|
||||
if installedErr != nil || availableErr != nil {
|
||||
items[2].ComponentStatus, items[2].Detail = RuntimeComponentFailed, "Python 版本清单暂不可用"
|
||||
} else {
|
||||
|
||||
@@ -125,6 +125,38 @@ func TestRuntimeCatalogUsesAaPanelProjectRoutes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPythonAvailableVersionsUseCommonCatalogWithoutArchiveFallback(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name, body string
|
||||
want []string
|
||||
}{
|
||||
{"common differs from archive", `{"status":true,"sdk":{"streamline":[{"version":"3.12.15"},{"version":"3.13.17"}],"all":[{"version":"3.12.16"},{"version":"3.16.1"}]}}`, []string{"3.13.17", "3.12.15"}},
|
||||
{"no common catalog", `{"status":true,"sdk":{"all":[{"version":"3.12.16"}]}}`, nil},
|
||||
{"empty common catalog", `{"status":true,"sdk":{"streamline":[],"all":[{"version":"3.12.16"}]}}`, nil},
|
||||
{"unsafe or prerelease entries", `{"status":true,"sdk":{"streamline":[{"version":"3.13.17"},{"version":"3.14.0rc1"},{"version":"../../../tmp"},{"version":"3.12.15;id"}]}}`, []string{"3.13.17"}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/project/python/list_py_version/stype" || r.Method != http.MethodPost {
|
||||
t.Errorf("unexpected Python catalog request: %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(test.body))
|
||||
}))
|
||||
defer server.Close()
|
||||
client := NewClient(server.URL, "test-key", false, time.Second)
|
||||
got, err := client.pythonCommonAvailableVersions(context.Background())
|
||||
if test.want == nil {
|
||||
if err == nil || !strings.Contains(err.Error(), "常用版本") {
|
||||
t.Fatalf("missing common catalog was silently accepted: %v", err)
|
||||
}
|
||||
} else if err != nil || !reflect.DeepEqual(got, test.want) {
|
||||
t.Fatalf("got %v, %v; want %v", got, err, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeCapabilitiesDoNotFailAsAGroup(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
@@ -57,9 +57,14 @@ func (s *Projects) InstallRuntimeEnvironment(ctx context.Context, name, version
|
||||
if s.store == nil {
|
||||
return s.installRuntimeEnvironmentLegacy(ctx, name, version)
|
||||
}
|
||||
_, err := s.SubmitRuntimeInstallation(ctx, name, version)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Projects) SubmitRuntimeInstallation(ctx context.Context, name, version string) (uint64, error) {
|
||||
items, err := s.panel.RuntimeEnvironments(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
return 0, err
|
||||
}
|
||||
allowed := false
|
||||
for _, item := range items {
|
||||
@@ -68,10 +73,9 @@ func (s *Projects) InstallRuntimeEnvironment(ctx context.Context, name, version
|
||||
}
|
||||
}
|
||||
if !allowed {
|
||||
return errors.New("请选择清单中尚未安装的运行环境版本")
|
||||
return 0, errors.New("请选择清单中尚未安装的运行环境版本")
|
||||
}
|
||||
_, err = s.store.CreateRuntimeJob(ctx, store.RuntimeJob{Action: "install", Runtime: name, TargetVersion: version})
|
||||
return err
|
||||
return s.store.CreateRuntimeJob(ctx, store.RuntimeJob{Action: "install", Runtime: name, TargetVersion: version})
|
||||
}
|
||||
func (s *Projects) SubmitPHPPatch(ctx context.Context, branch, target string) (uint64, error) {
|
||||
items, err := s.panel.RuntimeEnvironments(ctx)
|
||||
@@ -232,6 +236,7 @@ func (s *Projects) executeRuntimeJob(parent context.Context, job store.RuntimeJo
|
||||
}
|
||||
if err == nil && !installed && !installing {
|
||||
if job.Runtime == "Python" {
|
||||
slog.Info("installing Python from verified source", "job_id", job.ID, "node_id", job.NodeID, "version", job.TargetVersion)
|
||||
err = s.isolation.InstallPythonRuntime(ctx, job.TargetVersion)
|
||||
} else {
|
||||
err = s.panel.InstallRuntimeEnvironment(ctx, job.Runtime, job.TargetVersion)
|
||||
@@ -268,7 +273,11 @@ func (s *Projects) executeRuntimeJob(parent context.Context, job store.RuntimeJo
|
||||
_ = s.store.EnqueueAdminNotification(finishCtx, "critical", "runtime", "运行环境维护失败", fmt.Sprintf("任务 #%d %s %s:%v", job.ID, job.Runtime, job.TargetVersion, err))
|
||||
return
|
||||
}
|
||||
_ = s.store.UpdateRuntimeJob(finishCtx, job.ID, "completed", "verified", "目标版本已核验;原本停止的站点保持停止,待启动后核验进程")
|
||||
message := "目标版本已核验;原本停止的站点保持停止,待启动后核验进程"
|
||||
if job.Action == "install" {
|
||||
message = job.Runtime + " " + job.TargetVersion + " 已安装并核验"
|
||||
}
|
||||
_ = s.store.UpdateRuntimeJob(finishCtx, job.ID, "completed", "verified", message)
|
||||
}
|
||||
|
||||
// Coordinate with host identity changes and unfinished site switches, not
|
||||
|
||||
Reference in new issue
Block a user