Files
vHost/backend/internal/httpapi/admin_batches.go
T

730 lines
26 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.
package httpapi
import (
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"net/mail"
"regexp"
"strconv"
"strings"
"time"
"sea-vhost/internal/scope"
"sea-vhost/internal/service"
"sea-vhost/internal/store"
)
type batchRow struct {
Name string `json:"name,omitempty"`
Slug string `json:"slug,omitempty"`
LoginName string `json:"loginName,omitempty"`
Email string `json:"email,omitempty"`
DisplayName string `json:"displayName,omitempty"`
Password string `json:"password,omitempty"`
AccountID uint64 `json:"accountId,omitempty"`
Account string `json:"account,omitempty"`
Owner string `json:"owner,omitempty"`
TenantID uint64 `json:"tenantId,omitempty"`
HostID uint64 `json:"hostId,omitempty"`
Host string `json:"host,omitempty"`
OwnershipVersion uint64 `json:"ownershipVersion,omitempty"`
CredentialMode string `json:"credentialMode,omitempty"`
StopServices *bool `json:"stopServices,omitempty"`
ResumeOwnership bool `json:"resumeOwnership,omitempty"`
NodeID uint64 `json:"nodeId,omitempty"`
PlanID uint64 `json:"planId,omitempty"`
Runtime string `json:"runtime,omitempty"`
Version string `json:"version,omitempty"`
RunPath string `json:"runPath,omitempty"`
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
SetExpiry bool `json:"setExpiry,omitempty"`
AutoSSL bool `json:"autoSSL,omitempty"`
}
type batchRequest struct {
RequestKey string `json:"requestKey"`
Operation string `json:"operation"`
Rows []batchRow `json:"rows"`
}
type batchPreviewRow struct {
Row int `json:"row"`
Label string `json:"label"`
Valid bool `json:"valid"`
Detail string `json:"detail"`
}
type batchResult struct {
ResourceID uint64 `json:"resourceId"`
Login string `json:"login,omitempty"`
Password string `json:"password,omitempty"`
HostLogin string `json:"hostLogin,omitempty"`
FTPHost string `json:"ftpHost,omitempty"`
FTPUsername string `json:"ftpUsername,omitempty"`
FTPPassword string `json:"ftpPassword,omitempty"`
DatabaseName string `json:"databaseName,omitempty"`
DatabaseUsername string `json:"databaseUsername,omitempty"`
DatabasePassword string `json:"databasePassword,omitempty"`
}
var batchKeyPattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
var batchHostNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{1,48}[a-z0-9]$`)
var batchOperations = map[string]bool{"create_users": true, "create_hosts": true, "assign_hosts": true, "host_subscription": true, "host_start": true, "host_stop": true, "host_password_reset": true, "user_enable": true, "user_disable": true}
func randomBatchKey() (string, error) {
var raw [16]byte
_, err := rand.Read(raw[:])
return hex.EncodeToString(raw[:]), err
}
func randomBatchPassword() (string, error) {
var raw [24]byte
_, err := rand.Read(raw[:])
return "Sv-" + base64.RawURLEncoding.EncodeToString(raw[:]) + "9a", err
}
func batchCipherLabel(ref, kind string, row int) string {
return fmt.Sprintf("admin-batch:%s:%s:%d", ref, kind, row)
}
func (s *Server) normalizeBatch(ctx context.Context, input *batchRequest) ([]batchPreviewRow, error) {
if !batchOperations[input.Operation] {
return nil, errors.New("不支持此批量操作")
}
limit := 200
if input.Operation == "create_users" {
limit = 100
}
if input.Operation == "create_hosts" {
limit = 50
}
if len(input.Rows) == 0 || len(input.Rows) > limit {
return nil, fmt.Errorf("该操作每批需要 1–%d 条数据", limit)
}
plans, err := s.store.ListPlans(ctx)
if err != nil {
return nil, err
}
if len(plans) == 0 {
return nil, errors.New("请先创建套餐")
}
hosts, err := s.store.ListAdminProjects(ctx)
if err != nil {
return nil, err
}
accounts, err := s.store.ListTenants(ctx)
if err != nil {
return nil, err
}
result := make([]batchPreviewRow, len(input.Rows))
seen := map[string]bool{}
for index := range input.Rows {
row := &input.Rows[index]
preview := batchPreviewRow{Row: index + 1, Valid: true}
var validation error
switch input.Operation {
case "create_users":
row.LoginName = strings.ToLower(strings.TrimSpace(row.LoginName))
if row.LoginName != "" {
if !tenantSlugPattern.MatchString(row.LoginName) {
validation = errors.New("登录账号格式无效")
}
row.Slug = accountSlug(row.LoginName)
if row.Name == "" {
row.Name = row.DisplayName
}
}
row.Slug = strings.ToLower(strings.TrimSpace(row.Slug))
row.Email = strings.ToLower(strings.TrimSpace(row.Email))
row.Name = strings.TrimSpace(row.Name)
row.DisplayName = strings.TrimSpace(row.DisplayName)
if row.PlanID == 0 {
row.PlanID = plans[0].ID
}
if row.DisplayName == "" {
row.DisplayName = row.Name
}
address, e := mail.ParseAddress(row.Email)
if !tenantSlugPattern.MatchString(row.Slug) || len([]rune(row.Name)) < 2 || len([]rune(row.Name)) > 120 || len([]rune(row.DisplayName)) < 2 || len([]rune(row.DisplayName)) > 80 {
validation = errors.New("用户标识、名称或显示名称格式无效")
} else if e != nil || address.Address != row.Email {
validation = errors.New("登录邮箱格式无效")
} else if row.Password != "" && (len(row.Password) < 12 || len(row.Password) > 72) {
validation = errors.New("密码应为 12–72 字节,留空将独立随机生成")
} else if _, e = s.store.Plan(ctx, row.PlanID); e != nil {
validation = errors.New("套餐不存在")
}
key := "user:" + row.Email
slugKey := "slug:" + row.Slug
if validation == nil && (seen[key] || seen[slugKey] || (row.LoginName != "" && seen["login:"+row.LoginName])) {
validation = errors.New("同批邮箱或用户标识重复")
}
seen[key] = true
seen[slugKey] = true
if row.LoginName != "" {
seen["login:"+row.LoginName] = true
}
if validation == nil {
exists, e := s.store.AccountIdentityExists(ctx, row.Slug, row.Email)
if e != nil {
validation = errors.New("无法核对现有账号")
} else if exists {
validation = errors.New("邮箱或用户标识已存在")
} else if row.LoginName != "" {
if exists, e = s.store.AccountIdentityExists(ctx, row.Slug, row.LoginName); e != nil || exists {
validation = errors.New("登录账号已存在或无法核对")
}
}
}
preview.Label = row.Email
case "create_hosts":
row.Name = strings.ToLower(strings.TrimSpace(row.Name))
row.Runtime = strings.TrimSpace(row.Runtime)
row.Version = strings.TrimSpace(row.Version)
if row.RunPath == "" {
row.RunPath = "/public"
}
if row.Owner != "" {
row.TenantID, validation = s.store.ResolveAccount(ctx, row.Owner)
}
if validation == nil && row.TenantID > 0 {
_, validation = s.store.TenantOwner(ctx, row.TenantID)
}
if validation == nil && !batchHostNamePattern.MatchString(row.Name) {
validation = errors.New("主机名称应为 3–50 位小写字母、数字或连字符")
}
if validation == nil {
node, e := s.store.Node(ctx, row.NodeID)
if e != nil || !node.Enabled {
validation = errors.New("节点不存在或未启用")
}
}
if validation == nil {
if _, e := s.store.Plan(ctx, row.PlanID); e != nil {
validation = errors.New("套餐不存在")
}
}
if validation == nil && !map[string]bool{"PHP": true, "Node.js": true, "Python": true, "Go": true, "Java": true}[row.Runtime] {
validation = errors.New("运行环境无效")
}
if validation == nil && (row.Version == "" || len(row.Version) > 80) {
validation = errors.New("请选择已安装版本")
}
if validation == nil && (strings.Contains(row.RunPath, "..") || strings.ContainsAny(row.RunPath, "\\\x00") || len(row.RunPath) > 255) {
validation = errors.New("运行目录无效")
}
preview.Label = row.Name
case "user_enable", "user_disable":
if row.Account != "" {
row.AccountID, validation = s.store.ResolveAnyAccount(ctx, row.Account)
}
found := false
for _, account := range accounts {
if account.ID == row.AccountID {
preview.Label = account.Name
found = true
}
}
if !found {
validation = errors.New("用户账号不存在")
}
key := "account:" + strconv.FormatUint(row.AccountID, 10)
if seen[key] {
validation = errors.New("同批账号重复")
}
seen[key] = true
default:
var host *store.AdminProject
for i := range hosts {
if (row.HostID > 0 && hosts[i].ID == row.HostID) || (row.Host != "" && (hosts[i].HostName == row.Host || strconv.FormatUint(hosts[i].ID, 10) == row.Host)) {
host = &hosts[i]
break
}
}
if host == nil {
validation = errors.New("主机不存在,请使用主机 ID 或随机主机名")
break
}
row.HostID = host.ID
preview.Label = host.HostName
if row.OwnershipVersion != 0 && row.OwnershipVersion != host.OwnershipVersion {
validation = errors.New("主机归属已变化,请刷新后重新预览")
}
row.OwnershipVersion = host.OwnershipVersion
if host.ManagementLocked && !(input.Operation == "assign_hosts" && row.ResumeOwnership) {
validation = store.ErrManagementLocked
}
if host.Status == "failed" || host.Status == "provisioning" {
validation = errors.New("主机尚未完成开通,不能批量管理")
}
key := "host:" + strconv.FormatUint(row.HostID, 10)
if seen[key] {
validation = errors.New("同批主机重复")
}
seen[key] = true
if input.Operation == "assign_hosts" {
if row.CredentialMode == "" {
row.CredentialMode = "preserve"
}
if row.StopServices == nil {
value := true
row.StopServices = &value
}
if row.CredentialMode != "preserve" && row.CredentialMode != "reset" {
validation = errors.New("凭据策略必须为 preserve 或 reset")
}
if row.Owner != "" {
row.TenantID, err = s.store.ResolveAccount(ctx, row.Owner)
if err != nil {
validation = err
}
}
if row.TenantID > 0 {
if _, e := s.store.TenantOwner(ctx, row.TenantID); e != nil {
validation = errors.New("目标用户不存在或已停用")
}
}
if host.ManagementLocked && row.ResumeOwnership {
pending, e := s.store.OwnershipChange(ctx, host.ID)
matches := pending.TargetOwnerID == nil && row.TenantID == 0 || pending.TargetOwnerID != nil && *pending.TargetOwnerID == row.TenantID
if e != nil || pending.State != "pending" || !matches || pending.ExpectedVersion != row.OwnershipVersion || pending.CredentialMode != row.CredentialMode || pending.StopServices != *row.StopServices {
validation = errors.New("恢复操作必须使用未完成任务原有的目标用户、凭据和停站策略")
}
}
}
if input.Operation == "host_subscription" {
if row.PlanID == 0 {
row.PlanID = host.PlanID
}
if _, e := s.store.Plan(ctx, row.PlanID); e != nil {
validation = errors.New("套餐不存在")
}
if !row.SetExpiry {
row.ExpiresAt = host.ExpiresAt
}
}
}
if row.ExpiresAt != nil && (row.ExpiresAt.Year() < 2000 || row.ExpiresAt.Year() > 9999) {
validation = errors.New("到期时间超出允许范围")
}
if preview.Label == "" {
preview.Label = fmt.Sprintf("第 %d 条", index+1)
}
if validation != nil {
preview.Valid = false
preview.Detail = validation.Error()
} else {
preview.Detail = "可以执行"
if input.Operation == "assign_hosts" {
credential := "保留三类密码(旧持有者仍可登录主机、FTP 和数据库)"
if row.CredentialMode == "reset" {
credential = "随机重置主机、FTP、数据库密码并断开旧连接"
}
state := "先停止全部网站"
if row.StopServices != nil && !*row.StopServices {
state = "保持网站当前运行状态"
}
preview.Detail = state + ";" + credential + ";注销旧主机管理会话"
for _, host := range hosts {
if host.ID == row.HostID && !host.ManagementLocked && ((host.OwnerTenantID == nil && row.TenantID == 0) || (host.OwnerTenantID != nil && *host.OwnerTenantID == row.TenantID)) {
preview.Detail = "归属相同,将跳过,不停站也不重置密码"
break
}
}
}
}
result[index] = preview
}
return result, nil
}
func (s *Server) adminBatchPreview(w http.ResponseWriter, r *http.Request) {
var input batchRequest
if decodeJSON(r, &input) != nil {
writeError(w, 400, "批量数据格式无效")
return
}
rows, err := s.normalizeBatch(r.Context(), &input)
if err != nil {
writeError(w, 422, err.Error())
return
}
writeJSON(w, 200, map[string]any{"rows": rows})
}
func (s *Server) adminBatches(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
jobs, err := s.store.AdminBatches(r.Context())
if err != nil {
writeError(w, 500, "无法读取批量任务")
return
}
writeJSON(w, 200, map[string]any{"batches": jobs})
return
}
var input batchRequest
if decodeJSON(r, &input) != nil || !batchKeyPattern.MatchString(input.RequestKey) {
writeError(w, 400, "批量数据或请求标识无效")
return
}
original, _ := json.Marshal(input)
mac := hmac.New(sha256.New, []byte(s.cfg.SessionSecret))
_, _ = mac.Write([]byte("admin-batch-request\x00"))
_, _ = mac.Write(original)
digest := hex.EncodeToString(mac.Sum(nil))
existing, e := s.store.ExistingAdminBatch(r.Context(), input.RequestKey, digest)
if e != nil {
writeError(w, 409, e.Error())
return
}
if existing > 0 {
job, e := s.store.AdminBatch(r.Context(), existing, false)
if e != nil {
writeError(w, 500, "无法读取已有批次")
return
}
writeJSON(w, 202, map[string]any{"batch": job})
return
}
rows, err := s.normalizeBatch(r.Context(), &input)
if err != nil {
writeError(w, 422, err.Error())
return
}
ref, err := randomBatchKey()
if err != nil {
writeError(w, 500, "无法建立批量任务")
return
}
items := make([]store.AdminBatchItem, len(rows))
valid := 0
for index, preview := range rows {
item := store.AdminBatchItem{Row: index + 1, Label: preview.Label, State: "pending"}
if !preview.Valid {
item.State = "failed"
item.Detail = preview.Detail
} else {
valid++
if input.Operation != "create_users" && input.Operation != "create_hosts" {
target := input.Rows[index].HostID
if input.Operation == "user_enable" || input.Operation == "user_disable" {
target = input.Rows[index].AccountID
}
if target > 0 {
item.ResourceID = &target
}
}
}
raw, _ := json.Marshal(input.Rows[index])
cipher, e := s.secretBox.Seal(batchCipherLabel(ref, "input", index+1), string(raw))
if e != nil {
writeError(w, 500, "无法加密任务数据")
return
}
item.InputCipher = cipher
items[index] = item
}
if valid == 0 {
writeJSON(w, 422, map[string]any{"error": map[string]string{"message": "没有可执行的条目,请先修正预览错误"}, "rows": rows})
return
}
id, err := s.store.CreateAdminBatch(r.Context(), currentUser(r).ID, input.RequestKey, digest, input.Operation, ref, items)
if err != nil {
status := 422
if errors.Is(err, store.ErrBatchKeyConflict) {
status = 409
}
writeError(w, status, err.Error())
return
}
s.store.Log(r.Context(), nil, currentUser(r).ID, "create", "admin_batch", strconv.FormatUint(id, 10), requestClientIP(r), true, fmt.Sprintf("提交批量任务 %s,共 %d 项", input.Operation, len(rows)))
job, err := s.store.AdminBatch(r.Context(), id, false)
if err != nil {
writeError(w, 500, "任务已保存,请刷新任务列表")
return
}
writeJSON(w, 202, map[string]any{"batch": job})
}
func (s *Server) adminBatch(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.PathValue("batchID"), 10, 64)
if err != nil || id == 0 {
writeError(w, 400, "批次编号无效")
return
}
job, err := s.store.AdminBatch(r.Context(), id, false)
if err != nil {
writeError(w, 404, "批次不存在")
return
}
writeJSON(w, 200, map[string]any{"batch": job})
}
func (s *Server) adminCancelBatch(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.ParseUint(r.PathValue("batchID"), 10, 64)
if id == 0 {
writeError(w, 400, "批次编号无效")
return
}
if err := s.store.CancelAdminBatch(r.Context(), id); err != nil {
writeError(w, 500, "无法取消任务")
return
}
_ = s.store.RefreshAdminBatches(r.Context())
s.store.Log(r.Context(), nil, currentUser(r).ID, "cancel", "admin_batch", strconv.FormatUint(id, 10), requestClientIP(r), true, "取消批次未执行项,执行中条目继续完成")
w.WriteHeader(204)
}
func (s *Server) adminBatchDownload(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.ParseUint(r.PathValue("batchID"), 10, 64)
job, err := s.store.AdminBatch(r.Context(), id, true)
if err != nil {
writeError(w, 404, "批次不存在")
return
}
if job.Pending > 0 {
writeError(w, 409, "请等待批次执行完成再下载")
return
}
if job.SecretsExpireAt == nil || !job.SecretsExpireAt.After(time.Now()) {
writeError(w, 410, "批次凭据已过期;FTP 和数据库凭据仍可在对应主机查看,登录密码可重置")
return
}
type downloadItem struct {
Row int `json:"row"`
Label string `json:"label"`
State string `json:"state"`
ResourceID *uint64 `json:"resourceId,omitempty"`
Detail string `json:"detail"`
Result *batchResult `json:"result,omitempty"`
}
items := make([]downloadItem, 0, len(job.Items))
for _, item := range job.Items {
record := downloadItem{Row: item.Row, Label: item.Label, State: item.State, ResourceID: item.ResourceID, Detail: item.Detail}
if len(item.ResultCipher) > 0 {
var result batchResult
raw, e := s.secretBox.Open(batchCipherLabel(job.SecretRef, "result", item.Row), item.ResultCipher)
if e != nil || json.Unmarshal([]byte(raw), &result) != nil {
writeError(w, 500, "无法解密批次结果")
return
}
record.Result = &result
}
items = append(items, record)
}
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="sea-vhost-batch-%d.json"`, id))
job.Items = nil
writeJSON(w, 200, map[string]any{"format": "sea-vhost.batch-result", "version": 1, "batch": job, "items": items})
s.store.Log(r.Context(), nil, currentUser(r).ID, "download", "admin_batch", strconv.FormatUint(id, 10), requestClientIP(r), true, "下载批次凭据结果")
}
// RunAdminBatches runs on the controller; the browser never drives the queue.
func (s *Server) RunAdminBatches(ctx context.Context) {
var release func()
for ctx.Err() == nil {
var err error
release, err = s.store.LockBatchWorker(ctx)
if err == nil {
break
}
select {
case <-ctx.Done():
return
case <-time.After(5 * time.Second):
}
}
if release == nil {
return
}
defer release()
go s.runIntegrationWebhooks(ctx)
if err := s.store.RecoverAdminBatches(ctx); err != nil {
slog.Error("batch recovery failed", "error", err)
return
}
for ctx.Err() == nil {
_ = s.store.RefreshAdminBatches(ctx)
job, item, err := s.store.NextAdminBatchItem(ctx)
if err != nil {
if !errors.Is(err, sql.ErrNoRows) && ctx.Err() == nil {
slog.Error("batch queue read failed", "error", err)
}
select {
case <-ctx.Done():
return
case <-time.After(time.Second):
}
continue
}
s.executeBatchItem(ctx, job, item)
}
}
func (s *Server) executeBatchItem(parent context.Context, job store.AdminBatch, item store.AdminBatchItem) {
ctx, cancel := context.WithTimeout(scope.WithBatchItem(parent, item.ID), 10*time.Minute)
defer cancel()
state, detail := "succeeded", "已完成"
resource := uint64(0)
var result batchResult
administrator, err := s.store.UserByID(ctx, job.AdministratorID)
apiKey, keyErr := s.store.BatchIntegrationKey(ctx, job.ID)
if keyErr != nil || (apiKey > 0 && !s.store.IntegrationKeyActive(ctx, apiKey)) {
err = errors.New("对接 API 密钥已吊销、过期或不可用")
}
if err != nil || administrator.Role != "admin" {
err = errors.New("创建该批次的管理员已不可用")
detail = err.Error()
} else {
var raw string
raw, err = s.secretBox.Open(batchCipherLabel(job.SecretRef, "input", item.Row), item.InputCipher)
var row batchRow
if err == nil {
err = json.Unmarshal([]byte(raw), &row)
}
if err == nil {
result, err = s.performBatchRow(ctx, job.Operation, row)
resource = result.ResourceID
if err == nil && job.Operation == "assign_hosts" {
detail = fmt.Sprintf("主机 #%d → 用户 #%d(0 为未绑定);凭据 %s;停站 %t", row.HostID, row.TenantID, row.CredentialMode, row.StopServices == nil || *row.StopServices)
}
}
if err != nil {
detail = "执行未完成,请核对目标资源及管理员审计"
if errors.Is(err, service.ErrOwnershipIncomplete) {
detail = err.Error()
}
}
}
var cipher []byte
if err == nil {
raw, _ := json.Marshal(result)
cipher, err = s.secretBox.Seal(batchCipherLabel(job.SecretRef, "result", item.Row), string(raw))
if err != nil {
detail = "操作已执行但凭据保存未完成,需按资源 ID 核验"
state = "uncertain"
}
}
if err != nil && state != "uncertain" {
state = "failed"
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
state = "uncertain"
detail = "执行超时或被中断,请核验资源,禁止直接重复开通"
}
}
save, cancelSave := context.WithTimeout(context.Background(), 15*time.Second)
defer cancelSave()
if e := s.store.FinishAdminBatchItem(save, item.ID, state, detail, cipher, resource); e != nil {
slog.Error("batch outcome persistence failed", "batch_id", job.ID, "item_id", item.ID)
}
s.store.Log(save, nil, job.AdministratorID, "execute", "admin_batch", strconv.FormatUint(job.ID, 10), "batch", state == "succeeded", fmt.Sprintf("批次 #%d 第 %d 项 %s:%s", job.ID, item.Row, job.Operation, detail))
}
func (s *Server) performBatchRow(ctx context.Context, operation string, row batchRow) (batchResult, error) {
var result batchResult
if operation == "create_users" {
if row.Password == "" {
var err error
row.Password, err = randomBatchPassword()
if err != nil {
return result, err
}
}
id, err := s.store.CreateTenant(ctx, store.NewTenant{LoginName: row.LoginName, Slug: row.Slug, Name: row.Name, Email: row.Email, DisplayName: row.DisplayName, Password: row.Password, PlanID: row.PlanID})
result.ResourceID = id
result.Login = row.LoginName
if result.Login == "" {
result.Login = row.Email
}
result.Password = row.Password
return result, err
}
if operation == "user_enable" || operation == "user_disable" {
result.ResourceID = row.AccountID
return result, s.store.SetAccountEnabled(ctx, row.AccountID, operation == "user_enable")
}
if operation == "create_hosts" {
ctx = scope.WithNode(ctx, row.NodeID)
release, err := s.projects.BeginRuntimeMutation(ctx)
if err != nil {
return result, err
}
defer release()
created, err := s.projects.CreateManagedHost(ctx, row.TenantID, service.CreateProjectInput{NodeID: row.NodeID, PlanID: row.PlanID, Name: row.Name, Runtime: row.Runtime, Version: row.Version, RunPath: row.RunPath, AutoSSL: row.AutoSSL})
if err != nil {
return result, err
}
result = batchResult{ResourceID: created.Project.ID, HostLogin: created.Credentials.HostLogin, Password: created.Credentials.HostPassword, FTPHost: created.Credentials.FTPHost, FTPUsername: created.Credentials.FTPUsername, FTPPassword: created.Credentials.FTPPassword, DatabaseName: created.Credentials.DatabaseName, DatabaseUsername: created.Credentials.DatabaseUsername, DatabasePassword: created.Credentials.DatabasePassword}
err = s.store.SetHostSubscription(ctx, created.Project.ID, row.PlanID, row.ExpiresAt)
return result, err
}
hosts, err := s.store.ListAdminProjects(ctx)
if err != nil {
return result, err
}
var host *store.AdminProject
for i := range hosts {
if hosts[i].ID == row.HostID {
host = &hosts[i]
break
}
}
if host == nil {
return result, store.ErrNotFound
}
result.ResourceID = host.ID
if host.ManualRecycledAt != nil {
return result, errors.New("主机已手动回收,请先恢复")
}
if host.ManagementLocked && !(operation == "assign_hosts" && row.ResumeOwnership) {
return result, store.ErrManagementLocked
}
if host.OwnershipVersion != row.OwnershipVersion {
return result, errors.New("主机归属已变更,拒绝执行旧批次")
}
ctx = scope.WithProject(ctx, host.ID, host.NodeID)
if operation == "host_subscription" {
return result, s.projects.ApplyHostSubscription(ctx, host.ID, row.PlanID, row.ExpiresAt)
}
if operation == "assign_hosts" {
stop := true
if row.StopServices != nil {
stop = *row.StopServices
}
mode := row.CredentialMode
if mode == "" {
mode = "preserve"
}
credentials, e := s.projects.ChangeHostOwner(ctx, host.ID, row.OwnershipVersion, row.TenantID, mode, stop, row.ResumeOwnership)
result.HostLogin = host.HostName
result.Password = credentials.HostPassword
result.FTPUsername = host.HostName
result.FTPHost = host.Domain
result.FTPPassword = credentials.FTPPassword
result.DatabaseName = host.HostName
result.DatabaseUsername = host.HostName
result.DatabasePassword = credentials.DatabasePassword
return result, e
}
if operation == "host_password_reset" {
result.HostLogin = host.HostName
result.Password, err = s.projects.ResetManagedHostLogin(ctx, host.ID, row.OwnershipVersion)
return result, err
}
release, err := s.projects.BeginRuntimeMutation(ctx)
if err != nil {
return result, err
}
defer release()
namespace, project := host.TenantID, host.ID
user := store.User{Role: "host", TenantID: &namespace, ProjectID: &project}
sites, err := s.store.ListSites(ctx, namespace, project)
if err != nil {
return result, err
}
for _, site := range sites {
if _, err = s.projects.SetSiteState(ctx, user, project, site.ID, operation == "host_start"); err != nil {
return result, err
}
}
return result, nil
}