feat: import Sea vHost single-server testing release
This commit is contained in:
commit
248badd33e
441 files changed
+63221
No files matched your search
@@ -0,0 +1,232 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"sea-vhost/internal/scope"
|
||||
"time"
|
||||
)
|
||||
|
||||
type AdminBatch struct {
|
||||
ID uint64 `json:"id"`
|
||||
AdministratorID uint64 `json:"administratorId"`
|
||||
Operation string `json:"operation"`
|
||||
State string `json:"state"`
|
||||
Total int `json:"total"`
|
||||
Succeeded int `json:"succeeded"`
|
||||
Failed int `json:"failed"`
|
||||
Uncertain int `json:"uncertain"`
|
||||
Pending int `json:"pending"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
FinishedAt *time.Time `json:"finishedAt,omitempty"`
|
||||
SecretsExpireAt *time.Time `json:"secretsExpireAt,omitempty"`
|
||||
SecretRef string `json:"-"`
|
||||
Items []AdminBatchItem `json:"items,omitempty"`
|
||||
}
|
||||
type AdminBatchItem struct {
|
||||
ID uint64 `json:"id"`
|
||||
BatchID uint64 `json:"batchId"`
|
||||
Row int `json:"row"`
|
||||
Label string `json:"label"`
|
||||
State string `json:"state"`
|
||||
ResourceID *uint64 `json:"resourceId,omitempty"`
|
||||
Detail string `json:"detail"`
|
||||
InputCipher []byte `json:"-"`
|
||||
ResultCipher []byte `json:"-"`
|
||||
}
|
||||
|
||||
var ErrBatchKeyConflict = errors.New("请求标识已用于其他批次,请刷新后重新预览")
|
||||
var ErrBatchQueueFull = errors.New("待处理批次过多,请等待现有任务完成")
|
||||
|
||||
func (s *Store) ExistingAdminBatch(ctx context.Context, key, digest string) (uint64, error) {
|
||||
var id uint64
|
||||
var expected string
|
||||
err := s.db.QueryRowContext(ctx, "SELECT id,input_digest FROM admin_batches WHERE request_key=?", key).Scan(&id, &expected)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return 0, nil
|
||||
}
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if expected != digest {
|
||||
return 0, ErrBatchKeyConflict
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateAdminBatch(ctx context.Context, administrator uint64, key, digest, operation, ref string, items []AdminBatchItem) (uint64, error) {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var adminID uint64
|
||||
if err = tx.QueryRowContext(ctx, "SELECT id FROM users WHERE id=? AND role='admin' AND status='active' FOR UPDATE", administrator).Scan(&adminID); err != nil {
|
||||
return 0, ErrNotFound
|
||||
}
|
||||
var id uint64
|
||||
var existing string
|
||||
err = tx.QueryRowContext(ctx, "SELECT id,input_digest FROM admin_batches WHERE request_key=?", key).Scan(&id, &existing)
|
||||
if err == nil {
|
||||
if digest != existing {
|
||||
return 0, ErrBatchKeyConflict
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
return 0, err
|
||||
}
|
||||
var queued int
|
||||
if err = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM admin_batches WHERE state IN ('queued','running')").Scan(&queued); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if queued >= 20 {
|
||||
return 0, ErrBatchQueueFull
|
||||
}
|
||||
var apiKey any
|
||||
if id := scope.IntegrationKey(ctx); id > 0 {
|
||||
var activeID uint64
|
||||
if err = tx.QueryRowContext(ctx, "SELECT id FROM integration_keys WHERE id=? AND administrator_id=? AND revoked_at IS NULL AND expires_at>UTC_TIMESTAMP() FOR UPDATE", id, administrator).Scan(&activeID); err != nil {
|
||||
return 0, ErrNotFound
|
||||
}
|
||||
apiKey = id
|
||||
}
|
||||
result, err := tx.ExecContext(ctx, "INSERT INTO admin_batches(request_key,input_digest,administrator_id,operation,total_count,secret_ref,integration_key_id) VALUES(?,?,?,?,?,?,?)", key, digest, administrator, operation, len(items), ref, apiKey)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
inserted, err := result.LastInsertId()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
id = uint64(inserted)
|
||||
for _, item := range items {
|
||||
if _, err = tx.ExecContext(ctx, "INSERT INTO admin_batch_items(batch_id,item_number,label,state,input_cipher,detail,resource_id) VALUES(?,?,?,?,?,?,?)", id, item.Row, item.Label, item.State, item.InputCipher, item.Detail, item.ResourceID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
const batchSummarySQL = `SELECT b.id,b.administrator_id,b.operation,b.state,b.total_count,b.created_at,b.finished_at,b.secrets_expire_at,b.secret_ref,COALESCE(SUM(i.state='succeeded'),0),COALESCE(SUM(i.state IN ('failed','cancelled')),0),COALESCE(SUM(i.state='uncertain'),0),COALESCE(SUM(i.state IN ('pending','running')),0) FROM admin_batches b LEFT JOIN admin_batch_items i ON i.batch_id=b.id`
|
||||
|
||||
func scanAdminBatch(row rowScanner) (AdminBatch, error) {
|
||||
var b AdminBatch
|
||||
err := row.Scan(&b.ID, &b.AdministratorID, &b.Operation, &b.State, &b.Total, &b.CreatedAt, &b.FinishedAt, &b.SecretsExpireAt, &b.SecretRef, &b.Succeeded, &b.Failed, &b.Uncertain, &b.Pending)
|
||||
return b, err
|
||||
}
|
||||
func (s *Store) AdminBatches(ctx context.Context) ([]AdminBatch, error) {
|
||||
rows, err := s.db.QueryContext(ctx, batchSummarySQL+" GROUP BY b.id ORDER BY b.id DESC LIMIT 100")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []AdminBatch{}
|
||||
for rows.Next() {
|
||||
b, e := scanAdminBatch(rows)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out = append(out, b)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (s *Store) AdminBatch(ctx context.Context, id uint64, includeSecrets bool) (AdminBatch, error) {
|
||||
b, err := scanAdminBatch(s.db.QueryRowContext(ctx, batchSummarySQL+" WHERE b.id=? GROUP BY b.id", id))
|
||||
if err != nil {
|
||||
return b, err
|
||||
}
|
||||
columns := "id,batch_id,item_number,label,state,resource_id,detail"
|
||||
if includeSecrets {
|
||||
columns += ",input_cipher,result_cipher"
|
||||
}
|
||||
rows, err := s.db.QueryContext(ctx, "SELECT "+columns+" FROM admin_batch_items WHERE batch_id=? ORDER BY item_number", id)
|
||||
if err != nil {
|
||||
return b, err
|
||||
}
|
||||
defer rows.Close()
|
||||
b.Items = []AdminBatchItem{}
|
||||
for rows.Next() {
|
||||
var item AdminBatchItem
|
||||
args := []any{&item.ID, &item.BatchID, &item.Row, &item.Label, &item.State, &item.ResourceID, &item.Detail}
|
||||
if includeSecrets {
|
||||
args = append(args, &item.InputCipher, &item.ResultCipher)
|
||||
}
|
||||
if err = rows.Scan(args...); err != nil {
|
||||
return b, err
|
||||
}
|
||||
b.Items = append(b.Items, item)
|
||||
}
|
||||
return b, rows.Err()
|
||||
}
|
||||
|
||||
// One advisory lock owns the queue across API processes. Restarted work is
|
||||
// marked uncertain rather than issuing a second potentially destructive call.
|
||||
func (s *Store) LockBatchWorker(ctx context.Context) (func(), error) {
|
||||
conn, err := s.db.Conn(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var locked int
|
||||
if err = conn.QueryRowContext(ctx, "SELECT GET_LOCK(CONCAT('svh:batch:',LEFT(SHA2(DATABASE(),256),40)),0)").Scan(&locked); err != nil || locked != 1 {
|
||||
conn.Close()
|
||||
if err == nil {
|
||||
err = errors.New("batch worker already active")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return func() {
|
||||
release, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_, _ = conn.ExecContext(release, "DO RELEASE_LOCK(CONCAT('svh:batch:',LEFT(SHA2(DATABASE(),256),40)))")
|
||||
conn.Close()
|
||||
}, nil
|
||||
}
|
||||
func (s *Store) RecoverAdminBatches(ctx context.Context) error {
|
||||
if _, err := s.db.ExecContext(ctx, "UPDATE admin_batch_items SET state='uncertain',detail='服务重启前该项正在执行,请按资源 ID 核验,禁止自动重复执行',finished_at=UTC_TIMESTAMP() WHERE state='running'"); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, "UPDATE admin_batches SET state='queued' WHERE state='running'")
|
||||
return err
|
||||
}
|
||||
func (s *Store) NextAdminBatchItem(ctx context.Context) (AdminBatch, AdminBatchItem, error) {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return AdminBatch{}, AdminBatchItem{}, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var b AdminBatch
|
||||
var item AdminBatchItem
|
||||
err = tx.QueryRowContext(ctx, `SELECT b.id,b.administrator_id,b.operation,b.secret_ref,i.id,i.item_number,i.label,i.input_cipher FROM admin_batches b JOIN admin_batch_items i ON i.batch_id=b.id WHERE b.state IN ('queued','running') AND i.state='pending' ORDER BY b.id,i.item_number LIMIT 1 FOR UPDATE`).Scan(&b.ID, &b.AdministratorID, &b.Operation, &b.SecretRef, &item.ID, &item.Row, &item.Label, &item.InputCipher)
|
||||
if err != nil {
|
||||
return b, item, err
|
||||
}
|
||||
item.BatchID = b.ID
|
||||
if _, err = tx.ExecContext(ctx, "UPDATE admin_batch_items SET state='running',started_at=UTC_TIMESTAMP() WHERE id=? AND state='pending'", item.ID); err != nil {
|
||||
return b, item, err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, "UPDATE admin_batches SET state='running' WHERE id=?", b.ID); err != nil {
|
||||
return b, item, err
|
||||
}
|
||||
return b, item, tx.Commit()
|
||||
}
|
||||
func (s *Store) FinishAdminBatchItem(ctx context.Context, id uint64, state, detail string, result []byte, resourceID uint64) error {
|
||||
_, err := s.db.ExecContext(ctx, "UPDATE admin_batch_items SET state=?,detail=?,result_cipher=?,resource_id=COALESCE(NULLIF(?,0),resource_id),finished_at=UTC_TIMESTAMP() WHERE id=? AND state='running'", state, detail, result, resourceID, id)
|
||||
return err
|
||||
}
|
||||
func (s *Store) RefreshAdminBatches(ctx context.Context) error {
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE admin_batches b SET b.state=CASE WHEN EXISTS(SELECT 1 FROM admin_batch_items i WHERE i.batch_id=b.id AND i.state IN ('failed','uncertain','cancelled')) THEN 'partial' ELSE 'completed' END,b.finished_at=COALESCE(b.finished_at,UTC_TIMESTAMP()),b.secrets_expire_at=COALESCE(b.secrets_expire_at,DATE_ADD(UTC_TIMESTAMP(),INTERVAL 24 HOUR)) WHERE b.state IN ('queued','running') AND NOT EXISTS(SELECT 1 FROM admin_batch_items i WHERE i.batch_id=b.id AND i.state IN ('pending','running'))`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx, `UPDATE admin_batch_items i JOIN admin_batches b ON b.id=i.batch_id SET i.input_cipher=NULL,i.result_cipher=NULL WHERE b.secrets_expire_at<=UTC_TIMESTAMP() AND (i.input_cipher IS NOT NULL OR i.result_cipher IS NOT NULL)`)
|
||||
return err
|
||||
}
|
||||
func (s *Store) CancelAdminBatch(ctx context.Context, id uint64) error {
|
||||
_, err := s.db.ExecContext(ctx, "UPDATE admin_batch_items SET state='cancelled',detail='管理员取消未执行项',finished_at=UTC_TIMESTAMP() WHERE batch_id=? AND state='pending'", id)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type AuditFilter struct {
|
||||
MaxID uint64
|
||||
Query, Action, Result string
|
||||
From, To *time.Time
|
||||
Limit, Page int
|
||||
}
|
||||
|
||||
func (s *Store) FilterAdminActivities(ctx context.Context, f AuditFilter) ([]AdminActivity, int, error) {
|
||||
if f.Limit < 1 || f.Limit > 500 {
|
||||
f.Limit = 100
|
||||
}
|
||||
if f.Page < 1 {
|
||||
f.Page = 1
|
||||
}
|
||||
where := " WHERE TRUE"
|
||||
args := []any{}
|
||||
if f.MaxID > 0 {
|
||||
where += " AND l.id<=?"
|
||||
args = append(args, f.MaxID)
|
||||
}
|
||||
if f.Query != "" {
|
||||
where += " AND INSTR(LOWER(CONCAT_WS(' ',a.display_name,t.name,l.action,l.resource_type,l.resource_id,l.ip_address,l.detail)),?)>0"
|
||||
args = append(args, strings.ToLower(f.Query))
|
||||
}
|
||||
if f.Action != "" {
|
||||
where += " AND l.action=?"
|
||||
args = append(args, f.Action)
|
||||
}
|
||||
if f.Result != "" {
|
||||
where += " AND l.success=?"
|
||||
args = append(args, f.Result == "success")
|
||||
}
|
||||
if f.From != nil {
|
||||
where += " AND l.created_at>=?"
|
||||
args = append(args, f.From.UTC())
|
||||
}
|
||||
if f.To != nil {
|
||||
where += " AND l.created_at<?"
|
||||
args = append(args, f.To.UTC())
|
||||
}
|
||||
joins := ` FROM operation_logs l LEFT JOIN tenants t ON t.id=l.tenant_id LEFT JOIN users a ON a.id=l.user_id LEFT JOIN users target ON target.id=l.impersonated_user_id`
|
||||
var total int
|
||||
if err := s.db.QueryRowContext(ctx, "SELECT COUNT(*)"+joins+where, args...).Scan(&total); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
args = append(args, f.Limit, (f.Page-1)*f.Limit)
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT l.id,COALESCE(a.display_name,t.name,''),l.action,l.resource_type,COALESCE(l.resource_id,''),COALESCE(l.ip_address,''),l.success,COALESCE(l.detail,''),l.created_at,l.administrator_id,l.impersonated_user_id,COALESCE(target.login_name,'')`+joins+where+" ORDER BY l.id DESC LIMIT ? OFFSET ?", args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]AdminActivity, 0)
|
||||
for rows.Next() {
|
||||
var item AdminActivity
|
||||
if err := rows.Scan(&item.ID, &item.TenantName, &item.Action, &item.ResourceType, &item.ResourceID, &item.IPAddress, &item.Success, &item.Detail, &item.CreatedAt, &item.AdministratorID, &item.ImpersonatedUserID, &item.ImpersonatedUserName); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return items, total, rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sea-vhost/internal/scope"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ControlTask struct {
|
||||
ID uint64 `json:"id"`
|
||||
NodeID uint64 `json:"nodeId"`
|
||||
ProjectID *uint64 `json:"projectId,omitempty"`
|
||||
Operation string `json:"operation"`
|
||||
State string `json:"state"`
|
||||
Detail string `json:"detail"`
|
||||
StartedAt time.Time `json:"startedAt"`
|
||||
FinishedAt *time.Time `json:"finishedAt,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Store) RecoverControlTasks(ctx context.Context) error {
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE control_tasks SET state='uncertain',detail='主控重启,需要核对被控实际状态',finished_at=UTC_TIMESTAMP() WHERE state='running'`)
|
||||
return err
|
||||
}
|
||||
func (s *Store) NodeHasUnresolvedTask(ctx context.Context, nodeID uint64) (bool, error) {
|
||||
var n int
|
||||
err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM control_tasks WHERE node_id=? AND state='uncertain' AND (project_id IS NULL OR ?=0 OR project_id=?)", nodeID, scope.Project(ctx), scope.Project(ctx)).Scan(&n)
|
||||
return n > 0, err
|
||||
}
|
||||
func (s *Store) ControlTasks(ctx context.Context, nodeID uint64) ([]ControlTask, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT id,node_id,project_id,operation,state,detail,started_at,finished_at FROM control_tasks WHERE node_id=? ORDER BY id DESC LIMIT 100`, nodeID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []ControlTask{}
|
||||
for rows.Next() {
|
||||
var t ControlTask
|
||||
if err = rows.Scan(&t.ID, &t.NodeID, &t.ProjectID, &t.Operation, &t.State, &t.Detail, &t.StartedAt, &t.FinishedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, t)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (s *Store) ResolveControlTask(ctx context.Context, nodeID, id uint64, note string) error {
|
||||
if len([]rune(note)) < 6 || len(note) > 400 {
|
||||
return errors.New("请记录实际核验结果(至少六个字)")
|
||||
}
|
||||
r, err := s.db.ExecContext(ctx, "UPDATE control_tasks SET state='failed',detail=?,finished_at=UTC_TIMESTAMP() WHERE id=? AND node_id=? AND state='uncertain'", "管理员已核验:"+note, id, nodeID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, _ := r.RowsAffected()
|
||||
if n != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package store
|
||||
|
||||
import "context"
|
||||
|
||||
// A single transaction prevents filing and routing changes from partially
|
||||
// succeeding, and treats saving an unchanged policy as a successful operation.
|
||||
func (s *Store) UpdateDomainPolicy(ctx context.Context, id uint64, mode, target, status, number, note string) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var found uint64
|
||||
if err = tx.QueryRowContext(ctx, `SELECT id FROM domains WHERE id=? AND kind='custom' FOR UPDATE`, id).Scan(&found); err != nil {
|
||||
return ErrNotFound
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `UPDATE domains SET resolution_mode=?,cname_target=NULLIF(?,''),filing_status=?,filing_number=NULLIF(?,''),filing_note=NULLIF(?,'') WHERE id=?`, mode, target, status, number, note, id); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package store
|
||||
import "context"
|
||||
func(s *Store)SetFTPEnabled(ctx context.Context,project uint64,enabled bool)error{_,e:=s.db.ExecContext(ctx,"UPDATE ftp_accounts SET enabled=? WHERE project_id=?",enabled,project);return e}
|
||||
func(s *Store)SetFTPPasswordCipher(ctx context.Context,project uint64,cipher []byte)error{_,e:=s.db.ExecContext(ctx,"UPDATE ftp_accounts SET password_ciphertext=? WHERE project_id=?",cipher,project);return e}
|
||||
@@ -0,0 +1,115 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"os"
|
||||
"sea-vhost/internal/scope"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHostOperationLogsMySQL(t *testing.T) {
|
||||
dsn := os.Getenv("SEA_TEST_MYSQL_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("dedicated MySQL schema not supplied")
|
||||
}
|
||||
config, err := mysql.ParseDSN(dsn)
|
||||
if err != nil || !strings.HasPrefix(config.DBName, "svh_cluster_test_") {
|
||||
t.Fatal("refusing a non-test schema")
|
||||
}
|
||||
db, err := Open(dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||
defer cancel()
|
||||
if err = db.Migrate(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plans, err := db.ListPlans(ctx)
|
||||
if err != nil || len(plans) == 0 {
|
||||
t.Fatal("missing plan", err)
|
||||
}
|
||||
tenants := []uint64{}
|
||||
for _, name := range []string{"audit-a", "audit-b"} {
|
||||
id, e := db.CreateTenant(ctx, NewTenant{Slug: name, Name: name, Email: name + "@example.invalid", DisplayName: "审计测试用户", Password: "integration-only-password-123", PlanID: plans[0].ID})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
tenants = append(tenants, id)
|
||||
}
|
||||
ownerA, err := db.UserByLogin(ctx, "audit-a@example.invalid")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ownerB, err := db.UserByLogin(ctx, "audit-b@example.invalid")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hosts := []uint64{}
|
||||
for i, name := range []string{"sv1111111111", "sv2222222222", "sv3333333333"} {
|
||||
tenant := tenants[0]
|
||||
if i == 2 {
|
||||
tenant = tenants[1]
|
||||
}
|
||||
id, e := db.InsertProject(ctx, NewProject{NodeID: 1, PlanID: plans[0].ID, TenantID: tenant, HostName: name, Slug: name, Runtime: "PHP", Version: "8.4", Path: "/www/wwwroot/seavHost/vHost/" + name, RunPath: "/public", Domain: name + ".example.invalid", ProcessLimit: 10, HostPasswordHash: "test-hash"})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
hosts = append(hosts, id)
|
||||
}
|
||||
result, err := db.db.ExecContext(ctx, `INSERT INTO users(tenant_id,project_id,login_name,email,display_name,password_hash,role) VALUES (?,?,?,?,?,?,'host')`, tenants[0], hosts[0], "audit-host", "audit-host@example.invalid", "主机测试账号", "test-hash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actor, _ := result.LastInsertId()
|
||||
userID := uint64(actor)
|
||||
a := scope.WithProject(ctx, hosts[0], 1)
|
||||
b := scope.WithProject(ctx, hosts[1], 1)
|
||||
db.LogEvent(a, &tenants[0], &ownerA.ID, "update", "site", "1", "127.0.0.1", true, "HOST_A_USER_ACTION")
|
||||
db.LogEvent(b, &tenants[0], &ownerA.ID, "update", "site", "2", "127.0.0.1", true, "HOST_B_MUST_NOT_LEAK")
|
||||
db.LogEvent(ctx, &tenants[0], &ownerA.ID, "update", "account", "", "127.0.0.1", true, "ACCOUNT_MUST_NOT_LEAK")
|
||||
db.LogEvent(ctx, &tenants[0], &userID, "login", "session", "", "127.0.0.1", true, "HOST_A_LOGIN")
|
||||
db.LogEvent(scope.WithProject(ctx, hosts[2], 1), &tenants[1], &ownerB.ID, "update", "site", "3", "127.0.0.1", true, "OTHER_TENANT_MUST_NOT_LEAK")
|
||||
db.LogEvent(a, &tenants[0], nil, "update", "site", "1", "127.0.0.1", true, "UNKNOWN_ACTOR_MUST_NOT_LEAK")
|
||||
items, err := db.Activities(a, tenants[0], 100)
|
||||
if err != nil || len(items) != 2 {
|
||||
t.Fatalf("host logs: %+v %v", items, err)
|
||||
}
|
||||
for _, item := range items {
|
||||
if item.ProjectID == nil || *item.ProjectID != hosts[0] || strings.Contains(item.Detail, "MUST_NOT_LEAK") {
|
||||
t.Fatalf("cross-host log: %+v", item)
|
||||
}
|
||||
}
|
||||
if items, err = db.Activities(ctx, tenants[0], 100); err != nil || len(items) != 4 {
|
||||
t.Fatalf("tenant logs: %d %v", len(items), err)
|
||||
}
|
||||
if items, err = db.Activities(a, tenants[1], 100); err != nil || len(items) != 0 {
|
||||
t.Fatalf("cross-tenant scope: %+v %v", items, err)
|
||||
}
|
||||
if _, err = db.db.ExecContext(ctx, `INSERT INTO operation_logs(tenant_id,user_id,action,resource_type,resource_id,success,detail) VALUES (?,?,'state','project',?,TRUE,'LEGACY_EXACT_HOST'),(?,?,'create','project',?,FALSE,'LEGACY_AMBIGUOUS_FAILED_CREATE')`, tenants[0], ownerA.ID, strconv.FormatUint(hosts[0], 10), tenants[0], ownerA.ID, strconv.FormatUint(hosts[0], 10)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.db.ExecContext(ctx, "DELETE FROM schema_migrations WHERE version='015_host_operation_logs.sql'"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = db.Migrate(ctx); err != nil {
|
||||
t.Fatalf("resume migration 015: %v", err)
|
||||
}
|
||||
if err = db.Migrate(ctx); err != nil {
|
||||
t.Fatalf("repeat migration: %v", err)
|
||||
}
|
||||
items, err = db.Activities(a, tenants[0], 100)
|
||||
if err != nil || len(items) != 3 {
|
||||
t.Fatalf("legacy host attribution: %+v %v", items, err)
|
||||
}
|
||||
for _, item := range items {
|
||||
if item.Detail == "LEGACY_AMBIGUOUS_FAILED_CREATE" {
|
||||
t.Fatal("ambiguous historical log was attributed to a host")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"sea-vhost/internal/scope"
|
||||
"time"
|
||||
)
|
||||
|
||||
type HostLifecycle struct {
|
||||
ProjectID, TenantID, NodeID uint64
|
||||
State string
|
||||
ExpiresAt, GraceUntil, PurgeAfter, BackupPurgeAfter *time.Time
|
||||
}
|
||||
|
||||
var ErrHostNotWritable = errors.New("主机已到期或身份核验未通过,请联系管理员")
|
||||
|
||||
func (s *Store) HostLifecycles(ctx context.Context) ([]HostLifecycle, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT id,tenant_id,node_id,lifecycle_state,expires_at,grace_until,purge_after,backup_purge_after FROM projects WHERE management_locked=FALSE AND lifecycle_state IN ('grace','recycle') ORDER BY id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []HostLifecycle{}
|
||||
for rows.Next() {
|
||||
var h HostLifecycle
|
||||
if err = rows.Scan(&h.ProjectID, &h.TenantID, &h.NodeID, &h.State, &h.ExpiresAt, &h.GraceUntil, &h.PurgeAfter, &h.BackupPurgeAfter); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, h)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (s *Store) AdvanceHostLifecycle(ctx context.Context, now time.Time) error {
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE projects SET lifecycle_state='grace',grace_until=DATE_ADD(expires_at,INTERVAL 3 DAY),purge_after=DATE_ADD(expires_at,INTERVAL 10 DAY),backup_purge_after=DATE_ADD(expires_at,INTERVAL 24 DAY) WHERE management_locked=FALSE AND lifecycle_state='active' AND expires_at IS NOT NULL AND expires_at<=?`, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx, `UPDATE projects SET lifecycle_state='recycle' WHERE management_locked=FALSE AND lifecycle_state='grace' AND grace_until<=?`, now)
|
||||
return err
|
||||
}
|
||||
func (s *Store) HostWritable(ctx context.Context, tenantID uint64) error {
|
||||
if scope.Project(ctx) == 0 {
|
||||
return nil
|
||||
}
|
||||
var expired, locked bool
|
||||
err := s.db.QueryRowContext(ctx, `SELECT management_locked,NOT identity_verified OR lifecycle_state<>'active' OR (expires_at IS NOT NULL AND expires_at<=UTC_TIMESTAMP()) FROM projects WHERE id=? AND tenant_id=?`, scope.Project(ctx), tenantID).Scan(&locked, &expired)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if locked {
|
||||
return ErrManagementLocked
|
||||
}
|
||||
if expired {
|
||||
return ErrHostNotWritable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Store) SetHostSubscription(ctx context.Context, id, planID uint64, expires *time.Time) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var state string
|
||||
var process uint32
|
||||
var locked bool
|
||||
var manual *time.Time
|
||||
if err = tx.QueryRowContext(ctx, "SELECT lifecycle_state,management_locked,manual_recycled_at FROM projects WHERE id=? FOR UPDATE", id).Scan(&state, &locked, &manual); err != nil {
|
||||
return err
|
||||
}
|
||||
if locked {
|
||||
return ErrManagementLocked
|
||||
}
|
||||
if manual != nil {
|
||||
return errors.New("主机已手动回收,请先使用恢复入口")
|
||||
}
|
||||
if state == "purged" {
|
||||
return errors.New("主机已删除")
|
||||
}
|
||||
if err = tx.QueryRowContext(ctx, "SELECT process_limit FROM plans WHERE id=?", planID).Scan(&process); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `UPDATE projects SET plan_id=?,process_limit=?,expires_at=?,lifecycle_state='active',grace_until=NULL,purge_after=NULL,backup_purge_after=NULL WHERE id=?`, planID, process, expires, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, "UPDATE sites SET process_limit=? WHERE project_id=?", process, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) SetHostIdentityVerified(ctx context.Context, id uint64, verified bool) error {
|
||||
_, err := s.db.ExecContext(ctx, "UPDATE projects SET identity_verified=? WHERE id=?", verified, id)
|
||||
return err
|
||||
}
|
||||
func (s *Store) PurgeHostRecord(ctx context.Context, id, tenantID uint64) error {
|
||||
if id == 0 {
|
||||
return errors.New("host scope required")
|
||||
}
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err = tx.ExecContext(ctx, "DELETE s FROM sessions s JOIN users u ON u.id=s.user_id WHERE u.project_id=? AND u.tenant_id=?", id, tenantID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, "DELETE FROM users WHERE project_id=? AND tenant_id=? AND role='host'", id, tenantID); err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := tx.ExecContext(ctx, "DELETE FROM projects WHERE id=? AND tenant_id=? AND lifecycle_state='recycle'", id, tenantID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, _ := result.RowsAffected()
|
||||
if n != 1 {
|
||||
return sql.ErrNoRows
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Store) ImpersonationTarget(ctx context.Context, tenantID, projectID uint64) (User, error) {
|
||||
var id uint64
|
||||
query := `SELECT u.id FROM users u JOIN tenants t ON t.id=u.tenant_id WHERE u.status='active' AND t.status='active' AND u.role='tenant' AND u.project_id IS NULL AND u.tenant_id=? ORDER BY u.id LIMIT 1`
|
||||
value := tenantID
|
||||
if projectID > 0 {
|
||||
query = `SELECT u.id FROM users u JOIN projects p ON p.id=u.project_id AND p.tenant_id=u.tenant_id JOIN tenants t ON t.id=u.tenant_id WHERE u.status='active' AND t.status='active' AND u.role='host' AND p.id=? AND p.status NOT IN ('failed','provisioning') ORDER BY u.id LIMIT 1`
|
||||
value = projectID
|
||||
}
|
||||
if err := s.db.QueryRowContext(ctx, query, value).Scan(&id); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return User{}, ErrNotFound
|
||||
}
|
||||
return User{}, err
|
||||
}
|
||||
return s.UserByID(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Store) CreateImpersonation(ctx context.Context, parent, token string, administratorID, targetID uint64, expires time.Time) error {
|
||||
target, err := s.UserByID(ctx, targetID)
|
||||
if err != nil || target.Role == "admin" || target.TenantID == nil {
|
||||
return ErrNotFound
|
||||
}
|
||||
parentHash, hash := sha256.Sum256([]byte(parent)), sha256.Sum256([]byte(token))
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err = tx.ExecContext(ctx, "DELETE FROM impersonation_sessions WHERE parent_session_hash=? OR expires_at<=UTC_TIMESTAMP()", parentHash[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := tx.ExecContext(ctx, `INSERT INTO impersonation_sessions(token_hash,parent_session_hash,administrator_id,target_user_id,expires_at)
|
||||
SELECT ?,s.token_hash,a.id,?,LEAST(s.expires_at,?) FROM sessions s JOIN users a ON a.id=s.user_id
|
||||
WHERE s.token_hash=? AND a.id=? AND a.role='admin' AND a.status='active' AND s.expires_at>UTC_TIMESTAMP()`, hash[:], targetID, expires.UTC(), parentHash[:], administratorID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := result.RowsAffected(); n != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) ImpersonationUser(ctx context.Context, parent, token string, administratorID uint64) (User, error) {
|
||||
parentHash, hash := sha256.Sum256([]byte(parent)), sha256.Sum256([]byte(token))
|
||||
var target uint64
|
||||
var expires time.Time
|
||||
err := s.db.QueryRowContext(ctx, `SELECT i.target_user_id,i.expires_at FROM impersonation_sessions i JOIN sessions s ON s.token_hash=i.parent_session_hash
|
||||
JOIN users a ON a.id=i.administrator_id WHERE i.token_hash=? AND i.parent_session_hash=? AND i.administrator_id=?
|
||||
AND s.user_id=a.id AND a.role='admin' AND a.status='active' AND s.expires_at>UTC_TIMESTAMP() AND i.expires_at>UTC_TIMESTAMP()`, hash[:], parentHash[:], administratorID).Scan(&target, &expires)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return User{}, ErrNotFound
|
||||
}
|
||||
return User{}, err
|
||||
}
|
||||
user, err := s.UserByID(ctx, target)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
if user.Role != "host" && user.Role != "tenant" {
|
||||
return User{}, ErrNotFound
|
||||
}
|
||||
user.Impersonating = true
|
||||
user.ImpersonationExpiresAt = &expires
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *Store) StopImpersonation(ctx context.Context, parent, token string) error {
|
||||
p, h := sha256.Sum256([]byte(parent)), sha256.Sum256([]byte(token))
|
||||
_, err := s.db.ExecContext(ctx, "DELETE FROM impersonation_sessions WHERE parent_session_hash=? AND token_hash=?", p[:], h[:])
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type IntegrationKey struct {
|
||||
ID uint64 `json:"id"`
|
||||
AdministratorID uint64 `json:"administratorId"`
|
||||
Name string `json:"name"`
|
||||
Prefix string `json:"prefix"`
|
||||
Scopes []string `json:"scopes"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
RevokedAt *time.Time `json:"revokedAt"`
|
||||
LastUsedAt *time.Time `json:"lastUsedAt"`
|
||||
WebhookURL string `json:"webhookURL"`
|
||||
WebhookSecret []byte `json:"-"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
const integrationFields = "k.id,k.administrator_id,k.name,k.token_prefix,k.scopes_json,k.expires_at,k.revoked_at,k.last_used_at,k.webhook_url,k.webhook_secret_cipher,k.created_at"
|
||||
|
||||
func scanIntegrationKey(row rowScanner) (IntegrationKey, error) {
|
||||
var v IntegrationKey
|
||||
var raw []byte
|
||||
e := row.Scan(&v.ID, &v.AdministratorID, &v.Name, &v.Prefix, &raw, &v.ExpiresAt, &v.RevokedAt, &v.LastUsedAt, &v.WebhookURL, &v.WebhookSecret, &v.CreatedAt)
|
||||
if e == nil {
|
||||
e = json.Unmarshal(raw, &v.Scopes)
|
||||
}
|
||||
return v, e
|
||||
}
|
||||
func (s *Store) IntegrationKeys(ctx context.Context) ([]IntegrationKey, error) {
|
||||
rows, e := s.db.QueryContext(ctx, "SELECT "+integrationFields+" FROM integration_keys k ORDER BY k.id DESC LIMIT 100")
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []IntegrationKey{}
|
||||
for rows.Next() {
|
||||
v, e := scanIntegrationKey(rows)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (s *Store) IntegrationKeyByToken(ctx context.Context, hash string) (IntegrationKey, error) {
|
||||
return scanIntegrationKey(s.db.QueryRowContext(ctx, "SELECT "+integrationFields+" FROM integration_keys k JOIN users u ON u.id=k.administrator_id WHERE k.token_hash=? AND k.revoked_at IS NULL AND k.expires_at>UTC_TIMESTAMP() AND u.role='admin' AND u.status='active'", hash))
|
||||
}
|
||||
func (s *Store) IntegrationKeyActive(ctx context.Context, id uint64) bool {
|
||||
var v bool
|
||||
e := s.db.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM integration_keys k JOIN users u ON u.id=k.administrator_id WHERE k.id=? AND k.revoked_at IS NULL AND k.expires_at>UTC_TIMESTAMP() AND u.status='active' AND u.role='admin')", id).Scan(&v)
|
||||
return e == nil && v
|
||||
}
|
||||
func (s *Store) CreateIntegrationKey(ctx context.Context, v IntegrationKey, hash string) (uint64, error) {
|
||||
raw, _ := json.Marshal(v.Scopes)
|
||||
r, e := s.db.ExecContext(ctx, "INSERT INTO integration_keys(administrator_id,name,token_hash,token_prefix,scopes_json,expires_at,webhook_url,webhook_secret_cipher) VALUES(?,?,?,?,?,?,?,?)", v.AdministratorID, v.Name, hash, v.Prefix, raw, v.ExpiresAt, v.WebhookURL, v.WebhookSecret)
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
id, _ := r.LastInsertId()
|
||||
return uint64(id), nil
|
||||
}
|
||||
func (s *Store) RevokeIntegrationKey(ctx context.Context, id uint64) error {
|
||||
_, e := s.db.ExecContext(ctx, "UPDATE integration_keys SET revoked_at=COALESCE(revoked_at,UTC_TIMESTAMP()) WHERE id=?", id)
|
||||
return e
|
||||
}
|
||||
func (s *Store) TouchIntegrationKey(ctx context.Context, id uint64) {
|
||||
_, _ = s.db.ExecContext(ctx, "UPDATE integration_keys SET last_used_at=UTC_TIMESTAMP() WHERE id=?", id)
|
||||
}
|
||||
func (s *Store) BatchIntegrationKey(ctx context.Context, batch uint64) (uint64, error) {
|
||||
var id uint64
|
||||
e := s.db.QueryRowContext(ctx, "SELECT COALESCE(integration_key_id,0) FROM admin_batches WHERE id=?", batch).Scan(&id)
|
||||
return id, e
|
||||
}
|
||||
|
||||
type IntegrationWebhook struct {
|
||||
ID uint64 `json:"id"`
|
||||
EventID string `json:"eventId"`
|
||||
KeyID uint64 `json:"keyId"`
|
||||
BatchID uint64 `json:"batchId"`
|
||||
State string `json:"state"`
|
||||
Attempts int `json:"attempts"`
|
||||
NextAttempt time.Time `json:"nextAttempt"`
|
||||
Status int `json:"status"`
|
||||
LastError string `json:"lastError"`
|
||||
URL string `json:"-"`
|
||||
Secret []byte `json:"-"`
|
||||
Prefix string `json:"-"`
|
||||
}
|
||||
|
||||
func (s *Store) QueueIntegrationWebhooks(ctx context.Context) error {
|
||||
_, e := s.db.ExecContext(ctx, `INSERT IGNORE INTO integration_webhooks(event_id,key_id,batch_id,next_attempt_at) SELECT LOWER(REPLACE(UUID(),'-','')),k.id,b.id,UTC_TIMESTAMP() FROM admin_batches b JOIN integration_keys k ON k.id=b.integration_key_id WHERE b.state IN ('completed','partial') AND k.webhook_url<>'' AND k.revoked_at IS NULL AND k.expires_at>UTC_TIMESTAMP()`)
|
||||
return e
|
||||
}
|
||||
func (s *Store) IntegrationWebhooks(ctx context.Context, due bool) ([]IntegrationWebhook, error) {
|
||||
query := `SELECT w.id,w.event_id,w.key_id,w.batch_id,w.state,w.attempts,w.next_attempt_at,w.last_status,w.last_error,k.webhook_url,k.webhook_secret_cipher,k.token_prefix FROM integration_webhooks w JOIN integration_keys k ON k.id=w.key_id`
|
||||
if due {
|
||||
query += ` JOIN users u ON u.id=k.administrator_id WHERE w.state='pending' AND w.attempts<8 AND w.next_attempt_at<=UTC_TIMESTAMP() AND k.revoked_at IS NULL AND k.expires_at>UTC_TIMESTAMP() AND u.status='active' AND u.role='admin' ORDER BY w.id LIMIT 10`
|
||||
} else {
|
||||
query += " ORDER BY w.id DESC LIMIT 100"
|
||||
}
|
||||
rows, e := s.db.QueryContext(ctx, query)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []IntegrationWebhook{}
|
||||
for rows.Next() {
|
||||
var v IntegrationWebhook
|
||||
if e = rows.Scan(&v.ID, &v.EventID, &v.KeyID, &v.BatchID, &v.State, &v.Attempts, &v.NextAttempt, &v.Status, &v.LastError, &v.URL, &v.Secret, &v.Prefix); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (s *Store) FinishIntegrationWebhook(ctx context.Context, v IntegrationWebhook, delivered bool, status int) error {
|
||||
state := "pending"
|
||||
if delivered {
|
||||
state = "delivered"
|
||||
} else if v.Attempts+1 >= 8 {
|
||||
state = "failed"
|
||||
}
|
||||
delay := time.Duration(1<<uint(v.Attempts)) * time.Minute
|
||||
message := ""
|
||||
if !delivered {
|
||||
message = "回调请求失败或未返回 2xx"
|
||||
}
|
||||
_, e := s.db.ExecContext(ctx, "UPDATE integration_webhooks SET state=?,attempts=attempts+1,last_status=?,last_error=?,next_attempt_at=?,delivered_at=IF(?,UTC_TIMESTAMP(),NULL) WHERE id=? AND attempts=?", state, status, message, time.Now().UTC().Add(delay), delivered, v.ID, v.Attempts)
|
||||
return e
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"io/fs"
|
||||
"os"
|
||||
"sea-vhost/internal/migrations"
|
||||
"sea-vhost/internal/scope"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestExistingSingleNodeMigrationMySQL(t *testing.T) {
|
||||
testSingleNodeMigrationMySQL(t, false)
|
||||
}
|
||||
|
||||
func TestInterruptedSingleNodeMigrationMySQL(t *testing.T) {
|
||||
testSingleNodeMigrationMySQL(t, true)
|
||||
}
|
||||
|
||||
func testSingleNodeMigrationMySQL(t *testing.T, interrupted bool) {
|
||||
dsn := os.Getenv("SEA_TEST_MYSQL_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("dedicated MySQL schema not supplied")
|
||||
}
|
||||
cfg, err := mysql.ParseDSN(dsn)
|
||||
if err != nil || !strings.HasPrefix(cfg.DBName, "svh_cluster_test_") {
|
||||
t.Fatal("non-test schema denied")
|
||||
}
|
||||
database, err := Open(dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)
|
||||
defer cancel()
|
||||
var sessionZone string
|
||||
if err = database.db.QueryRowContext(ctx, "SELECT @@session.time_zone").Scan(&sessionZone); err != nil || sessionZone != "+00:00" {
|
||||
t.Fatalf("platform session is not UTC: %q %v", sessionZone, err)
|
||||
}
|
||||
var tables int
|
||||
if err = database.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE()").Scan(&tables); err != nil || tables != 0 {
|
||||
t.Fatal("legacy fixture requires an empty disposable schema")
|
||||
}
|
||||
entries, err := fs.ReadDir(migrations.Files, ".")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") || entry.Name() >= "012_" {
|
||||
continue
|
||||
}
|
||||
raw, err := migrations.Files.ReadFile(entry.Name())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, statement := range strings.Split(string(raw), ";") {
|
||||
if strings.TrimSpace(statement) == "" {
|
||||
continue
|
||||
}
|
||||
if _, err = database.db.ExecContext(ctx, statement); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err = database.db.ExecContext(ctx, "INSERT INTO schema_migrations(version) VALUES(?)", entry.Name()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// This fixture intentionally predates migration 014's bandwidth_mbps.
|
||||
// Read only historical columns until the current migrations have run.
|
||||
var plan Plan
|
||||
if err = database.db.QueryRowContext(ctx, "SELECT id,process_limit FROM plans ORDER BY id LIMIT 1").Scan(&plan.ID, &plan.ProcessLimit); err != nil {
|
||||
t.Fatalf("legacy plan fixture: %v", err)
|
||||
}
|
||||
tenant, err := database.CreateTenant(ctx, NewTenant{Slug: "legacy-test", Name: "旧版迁移测试", Email: "legacy@example.invalid", DisplayName: "迁移测试", Password: "legacy-test-only-12345", PlanID: plan.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expiry := time.Now().UTC().Add(-5 * 24 * time.Hour).Truncate(time.Second)
|
||||
if _, err = database.db.ExecContext(ctx, `UPDATE tenants SET status='suspended',lifecycle_state='recycle',expires_at=?,grace_until=DATE_ADD(?,INTERVAL 3 DAY),purge_after=DATE_ADD(?,INTERVAL 10 DAY),backup_purge_after=DATE_ADD(?,INTERVAL 24 DAY) WHERE id=?`, expiry, expiry, expiry, expiry, tenant); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := database.db.ExecContext(ctx, `INSERT INTO projects(tenant_id,host_name,slug,runtime,runtime_version,root_path,run_path,assigned_domain,panel_site_id,backend_port,process_limit,status) VALUES(?,'sv3333333333','legacy-host','PHP','8.4','/www/wwwroot/seavHost/vHost/sv3333333333','/custom','sv3333333333.legacy.example.invalid',1001,20000,7,'stopped')`, tenant)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, _ := result.LastInsertId()
|
||||
_, err = database.db.ExecContext(ctx, `INSERT INTO sites(tenant_id,project_id,slug,assigned_domain,run_path,runtime,runtime_version,panel_site_id,backend_port,process_limit,status,is_primary) VALUES(?,?,'legacy-site','sv3333333333.legacy.example.invalid','/custom','PHP','8.4',1001,20000,7,'stopped',TRUE)`, tenant, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if interrupted {
|
||||
raw, err := migrations.Files.ReadFile("012_control_nodes.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, statement := range strings.Split(string(raw), ";") {
|
||||
statement = strings.TrimSpace(statement)
|
||||
if statement == "" {
|
||||
continue
|
||||
}
|
||||
if _, err = database.db.ExecContext(ctx, statement); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Simulate a process dying after the old account lifecycle was reset,
|
||||
// without recording the migration version. Expiry must not be lost.
|
||||
if strings.HasPrefix(statement, "UPDATE tenants SET status='active'") {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if err = database.Migrate(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = database.Migrate(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
project, err := database.Project(ctx, tenant, uint64(id))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner, err := database.ProjectOwner(ctx, project.ID)
|
||||
if err != nil || owner == nil || *owner != tenant {
|
||||
t.Fatalf("legacy customer ownership was not backfilled: %v", err)
|
||||
}
|
||||
if project.NodeID != 1 || project.PlanID != plan.ID || project.ProcessLimit != int(plan.ProcessLimit) || project.Status != "stopped" || project.RunPath != "/custom" || project.Domain != "sv3333333333.legacy.example.invalid" {
|
||||
t.Fatalf("legacy host changed unexpectedly: %+v", project)
|
||||
}
|
||||
sites, err := database.ListSites(ctx, tenant, project.ID)
|
||||
if err != nil || len(sites) != 1 || sites[0].ProcessLimit != int(plan.ProcessLimit) || sites[0].Status != "stopped" {
|
||||
t.Fatalf("legacy site migration: %+v %v", sites, err)
|
||||
}
|
||||
var copied time.Time
|
||||
var state string
|
||||
if err = database.db.QueryRowContext(ctx, "SELECT expires_at,lifecycle_state FROM projects WHERE id=?", id).Scan(&copied, &state); err != nil || !copied.Equal(expiry) || state != "recycle" {
|
||||
t.Fatalf("legacy expiry not preserved: %v %s %v", copied, state, err)
|
||||
}
|
||||
if _, err = database.TenantOwner(ctx, tenant); err != nil {
|
||||
t.Fatalf("host expiry still disables the user: %v", err)
|
||||
}
|
||||
p, _, err := database.PlanAndUsage(scope.WithProject(ctx, project.ID, 1), tenant)
|
||||
if err != nil || p.ID != plan.ID {
|
||||
t.Fatalf("host plan mapping: %+v %v", p, err)
|
||||
}
|
||||
t.Log("existing single-node host, stopped state, custom run directory, assigned domain, full per-host process allowance, expiration and user account separation preserved")
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var controlTable = regexp.MustCompile(`^CREATE TABLE ([a-z_]+) \(`)
|
||||
var controlAdd = regexp.MustCompile(`^ALTER TABLE ([a-z_]+) ADD (COLUMN|CONSTRAINT|UNIQUE KEY|KEY) ([a-z_]+)\b`)
|
||||
var controlDrop = regexp.MustCompile(`^ALTER TABLE ([a-z_]+) DROP INDEX ([a-z_]+)$`)
|
||||
|
||||
// Migration 012 contains many autocommitting DDL statements. Inspect the actual
|
||||
// schema before each one so a timeout, restart or response loss can resume it.
|
||||
// Its data backfills are deliberately idempotent as well (see the SQL source).
|
||||
func (s *Store) applyControlNodeStatement(ctx context.Context, statement string) error {
|
||||
var query string
|
||||
var args []any
|
||||
if match := controlTable.FindStringSubmatch(statement); match != nil {
|
||||
query = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=?"
|
||||
args = []any{match[1]}
|
||||
} else if match := controlAdd.FindStringSubmatch(statement); match != nil {
|
||||
switch match[2] {
|
||||
case "COLUMN":
|
||||
query = "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=? AND column_name=?"
|
||||
case "CONSTRAINT":
|
||||
query = "SELECT COUNT(*) FROM information_schema.table_constraints WHERE constraint_schema=DATABASE() AND table_name=? AND constraint_name=?"
|
||||
case "UNIQUE KEY", "KEY":
|
||||
query = "SELECT COUNT(*) FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name=? AND index_name=?"
|
||||
}
|
||||
args = []any{match[1], match[3]}
|
||||
} else if match := controlDrop.FindStringSubmatch(statement); match != nil {
|
||||
var count int
|
||||
if err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name=? AND index_name=?", match[1], match[2]).Scan(&count); err != nil {
|
||||
return err
|
||||
}
|
||||
if count == 0 {
|
||||
return nil
|
||||
}
|
||||
} else if strings.HasPrefix(statement, "ALTER TABLE runtime_update_notices DROP PRIMARY KEY") {
|
||||
var columns string
|
||||
if err := s.db.QueryRowContext(ctx, "SELECT COALESCE(GROUP_CONCAT(column_name ORDER BY seq_in_index),'') FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name='runtime_update_notices' AND index_name='PRIMARY'").Scan(&columns); err != nil {
|
||||
return err
|
||||
}
|
||||
if columns == "node_id,release_key" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if query != "" {
|
||||
var count int
|
||||
if err := s.db.QueryRowContext(ctx, query, args...).Scan(&count); err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, statement)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
package store
|
||||
|
||||
import "time"
|
||||
|
||||
type User struct {
|
||||
Impersonating bool `json:"impersonating,omitempty"`
|
||||
ImpersonationExpiresAt *time.Time `json:"impersonationExpiresAt,omitempty"`
|
||||
ID uint64 `json:"id"`
|
||||
TenantID *uint64 `json:"tenantId,omitempty"`
|
||||
ProjectID *uint64 `json:"projectId,omitempty"`
|
||||
LoginName string `json:"loginName"`
|
||||
Email string `json:"email,omitempty"`
|
||||
DisplayName string `json:"displayName"`
|
||||
PasswordHash string `json:"-"`
|
||||
Role string `json:"role"`
|
||||
TenantName string `json:"tenantName,omitempty"`
|
||||
TenantSlug string `json:"tenantSlug,omitempty"`
|
||||
MFAEnabled bool `json:"mfaEnabled"`
|
||||
}
|
||||
|
||||
type UserSecurity struct {
|
||||
PasswordHash string
|
||||
TOTPSecretCiphertext []byte
|
||||
TOTPEnabled bool
|
||||
}
|
||||
|
||||
type Plan struct {
|
||||
DeleteBlockedReason string `json:"deleteBlockedReason,omitempty"`
|
||||
ID uint64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
StorageBytes uint64 `json:"storageBytes"`
|
||||
DatabaseBytes uint64 `json:"databaseBytes"`
|
||||
BandwidthBytes uint64 `json:"bandwidthBytes"`
|
||||
BandwidthMbps uint32 `json:"bandwidthMbps"`
|
||||
ProcessLimit uint32 `json:"processLimit"`
|
||||
FTPLimit uint32 `json:"ftpLimit"`
|
||||
DatabaseLimit uint32 `json:"databaseLimit"`
|
||||
ProjectLimit uint32 `json:"projectLimit"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type NewPlan struct {
|
||||
Name string
|
||||
StorageBytes, DatabaseBytes, BandwidthBytes uint64
|
||||
ProcessLimit, FTPLimit, DatabaseLimit, ProjectLimit uint32
|
||||
BandwidthMbps uint32
|
||||
}
|
||||
|
||||
type ResourceCounts struct {
|
||||
FTP, Databases uint32
|
||||
}
|
||||
|
||||
type Usage struct {
|
||||
StorageBytes uint64 `json:"storageBytes"`
|
||||
DatabaseBytes uint64 `json:"databaseBytes"`
|
||||
BandwidthBytes uint64 `json:"bandwidthBytes"`
|
||||
ProcessCount uint32 `json:"processCount"`
|
||||
MeasuredAt time.Time `json:"measuredAt"`
|
||||
}
|
||||
|
||||
type Project struct {
|
||||
AllowRuntimeChange bool `json:"allowRuntimeChange"`
|
||||
BandwidthBytes uint64 `json:"bandwidthBytes"`
|
||||
NodeID uint64 `json:"nodeId"`
|
||||
PlanID uint64 `json:"planId"`
|
||||
ID uint64 `json:"id"`
|
||||
TenantID uint64 `json:"-"`
|
||||
HostName string `json:"hostName"`
|
||||
Slug string `json:"name"`
|
||||
Domain string `json:"domain"`
|
||||
Path string `json:"path"`
|
||||
RunPath string `json:"runPath"`
|
||||
Runtime string `json:"runtime"`
|
||||
Version string `json:"version"`
|
||||
Status string `json:"status"`
|
||||
SSLStatus string `json:"sslStatus"`
|
||||
PanelSiteID int64 `json:"-"`
|
||||
BackendPort int `json:"backendPort"`
|
||||
ProcessLimit int `json:"processLimit"`
|
||||
AutoSSL bool `json:"autoSSL"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type Site struct {
|
||||
ID uint64 `json:"id"`
|
||||
TenantID uint64 `json:"-"`
|
||||
ProjectID uint64 `json:"projectId"`
|
||||
Name string `json:"name"`
|
||||
Domain string `json:"domain"`
|
||||
RunPath string `json:"runPath"`
|
||||
Runtime string `json:"runtime"`
|
||||
Version string `json:"version"`
|
||||
Status string `json:"status"`
|
||||
SSLStatus string `json:"sslStatus"`
|
||||
PanelSiteID int64 `json:"-"`
|
||||
BackendPort int `json:"backendPort"`
|
||||
ProcessLimit int `json:"processLimit"`
|
||||
AutoSSL bool `json:"autoSSL"`
|
||||
Primary bool `json:"primary"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
// DNSCredential is safe to return through the API. CredentialCiphertext and
|
||||
// SecretRef are deliberately excluded from JSON and only used by the issuance
|
||||
// service after an ownership-scoped database lookup.
|
||||
type DNSCredential struct {
|
||||
ID uint64 `json:"id"`
|
||||
TenantID *uint64 `json:"-"`
|
||||
ScopeKey string `json:"scope"`
|
||||
SecretRef string `json:"-"`
|
||||
Label string `json:"label"`
|
||||
Provider string `json:"provider"`
|
||||
ZoneName string `json:"zoneName"`
|
||||
CredentialCiphertext []byte `json:"-"`
|
||||
LastTestedAt *time.Time `json:"lastTestedAt,omitempty"`
|
||||
TestStatus string `json:"testStatus"`
|
||||
TestError string `json:"testError,omitempty"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type NewDNSCredential struct {
|
||||
TenantID *uint64
|
||||
ScopeKey string
|
||||
SecretRef string
|
||||
Label string
|
||||
Provider string
|
||||
ZoneName string
|
||||
CredentialCiphertext []byte
|
||||
}
|
||||
|
||||
type CertificateAutomation struct {
|
||||
SiteID uint64 `json:"siteId"`
|
||||
Mode string `json:"mode"`
|
||||
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
|
||||
LastAttemptAt *time.Time `json:"lastAttemptAt,omitempty"`
|
||||
NextAttemptAt *time.Time `json:"nextAttemptAt,omitempty"`
|
||||
LastError string `json:"lastError,omitempty"`
|
||||
}
|
||||
|
||||
type CertificateRenewal struct {
|
||||
Project Project
|
||||
Site Site
|
||||
}
|
||||
|
||||
type DomainResource struct {
|
||||
ID uint64 `json:"id"`
|
||||
TenantID uint64 `json:"-"`
|
||||
ProjectID uint64 `json:"projectId"`
|
||||
SiteID uint64 `json:"siteId"`
|
||||
TenantName string `json:"tenantName,omitempty"`
|
||||
HostName string `json:"hostName"`
|
||||
ProjectName string `json:"projectName"`
|
||||
SiteName string `json:"siteName"`
|
||||
Domain string `json:"domain"`
|
||||
Kind string `json:"kind"`
|
||||
Status string `json:"status"`
|
||||
ResolutionMode string `json:"resolutionMode"`
|
||||
CNAME string `json:"cnameTarget,omitempty"`
|
||||
DNSCredentialID *uint64 `json:"dnsCredentialId,omitempty"`
|
||||
DNSRecordID string `json:"dnsRecordId,omitempty"`
|
||||
DNSRecordType string `json:"dnsRecordType,omitempty"`
|
||||
DNSLastError string `json:"dnsLastError,omitempty"`
|
||||
FilingStatus string `json:"filingStatus"`
|
||||
FilingNumber string `json:"filingNumber,omitempty"`
|
||||
FilingNote string `json:"filingNote,omitempty"`
|
||||
SSLStatus string `json:"sslStatus"`
|
||||
PanelSiteID int64 `json:"-"`
|
||||
SiteAssignedDomain string `json:"-"`
|
||||
RootPath string `json:"-"`
|
||||
AutoSSL bool `json:"-"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type FTPResource struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ID uint64 `json:"id"`
|
||||
TenantID uint64 `json:"-"`
|
||||
PanelID int64 `json:"-"`
|
||||
ProjectID uint64 `json:"projectId"`
|
||||
HostName string `json:"hostName"`
|
||||
ProjectName string `json:"projectName"`
|
||||
Username string `json:"username"`
|
||||
RootPath string `json:"rootPath"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type DatabaseResource struct {
|
||||
ID uint64 `json:"id"`
|
||||
TenantID uint64 `json:"-"`
|
||||
PanelID int64 `json:"-"`
|
||||
ProjectID uint64 `json:"projectId"`
|
||||
HostName string `json:"hostName"`
|
||||
ProjectName string `json:"projectName"`
|
||||
Name string `json:"name"`
|
||||
Username string `json:"username"`
|
||||
SizeBytes uint64 `json:"sizeBytes"`
|
||||
Status string `json:"status"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type NewSite struct {
|
||||
TenantID, ProjectID uint64
|
||||
Name, Domain, RunPath, Runtime string
|
||||
Version string
|
||||
BackendPort, ProcessLimit int
|
||||
AutoSSL, Primary bool
|
||||
}
|
||||
|
||||
type StoredCredentials struct {
|
||||
FTPUsername, DatabaseName, DatabaseUsername string
|
||||
FTPPasswordCipher, DatabasePasswordCipher []byte
|
||||
}
|
||||
|
||||
type NewProject struct {
|
||||
OwnerTenantID *uint64
|
||||
OwnershipSpecified bool
|
||||
NodeID, PlanID uint64
|
||||
TenantID uint64
|
||||
HostName, Slug, Runtime, Version, Path, RunPath, Domain string
|
||||
BackendPort, ProcessLimit int
|
||||
AutoSSL bool
|
||||
HostPasswordHash string
|
||||
}
|
||||
|
||||
type Activity struct {
|
||||
ID uint64 `json:"id"`
|
||||
ProjectID *uint64 `json:"projectId,omitempty"`
|
||||
HostName string `json:"hostName,omitempty"`
|
||||
Actor string `json:"actor"`
|
||||
IPAddress string `json:"ipAddress,omitempty"`
|
||||
Action string `json:"action"`
|
||||
ResourceType string `json:"resourceType"`
|
||||
Detail string `json:"detail"`
|
||||
Success bool `json:"success"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type TenantSummary struct {
|
||||
ID uint64 `json:"id"`
|
||||
Slug string `json:"slug"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
LifecycleState string `json:"lifecycleState"`
|
||||
PlanName string `json:"planName"`
|
||||
UserCount int `json:"userCount"`
|
||||
ProjectCount int `json:"projectCount"`
|
||||
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
|
||||
GraceUntil *time.Time `json:"graceUntil,omitempty"`
|
||||
PurgeAfter *time.Time `json:"purgeAfter,omitempty"`
|
||||
BackupPurgeAfter *time.Time `json:"backupPurgeAfter,omitempty"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type AdminProject struct {
|
||||
ManualRecycledAt *time.Time `json:"manualRecycledAt,omitempty"`
|
||||
PurgeAfter *time.Time `json:"purgeAfter,omitempty"`
|
||||
RecycleError string `json:"recycleError,omitempty"`
|
||||
PendingOwnership *OwnershipChange `json:"pendingOwnership,omitempty"`
|
||||
OwnerTenantID *uint64 `json:"ownerTenantId"`
|
||||
ManagementLocked bool `json:"managementLocked"`
|
||||
OwnershipVersion uint64 `json:"ownershipVersion"`
|
||||
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
|
||||
LifecycleState string `json:"lifecycleState"`
|
||||
Project
|
||||
TenantName string `json:"tenantName"`
|
||||
SiteCount int `json:"siteCount"`
|
||||
IPAddress string `json:"ipAddress,omitempty"`
|
||||
DedicatedIP bool `json:"dedicatedIp"`
|
||||
HTTPPort int `json:"httpPort"`
|
||||
HTTPSPort int `json:"httpsPort"`
|
||||
}
|
||||
|
||||
type IPAddress struct {
|
||||
NodeID uint64 `json:"nodeId"`
|
||||
ID uint64 `json:"id"`
|
||||
Address string `json:"address"`
|
||||
Family string `json:"family"`
|
||||
AllocationMode string `json:"allocationMode"`
|
||||
Label string `json:"label"`
|
||||
Enabled bool `json:"enabled"`
|
||||
AssignedSites int `json:"assignedSites"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type AdminActivity struct {
|
||||
AdministratorID *uint64 `json:"administratorId,omitempty"`
|
||||
ImpersonatedUserID *uint64 `json:"impersonatedUserId,omitempty"`
|
||||
ImpersonatedUserName string `json:"impersonatedUserName,omitempty"`
|
||||
ID uint64 `json:"id"`
|
||||
TenantName string `json:"userName,omitempty"`
|
||||
Action string `json:"action"`
|
||||
ResourceType string `json:"resourceType"`
|
||||
ResourceID string `json:"resourceId,omitempty"`
|
||||
IPAddress string `json:"ipAddress,omitempty"`
|
||||
Success bool `json:"success"`
|
||||
Detail string `json:"detail"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type NewTenant struct {
|
||||
Slug, Name, Email, DisplayName, Password string
|
||||
PlanID uint64
|
||||
ExpiresAt *time.Time
|
||||
}
|
||||
|
||||
type TenantBackup struct {
|
||||
NodeID uint64 `json:"nodeId"`
|
||||
ID uint64 `json:"id"`
|
||||
TenantID uint64 `json:"tenantId"`
|
||||
ProjectID *uint64 `json:"projectId,omitempty"`
|
||||
HostName string `json:"hostName"`
|
||||
ArchivePath string `json:"-"`
|
||||
SizeBytes uint64 `json:"sizeBytes"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
DeletedAt *time.Time `json:"deletedAt,omitempty"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type AdminNotification struct {
|
||||
ID uint64
|
||||
Severity string
|
||||
Category string
|
||||
Title string
|
||||
Detail string
|
||||
Attempts uint32
|
||||
NextAttemptAt *time.Time
|
||||
}
|
||||
|
||||
type OIDCState struct {
|
||||
SessionHash []byte
|
||||
ProviderKey string
|
||||
UserID *uint64
|
||||
Mode string
|
||||
Verifier string
|
||||
Nonce string
|
||||
Expires time.Time
|
||||
}
|
||||
|
||||
type OIDCIdentity struct {
|
||||
Provider string `json:"provider"`
|
||||
Subject string `json:"-"`
|
||||
Email string `json:"email"`
|
||||
Created time.Time `json:"createdAt"`
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"os"
|
||||
"sea-vhost/internal/scope"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Run only against a disposable schema created by the test harness. The test
|
||||
// never opens the production schema and cannot be enabled with its usual DSN.
|
||||
func TestMultiNodeMySQL(t *testing.T) {
|
||||
dsn := os.Getenv("SEA_TEST_MYSQL_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("dedicated MySQL schema not supplied")
|
||||
}
|
||||
config, err := mysql.ParseDSN(dsn)
|
||||
if err != nil || !strings.HasPrefix(config.DBName, "svh_cluster_test_") {
|
||||
t.Fatal("refusing a non-test schema")
|
||||
}
|
||||
db, err := Open(dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||
defer cancel()
|
||||
if err = db.Migrate(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = db.Migrate(ctx); err != nil {
|
||||
t.Fatalf("repeat migration: %v", err)
|
||||
}
|
||||
plans, err := db.ListPlans(ctx)
|
||||
if err != nil || len(plans) == 0 {
|
||||
t.Fatalf("plans: %v", err)
|
||||
}
|
||||
tenant, err := db.CreateTenant(ctx, NewTenant{Slug: "cluster-test", Name: "测试用户", Email: "cluster@example.invalid", DisplayName: "测试管理员", Password: "integration-test-only-123", PlanID: plans[0].ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nodes := []uint64{}
|
||||
hosts := []uint64{}
|
||||
for i, name := range []string{"sv0123456789", "svabcdef0123"} {
|
||||
node, err := db.CreateNode(ctx, Node{Name: name, Endpoint: "https://" + name + ".example.invalid:9443", RootDomain: name + ".example.invalid", TenantRoot: "/www/wwwroot/seavHost/vHost", FTPCertificateDomain: "ftp.example.invalid"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = db.SetNodeEnabled(ctx, node, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nodes = append(nodes, node)
|
||||
id, err := db.InsertProject(ctx, NewProject{NodeID: node, PlanID: plans[0].ID, TenantID: tenant, HostName: name, Slug: name, Runtime: "PHP", Version: "8.4", Path: "/www/wwwroot/seavHost/vHost/" + name, RunPath: "/public", Domain: name + ".example.invalid", ProcessLimit: 10, HostPasswordHash: "test-hash"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hosts = append(hosts, id)
|
||||
if err = db.CompleteProject(scope.WithProject(ctx, id, node), id, 1001, 1002, 1003, name, name, name, []byte("cipher"), []byte("cipher"), "running", "", "", false); err != nil {
|
||||
t.Fatalf("same native site ID on node %d: %v", i, err)
|
||||
}
|
||||
for _, state := range []string{"running", "running", "stopped", "stopped", "running"} {
|
||||
if err = db.SetProjectState(ctx, tenant, id, state); err != nil {
|
||||
t.Fatalf("idempotent primary state %s: %v", state, err)
|
||||
}
|
||||
}
|
||||
extra, createErr := db.InsertSite(ctx, NewSite{TenantID: tenant, ProjectID: id, Name: "idempotent", Domain: name + "-extra.example.invalid", RunPath: "/extra", Runtime: "PHP", Version: "8.4", ProcessLimit: 10})
|
||||
if createErr != nil {
|
||||
t.Fatal(createErr)
|
||||
}
|
||||
for _, state := range []string{"running", "running", "stopped", "stopped"} {
|
||||
if err = db.SetSiteState(ctx, tenant, id, extra, state); err != nil {
|
||||
t.Fatalf("idempotent extra site state %s: %v", state, err)
|
||||
}
|
||||
}
|
||||
if err = db.SetSiteState(ctx, tenant, id+1, extra, "running"); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("wrong host state accepted: %v", err)
|
||||
}
|
||||
if err = db.DeleteSite(ctx, tenant, id, extra); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, port := range []int{18080, 18080, 80, 80} {
|
||||
if err = db.SetProjectNetwork(ctx, id, nil, false, port, 443); err != nil {
|
||||
t.Fatalf("upsert network %d: %v", port, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
a := scope.WithProject(ctx, hosts[0], nodes[0])
|
||||
b := scope.WithProject(ctx, hosts[1], nodes[1])
|
||||
if _, _, err = db.ProjectPlacement(ctx, hosts[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if items, err := db.ListProjects(a, tenant); err != nil || len(items) != 1 || items[0].NodeID != nodes[0] {
|
||||
t.Fatalf("project scope: %+v %v", items, err)
|
||||
}
|
||||
if items, err := db.ListProjects(ctx, tenant); err != nil || len(items) != 2 {
|
||||
t.Fatalf("account aggregation: %d %v", len(items), err)
|
||||
}
|
||||
if sites, err := db.ListTenantSites(a, tenant, nil); err != nil || len(sites) != 1 || sites[0].ProjectID != hosts[0] {
|
||||
t.Fatalf("site scope: %+v %v", sites, err)
|
||||
}
|
||||
if err = db.UpdateQuotaMeasurement(a, tenant, Usage{StorageBytes: 111}, time.Now(), nil, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = db.SetTenantQuotaSuspended(a, tenant, "storage quota exceeded"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, u, err := db.PlanAndUsage(a, tenant); err != nil || u.StorageBytes != 111 {
|
||||
t.Fatalf("host usage: %+v %v", u, err)
|
||||
}
|
||||
if suspended, _, err := db.TenantQuotaSuspension(b, tenant); err != nil || suspended {
|
||||
t.Fatalf("quota affected another host: %v", err)
|
||||
}
|
||||
if _, u, err := db.PlanAndUsage(ctx, tenant); err != nil || u.StorageBytes != 111 {
|
||||
t.Fatalf("account usage aggregate: %+v %v", u, err)
|
||||
}
|
||||
for _, c := range []context.Context{a, b} {
|
||||
if _, err = db.CreateRuntimeJob(c, RuntimeJob{Action: "check", Runtime: "all", TargetVersion: "-"}); err != nil {
|
||||
t.Fatalf("node job lock: %v", err)
|
||||
}
|
||||
}
|
||||
if _, err = db.CreateRuntimeJob(a, RuntimeJob{Action: "check", Runtime: "all", TargetVersion: "-"}); err == nil {
|
||||
t.Fatal("same-node concurrent maintenance accepted")
|
||||
}
|
||||
lease, err := db.LockNodeRegistry(ctx, nodes[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := lease.Read(ctx)
|
||||
if err != nil || !strings.Contains(string(raw), `"sites":{}`) {
|
||||
t.Fatal("empty registry missing")
|
||||
}
|
||||
if err = lease.Save(ctx, []byte(`{"version":1,"sites":{},"ftp":{},"databases":{}}`)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lease.Close()
|
||||
expiry := time.Now().Add(-time.Hour)
|
||||
if err = db.SetHostSubscription(a, hosts[0], plans[0].ID, &expiry); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = db.AdvanceHostLifecycle(ctx, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = db.HostWritable(a, tenant); err == nil {
|
||||
t.Fatal("expired host still writable")
|
||||
}
|
||||
if err = db.HostWritable(b, tenant); err != nil {
|
||||
t.Fatalf("expiration affected another host: %v", err)
|
||||
}
|
||||
if owner, err := db.TenantOwner(ctx, tenant); err != nil || owner.Role != "tenant" {
|
||||
t.Fatalf("tenant account affected: %v", err)
|
||||
}
|
||||
admin, err := db.ListAdminProjects(ctx)
|
||||
if err != nil || len(admin) != 2 {
|
||||
t.Fatalf("admin projects scan: %v", err)
|
||||
}
|
||||
t.Log("migrations, duplicate native IDs, project quotas, account aggregation, node maintenance locks, central registry, and per-host expiration verified")
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Node struct {
|
||||
ID uint64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Transport string `json:"transport"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
RootDomain string `json:"rootDomain"`
|
||||
TenantRoot string `json:"tenantRoot"`
|
||||
FTPCertificateDomain string `json:"ftpCertificateDomain"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Credentials []byte `json:"-"`
|
||||
LastSeenAt *time.Time `json:"lastSeenAt,omitempty"`
|
||||
LastError string `json:"lastError"`
|
||||
}
|
||||
|
||||
const nodeColumns = "id,name,transport,endpoint,root_domain,tenant_root,ftp_certificate_domain,enabled,credentials,last_seen_at,last_error"
|
||||
|
||||
func scanNode(row interface{ Scan(...any) error }) (Node, error) {
|
||||
var n Node
|
||||
err := row.Scan(&n.ID, &n.Name, &n.Transport, &n.Endpoint, &n.RootDomain, &n.TenantRoot, &n.FTPCertificateDomain, &n.Enabled, &n.Credentials, &n.LastSeenAt, &n.LastError)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
err = ErrNotFound
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
func (s *Store) Node(ctx context.Context, id uint64) (Node, error) {
|
||||
return scanNode(s.db.QueryRowContext(ctx, "SELECT "+nodeColumns+" FROM control_nodes WHERE id=? AND deleted_at IS NULL", id))
|
||||
}
|
||||
func (s *Store) Nodes(ctx context.Context) ([]Node, error) {
|
||||
rows, err := s.db.QueryContext(ctx, "SELECT "+nodeColumns+" FROM control_nodes WHERE deleted_at IS NULL ORDER BY id")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
result := []Node{}
|
||||
for rows.Next() {
|
||||
n, e := scanNode(rows)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
result = append(result, n)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
func (s *Store) InitializeLocalNode(ctx context.Context, domain, root, ftp string) error {
|
||||
_, err := s.db.ExecContext(ctx, "UPDATE control_nodes SET root_domain=?,tenant_root=?,ftp_certificate_domain=? WHERE id=1 AND transport='local' AND root_domain=''", domain, root, ftp)
|
||||
return err
|
||||
}
|
||||
func (s *Store) CreateNode(ctx context.Context, n Node) (uint64, error) {
|
||||
r, err := s.db.ExecContext(ctx, `INSERT INTO control_nodes(name,transport,endpoint,root_domain,tenant_root,ftp_certificate_domain,enabled,registry_json) VALUES(?,'https',?,?,?,?,FALSE,'{"version":1,"sites":{},"ftp":{},"databases":{}}')`, n.Name, n.Endpoint, n.RootDomain, n.TenantRoot, n.FTPCertificateDomain)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
id, err := r.LastInsertId()
|
||||
return uint64(id), err
|
||||
}
|
||||
func (s *Store) SetNodeCredentials(ctx context.Context, id uint64, cipher []byte) error {
|
||||
_, err := s.db.ExecContext(ctx, "UPDATE control_nodes SET credentials=?,enabled=FALSE,last_seen_at=NULL,last_error='' WHERE id=? AND deleted_at IS NULL AND transport='https'", cipher, id)
|
||||
return err
|
||||
}
|
||||
func (s *Store) SetNodeEnabled(ctx context.Context, id uint64, enabled bool) error {
|
||||
r, err := s.db.ExecContext(ctx, "UPDATE control_nodes SET enabled=? WHERE id=? AND deleted_at IS NULL", enabled, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, _ := r.RowsAffected()
|
||||
if n == 0 {
|
||||
_, err = s.Node(ctx, id)
|
||||
}
|
||||
return err
|
||||
}
|
||||
func (s *Store) RecordNodeProbe(ctx context.Context, id uint64, detail string) error {
|
||||
if len(detail) > 500 {
|
||||
detail = detail[:500]
|
||||
}
|
||||
if detail == "" {
|
||||
_, err := s.db.ExecContext(ctx, "UPDATE control_nodes SET last_seen_at=UTC_TIMESTAMP(),last_error='' WHERE id=?", id)
|
||||
return err
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, "UPDATE control_nodes SET last_error=? WHERE id=?", detail, id)
|
||||
return err
|
||||
}
|
||||
func (s *Store) NodeForHost(ctx context.Context, host string) (uint64, error) {
|
||||
var id uint64
|
||||
err := s.db.QueryRowContext(ctx, "SELECT node_id FROM projects WHERE host_name=?", host).Scan(&id)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
err = ErrNotFound
|
||||
}
|
||||
return id, err
|
||||
}
|
||||
func (s *Store) ProjectPlacement(ctx context.Context, id uint64) (nodeID, planID uint64, err error) {
|
||||
err = s.db.QueryRowContext(ctx, "SELECT node_id,COALESCE(plan_id,0) FROM projects WHERE id=?", id).Scan(&nodeID, &planID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
err = ErrNotFound
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *Store) NodeForSite(ctx context.Context, id uint64) (uint64, error) {
|
||||
var node uint64
|
||||
err := s.db.QueryRowContext(ctx, "SELECT node_id FROM sites WHERE id=?", id).Scan(&node)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
err = ErrNotFound
|
||||
}
|
||||
return node, err
|
||||
}
|
||||
|
||||
// The registry lives only in the controller DB. A per-node MySQL named lock
|
||||
// serializes snapshots across foreground requests and scheduler workers.
|
||||
type NodeRegistryLease struct {
|
||||
conn *sql.Conn
|
||||
id uint64
|
||||
key string
|
||||
}
|
||||
|
||||
func (s *Store) LockNodeRegistry(ctx context.Context, id uint64) (*NodeRegistryLease, error) {
|
||||
conn, err := s.db.Conn(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key := fmt.Sprintf("sea-vhost/node/%d", id)
|
||||
var acquired sql.NullInt64
|
||||
if err = conn.QueryRowContext(ctx, "SELECT GET_LOCK(?,10)", key).Scan(&acquired); err != nil || !acquired.Valid || acquired.Int64 != 1 {
|
||||
conn.Close()
|
||||
return nil, errors.New("node controller operation is busy")
|
||||
}
|
||||
return &NodeRegistryLease{conn: conn, id: id, key: key}, nil
|
||||
}
|
||||
func (l *NodeRegistryLease) Read(ctx context.Context) ([]byte, error) {
|
||||
var raw string
|
||||
err := l.conn.QueryRowContext(ctx, "SELECT registry_json FROM control_nodes WHERE id=? AND deleted_at IS NULL", l.id).Scan(&raw)
|
||||
return []byte(raw), err
|
||||
}
|
||||
func (l *NodeRegistryLease) Save(ctx context.Context, raw []byte) error {
|
||||
_, err := l.conn.ExecContext(ctx, "UPDATE control_nodes SET registry_json=?,registry_revision=registry_revision+1 WHERE id=?", string(raw), l.id)
|
||||
return err
|
||||
}
|
||||
func (l *NodeRegistryLease) Close() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
_, _ = l.conn.ExecContext(ctx, "SELECT RELEASE_LOCK(?)", l.key)
|
||||
_ = l.conn.Close()
|
||||
}
|
||||
|
||||
func (s *Store) StartControlTask(ctx context.Context, nodeID, projectID uint64, operation, requestID string) (uint64, error) {
|
||||
var project any
|
||||
if projectID > 0 {
|
||||
project = projectID
|
||||
}
|
||||
r, err := s.db.ExecContext(ctx, "INSERT INTO control_tasks(node_id,project_id,operation,request_id,started_at) VALUES(?,?,?,?,UTC_TIMESTAMP())", nodeID, project, operation, requestID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
id, err := r.LastInsertId()
|
||||
return uint64(id), err
|
||||
}
|
||||
func (s *Store) FinishControlTask(ctx context.Context, id uint64, state, detail string) error {
|
||||
if state != "succeeded" && state != "failed" && state != "uncertain" {
|
||||
return errors.New("invalid controller task state")
|
||||
}
|
||||
if len(detail) > 500 {
|
||||
detail = detail[:500]
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, "UPDATE control_tasks SET state=?,detail=?,finished_at=UTC_TIMESTAMP() WHERE id=?", state, detail, id)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"sea-vhost/internal/scope"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var ErrManagementLocked = errors.New("主机正在处理环境或归属变更,请稍后重试;持续未恢复时请联系管理员核验任务")
|
||||
|
||||
func (s *Store) BindUnassignedHost(ctx context.Context, id, version, target uint64) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var current sql.NullInt64
|
||||
var actual uint64
|
||||
var locked bool
|
||||
if err = tx.QueryRowContext(ctx, "SELECT owner_tenant_id,ownership_version,(management_locked OR manual_recycled_at IS NOT NULL) FROM projects WHERE id=? FOR UPDATE", id).Scan(¤t, &actual, &locked); err != nil {
|
||||
return ErrNotFound
|
||||
}
|
||||
if actual != version {
|
||||
return errors.New("主机归属已变化,请重新预览")
|
||||
}
|
||||
if locked {
|
||||
return ErrManagementLocked
|
||||
}
|
||||
if (current.Valid && uint64(current.Int64) == target) || (!current.Valid && target == 0) {
|
||||
return tx.Commit()
|
||||
}
|
||||
if current.Valid {
|
||||
return errors.New("已有归属的主机须按已确认的凭据撤销策略处理")
|
||||
}
|
||||
var account uint64
|
||||
if err = tx.QueryRowContext(ctx, "SELECT t.id FROM tenants t JOIN users u ON u.tenant_id=t.id AND u.role='tenant' WHERE t.id=? AND t.resource_namespace=FALSE AND t.status='active' AND u.status='active' FOR UPDATE", target).Scan(&account); err != nil {
|
||||
return errors.New("目标用户不存在或已停用")
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, "UPDATE projects SET owner_tenant_id=?,ownership_version=ownership_version+1 WHERE id=?", target, id); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) AccountIdentityExists(ctx context.Context, slug, login string) (bool, error) {
|
||||
var count int
|
||||
err := s.db.QueryRowContext(ctx, "SELECT (SELECT COUNT(*) FROM tenants WHERE slug=?)+(SELECT COUNT(*) FROM users WHERE email=? OR login_name=?)", slug, login, login).Scan(&count)
|
||||
return count > 0, err
|
||||
}
|
||||
func (s *Store) ResolveAnyAccount(ctx context.Context, reference string) (uint64, error) {
|
||||
reference = strings.ToLower(strings.TrimSpace(reference))
|
||||
numeric, _ := strconv.ParseUint(reference, 10, 64)
|
||||
var id uint64
|
||||
query := "SELECT t.id FROM tenants t JOIN users u ON u.tenant_id=t.id AND u.role='tenant' WHERE t.resource_namespace=FALSE AND t.deleted_at IS NULL AND (t.slug=? OR u.login_name=?) ORDER BY t.id LIMIT 1"
|
||||
args := []any{reference, reference}
|
||||
if numeric > 0 {
|
||||
query = "SELECT t.id FROM tenants t JOIN users u ON u.tenant_id=t.id AND u.role='tenant' WHERE t.resource_namespace=FALSE AND t.deleted_at IS NULL AND t.id=?"
|
||||
args = []any{numeric}
|
||||
}
|
||||
err := s.db.QueryRowContext(ctx, query, args...).Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
// CustomerFilter is used only for customer-facing aggregate queries. A scoped
|
||||
// host request uses the internal namespace supplied after authorization.
|
||||
func customerFilter(ctx context.Context, tenantID uint64, projectAlias, resourceAlias string) (string, []any) {
|
||||
if account := scope.Account(ctx); account > 0 {
|
||||
return projectAlias + ".owner_tenant_id=? AND " + projectAlias + ".management_locked=FALSE AND " + projectAlias + ".manual_recycled_at IS NULL", []any{account}
|
||||
}
|
||||
return resourceAlias + ".tenant_id=?", []any{tenantID}
|
||||
}
|
||||
|
||||
func (s *Store) ProjectForUser(ctx context.Context, user User, id uint64) (Project, error) {
|
||||
if user.TenantID == nil {
|
||||
return Project{}, ErrNotFound
|
||||
}
|
||||
var namespace uint64
|
||||
var owner sql.NullInt64
|
||||
var locked bool
|
||||
if err := s.db.QueryRowContext(ctx, "SELECT tenant_id,owner_tenant_id,(management_locked OR manual_recycled_at IS NOT NULL) FROM projects WHERE id=?", id).Scan(&namespace, &owner, &locked); err != nil {
|
||||
return Project{}, ErrNotFound
|
||||
}
|
||||
if user.Role == "host" {
|
||||
if user.ProjectID == nil || *user.ProjectID != id || *user.TenantID != namespace {
|
||||
return Project{}, ErrNotFound
|
||||
}
|
||||
} else if user.Role == "tenant" {
|
||||
account := scope.Account(ctx)
|
||||
if account == 0 {
|
||||
account = *user.TenantID
|
||||
}
|
||||
if !owner.Valid || uint64(owner.Int64) != account {
|
||||
return Project{}, ErrNotFound
|
||||
}
|
||||
} else {
|
||||
return Project{}, ErrNotFound
|
||||
}
|
||||
if locked {
|
||||
return Project{}, ErrManagementLocked
|
||||
}
|
||||
return s.Project(ctx, namespace, id)
|
||||
}
|
||||
|
||||
func (s *Store) ProjectOwner(ctx context.Context, id uint64) (*uint64, error) {
|
||||
var value sql.NullInt64
|
||||
if err := s.db.QueryRowContext(ctx, "SELECT owner_tenant_id FROM projects WHERE id=?", id).Scan(&value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !value.Valid {
|
||||
return nil, nil
|
||||
}
|
||||
id = uint64(value.Int64)
|
||||
return &id, nil
|
||||
}
|
||||
|
||||
func (s *Store) NewResourceNamespace(ctx context.Context, planID uint64) (uint64, error) {
|
||||
var token [16]byte
|
||||
if _, err := rand.Read(token[:]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
result, err := s.db.ExecContext(ctx, "INSERT INTO tenants(slug,name,plan_id,resource_namespace) VALUES (?,?,?,TRUE)", "internal-"+hex.EncodeToString(token[:]), "独立主机资源", planID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
id, err := result.LastInsertId()
|
||||
return uint64(id), err
|
||||
}
|
||||
func (s *Store) DeleteUnusedResourceNamespace(ctx context.Context, id uint64) error {
|
||||
_, err := s.db.ExecContext(ctx, "DELETE FROM tenants WHERE id=? AND resource_namespace=TRUE AND NOT EXISTS(SELECT 1 FROM projects WHERE tenant_id=?) AND NOT EXISTS(SELECT 1 FROM tenant_backups WHERE tenant_id=?)", id, id, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) ResolveAccount(ctx context.Context, reference string) (uint64, error) {
|
||||
reference = strings.ToLower(strings.TrimSpace(reference))
|
||||
if reference == "" {
|
||||
return 0, nil
|
||||
}
|
||||
var id uint64
|
||||
numeric, _ := strconv.ParseUint(reference, 10, 64)
|
||||
query := `SELECT t.id FROM tenants t JOIN users u ON u.tenant_id=t.id AND u.role='tenant' WHERE t.resource_namespace=FALSE AND t.deleted_at IS NULL AND t.status='active' AND u.status='active' AND (BINARY t.slug=BINARY ? OR BINARY u.login_name=BINARY ?) ORDER BY t.id LIMIT 1`
|
||||
args := []any{reference, reference}
|
||||
if numeric > 0 {
|
||||
query = `SELECT t.id FROM tenants t JOIN users u ON u.tenant_id=t.id AND u.role='tenant' WHERE t.resource_namespace=FALSE AND t.deleted_at IS NULL AND t.status='active' AND u.status='active' AND t.id=?`
|
||||
args = []any{numeric}
|
||||
}
|
||||
err := s.db.QueryRowContext(ctx, query, args...).Scan(&id)
|
||||
if err != nil {
|
||||
return 0, errors.New("用户账号不存在或已停用")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (s *Store) SetAccountEnabled(ctx context.Context, id uint64, enabled bool) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var internal bool
|
||||
if err = tx.QueryRowContext(ctx, "SELECT resource_namespace FROM tenants WHERE id=? AND deleted_at IS NULL FOR UPDATE", id).Scan(&internal); err != nil || internal {
|
||||
return ErrNotFound
|
||||
}
|
||||
status := "disabled"
|
||||
if enabled {
|
||||
status = "active"
|
||||
if _, err = tx.ExecContext(ctx, "UPDATE tenants SET status='active' WHERE id=?", id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, "UPDATE users SET status=? WHERE tenant_id=? AND role='tenant'", status, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, "DELETE i FROM impersonation_sessions i JOIN users u ON u.id=i.target_user_id WHERE u.tenant_id=? AND u.role='tenant'", id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, "DELETE s FROM sessions s JOIN users u ON u.id=s.user_id WHERE u.tenant_id=? AND u.role='tenant'", id); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
type OwnershipChange struct {
|
||||
ProjectID uint64 `json:"projectId"`
|
||||
TargetOwnerID *uint64 `json:"targetOwnerId"`
|
||||
ExpectedVersion uint64 `json:"expectedVersion"`
|
||||
CredentialMode string `json:"credentialMode"`
|
||||
StopServices bool `json:"stopServices"`
|
||||
State string `json:"state"`
|
||||
CredentialsCipher []byte `json:"-"`
|
||||
}
|
||||
|
||||
func (s *Store) OwnershipChange(ctx context.Context, id uint64) (OwnershipChange, error) {
|
||||
var value OwnershipChange
|
||||
err := s.db.QueryRowContext(ctx, "SELECT project_id,target_owner_id,expected_version,credential_mode,stop_services,state,credentials_cipher FROM host_ownership_changes WHERE project_id=?", id).Scan(&value.ProjectID, &value.TargetOwnerID, &value.ExpectedVersion, &value.CredentialMode, &value.StopServices, &value.State, &value.CredentialsCipher)
|
||||
return value, err
|
||||
}
|
||||
func sameOwner(a *uint64, b uint64) bool { return (a == nil && b == 0) || (a != nil && *a == b) }
|
||||
func (s *Store) BeginOwnershipChange(ctx context.Context, id, version, target uint64, mode string, stop, resume bool, cipher []byte) (OwnershipChange, error) {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return OwnershipChange{}, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var owner *uint64
|
||||
var actual uint64
|
||||
var locked bool
|
||||
if err = tx.QueryRowContext(ctx, "SELECT owner_tenant_id,ownership_version,management_locked FROM projects WHERE id=? AND manual_recycled_at IS NULL FOR UPDATE", id).Scan(&owner, &actual, &locked); err != nil {
|
||||
return OwnershipChange{}, err
|
||||
}
|
||||
if actual != version {
|
||||
return OwnershipChange{}, errors.New("主机归属已变化,请重新预览")
|
||||
}
|
||||
if locked {
|
||||
if !resume {
|
||||
return OwnershipChange{}, ErrManagementLocked
|
||||
}
|
||||
var pending OwnershipChange
|
||||
err = tx.QueryRowContext(ctx, "SELECT project_id,target_owner_id,expected_version,credential_mode,stop_services,state,credentials_cipher FROM host_ownership_changes WHERE project_id=?", id).Scan(&pending.ProjectID, &pending.TargetOwnerID, &pending.ExpectedVersion, &pending.CredentialMode, &pending.StopServices, &pending.State, &pending.CredentialsCipher)
|
||||
if err != nil || pending.State != "pending" || !sameOwner(pending.TargetOwnerID, target) || pending.ExpectedVersion != version || pending.CredentialMode != mode || pending.StopServices != stop {
|
||||
return pending, errors.New("恢复任务必须与未完成任务的目标用户和策略一致")
|
||||
}
|
||||
return pending, tx.Commit()
|
||||
}
|
||||
if target > 0 {
|
||||
var found uint64
|
||||
if err = tx.QueryRowContext(ctx, "SELECT t.id FROM tenants t JOIN users u ON u.tenant_id=t.id AND u.role='tenant' WHERE t.id=? AND t.status='active' AND t.resource_namespace=FALSE AND u.status='active' FOR UPDATE", target).Scan(&found); err != nil {
|
||||
return OwnershipChange{}, errors.New("目标账号不可用")
|
||||
}
|
||||
}
|
||||
var targetValue any
|
||||
if target > 0 {
|
||||
targetValue = target
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `INSERT INTO host_ownership_changes(project_id,source_owner_id,target_owner_id,expected_version,credential_mode,stop_services,state,credentials_cipher) VALUES(?,?,?,?,?,?,'pending',?) ON DUPLICATE KEY UPDATE source_owner_id=VALUES(source_owner_id),target_owner_id=VALUES(target_owner_id),expected_version=VALUES(expected_version),credential_mode=VALUES(credential_mode),stop_services=VALUES(stop_services),state='pending',credentials_cipher=VALUES(credentials_cipher)`, id, owner, targetValue, version, mode, stop, cipher)
|
||||
if err != nil {
|
||||
return OwnershipChange{}, err
|
||||
}
|
||||
for _, statement := range []string{"UPDATE user_schedules SET enabled=FALSE,run_requested=FALSE,last_state='ownership_paused' WHERE project_id=?", "UPDATE projects SET management_locked=TRUE WHERE id=?", "UPDATE users SET status='disabled' WHERE project_id=? AND role='host'", "DELETE i FROM impersonation_sessions i JOIN users u ON u.id=i.target_user_id WHERE u.project_id=?", "DELETE s FROM sessions s JOIN users u ON u.id=s.user_id WHERE u.project_id=?"} {
|
||||
if _, err = tx.ExecContext(ctx, statement, id); err != nil {
|
||||
return OwnershipChange{}, err
|
||||
}
|
||||
}
|
||||
result := OwnershipChange{ProjectID: id, ExpectedVersion: version, CredentialMode: mode, StopServices: stop, State: "pending", CredentialsCipher: cipher}
|
||||
if target > 0 {
|
||||
result.TargetOwnerID = &target
|
||||
}
|
||||
return result, tx.Commit()
|
||||
}
|
||||
func (s *Store) CompleteOwnershipChange(ctx context.Context, id, version, target uint64, mode, hostHash string, ftpCipher, dbCipher []byte) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var actual uint64
|
||||
var locked bool
|
||||
if err = tx.QueryRowContext(ctx, "SELECT ownership_version,management_locked FROM projects WHERE id=? FOR UPDATE", id).Scan(&actual, &locked); err != nil {
|
||||
return err
|
||||
}
|
||||
if !locked || actual != version {
|
||||
return errors.New("归属核验状态已变化")
|
||||
}
|
||||
var pendingTarget *uint64
|
||||
var pendingMode, pendingState string
|
||||
if err = tx.QueryRowContext(ctx, "SELECT target_owner_id,credential_mode,state FROM host_ownership_changes WHERE project_id=? FOR UPDATE", id).Scan(&pendingTarget, &pendingMode, &pendingState); err != nil {
|
||||
return err
|
||||
}
|
||||
if !sameOwner(pendingTarget, target) || pendingMode != mode || pendingState != "pending" {
|
||||
return errors.New("归属变更策略已变化")
|
||||
}
|
||||
if target > 0 {
|
||||
var found uint64
|
||||
if err = tx.QueryRowContext(ctx, "SELECT id FROM users WHERE tenant_id=? AND role='tenant' AND status='active' FOR UPDATE", target).Scan(&found); err != nil {
|
||||
return errors.New("目标用户在任务执行期间已停用")
|
||||
}
|
||||
}
|
||||
if mode == "reset" {
|
||||
if hostHash == "" || len(ftpCipher) == 0 || len(dbCipher) == 0 {
|
||||
return errors.New("重置凭据不完整")
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, "UPDATE users SET password_hash=? WHERE project_id=? AND role='host'", hostHash, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, "UPDATE ftp_accounts SET password_ciphertext=? WHERE project_id=?", ftpCipher, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, "UPDATE `databases` SET password_ciphertext=? WHERE project_id=?", dbCipher, id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, "UPDATE certificate_automations SET mode='off',next_attempt_at=NULL WHERE site_id IN (SELECT id FROM sites WHERE project_id=?)", id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, "UPDATE sites SET auto_ssl=FALSE WHERE project_id=?", id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, "UPDATE domains d JOIN dns_credentials c ON c.id=d.dns_credential_id SET d.dns_credential_id=NULL,d.dns_record_id=NULL,d.dns_record_type=NULL,d.dns_last_error=NULL WHERE d.project_id=? AND c.tenant_id IS NOT NULL", id); err != nil {
|
||||
return err
|
||||
}
|
||||
var targetValue any
|
||||
if target > 0 {
|
||||
targetValue = target
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, "UPDATE projects SET owner_tenant_id=?,ownership_version=ownership_version+1,management_locked=FALSE,auto_ssl=FALSE WHERE id=?", targetValue, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, "UPDATE users SET status='active' WHERE project_id=? AND role='host'", id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, "UPDATE host_ownership_changes SET state='completed',credentials_cipher=NULL WHERE project_id=?", id); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
)
|
||||
|
||||
var ErrPlanInUse = errors.New("默认套餐、已被主机或历史账号引用的套餐不能删除;有未完成批量任务时请先等待任务完成")
|
||||
|
||||
func (s *Store) DeleteUnusedPlan(ctx context.Context, id uint64, confirmation string) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var name string
|
||||
if err = tx.QueryRowContext(ctx, "SELECT name FROM plans WHERE id=? FOR UPDATE", id).Scan(&name); errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
if name != confirmation {
|
||||
return errors.New("请准确输入套餐名称确认删除")
|
||||
}
|
||||
var references, pending int
|
||||
if err = tx.QueryRowContext(ctx, `SELECT (SELECT COUNT(*) FROM tenants WHERE plan_id=?)+(SELECT COUNT(*) FROM projects WHERE plan_id=?),(SELECT COUNT(*) FROM admin_batches WHERE state IN ('queued','running'))`, id, id).Scan(&references, &pending); err != nil {
|
||||
return err
|
||||
}
|
||||
if id == 1 || references > 0 || pending > 0 {
|
||||
return ErrPlanInUse
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, "DELETE FROM plans WHERE id=?", id); err != nil {
|
||||
return ErrPlanInUse
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Callers supply hosts already selected through the account/host access scope.
|
||||
// Batch reads avoid a separate usage query for every host in an account view.
|
||||
func (s *Store) FillProjectBandwidth(ctx context.Context, projects []Project) error {
|
||||
byID := make(map[uint64]int, len(projects))
|
||||
for i, p := range projects {
|
||||
byID[p.ID] = i
|
||||
}
|
||||
for start := 0; start < len(projects); start += 500 {
|
||||
end := min(start+500, len(projects))
|
||||
args := make([]any, 0, end-start)
|
||||
for _, p := range projects[start:end] {
|
||||
args = append(args, p.ID)
|
||||
}
|
||||
rows, err := s.db.QueryContext(ctx, "SELECT project_id,bandwidth_bytes FROM project_quota_usage WHERE project_id IN ("+strings.TrimSuffix(strings.Repeat("?,", len(args)), ",")+")", args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for rows.Next() {
|
||||
var id, used uint64
|
||||
if err = rows.Scan(&id, &used); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
if i, ok := byID[id]; ok {
|
||||
projects[i].BandwidthBytes = used
|
||||
}
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
)
|
||||
|
||||
func (s *Store) DeleteCustomDomain(ctx context.Context, id, projectID uint64) error {
|
||||
result, err := s.db.ExecContext(ctx, "DELETE FROM domains WHERE id=? AND project_id=? AND kind='custom' AND dns_record_id IS NULL", id, projectID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := result.RowsAffected(); n != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) ProjectAssignedDomain(ctx context.Context, tenantID, projectID uint64) (string, error) {
|
||||
var domain string
|
||||
err := s.db.QueryRowContext(ctx, "SELECT domain FROM domains WHERE tenant_id=? AND project_id=? AND kind='assigned' ORDER BY id LIMIT 1", tenantID, projectID).Scan(&domain)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
err = ErrNotFound
|
||||
}
|
||||
return domain, err
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"sea-vhost/internal/scope"
|
||||
)
|
||||
|
||||
// Account views aggregate allowances for display only. Every write gate and
|
||||
// measurement requires a project scope derived from an authorized host.
|
||||
func (s *Store) projectPlanAndUsage(ctx context.Context, tenantID uint64) (Plan, Usage, error) {
|
||||
var p Plan
|
||||
var u Usage
|
||||
var measured sql.NullTime
|
||||
id := scope.Project(ctx)
|
||||
if id == 0 {
|
||||
filter, args := customerFilter(ctx, tenantID, "h", "h")
|
||||
err := s.db.QueryRowContext(ctx, `SELECT COALESCE(SUM(l.storage_bytes),0),COALESCE(SUM(l.database_bytes),0),COALESCE(SUM(l.monthly_bandwidth_bytes),0),COALESCE(SUM(l.process_limit),0),COALESCE(SUM(l.ftp_limit),0),COALESCE(SUM(l.database_limit),0),COALESCE(SUM(l.project_limit),0),COALESCE(SUM(q.storage_bytes),0),COALESCE(SUM(q.database_bytes),0),COALESCE(SUM(q.bandwidth_bytes),0),COALESCE(SUM(q.process_count),0),MIN(q.measured_at) FROM projects h JOIN plans l ON l.id=h.plan_id LEFT JOIN project_quota_usage q ON q.project_id=h.id WHERE `+filter+` AND h.status<>'failed' AND h.lifecycle_state<>'purged'`, args...).Scan(&p.StorageBytes, &p.DatabaseBytes, &p.BandwidthBytes, &p.ProcessLimit, &p.FTPLimit, &p.DatabaseLimit, &p.ProjectLimit, &u.StorageBytes, &u.DatabaseBytes, &u.BandwidthBytes, &u.ProcessCount, &measured)
|
||||
p.Name = "主机资源汇总"
|
||||
if measured.Valid {
|
||||
u.MeasuredAt = measured.Time
|
||||
}
|
||||
return p, u, err
|
||||
}
|
||||
err := s.db.QueryRowContext(ctx, `SELECT l.id,l.name,l.storage_bytes,l.database_bytes,l.monthly_bandwidth_bytes,l.bandwidth_mbps,l.process_limit,l.ftp_limit,l.database_limit,l.project_limit,COALESCE(q.storage_bytes,0),COALESCE(q.database_bytes,0),COALESCE(q.bandwidth_bytes,0),COALESCE(q.process_count,0),q.measured_at FROM projects h JOIN plans l ON l.id=h.plan_id LEFT JOIN project_quota_usage q ON q.project_id=h.id WHERE h.id=? AND h.tenant_id=? AND h.lifecycle_state<>'purged'`, id, tenantID).Scan(&p.ID, &p.Name, &p.StorageBytes, &p.DatabaseBytes, &p.BandwidthBytes, &p.BandwidthMbps, &p.ProcessLimit, &p.FTPLimit, &p.DatabaseLimit, &p.ProjectLimit, &u.StorageBytes, &u.DatabaseBytes, &u.BandwidthBytes, &u.ProcessCount, &measured)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
err = ErrNotFound
|
||||
}
|
||||
if measured.Valid {
|
||||
u.MeasuredAt = measured.Time
|
||||
}
|
||||
return p, u, err
|
||||
}
|
||||
|
||||
func (s *Store) TenantOwner(ctx context.Context, id uint64) (User, error) {
|
||||
var uid uint64
|
||||
err := s.db.QueryRowContext(ctx, "SELECT id FROM users WHERE tenant_id=? AND role='tenant' AND status='active' ORDER BY id LIMIT 1", id).Scan(&uid)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
return s.UserByID(ctx, uid)
|
||||
}
|
||||
|
||||
// Port reservations are scoped to the node and kept centrally, including failed
|
||||
// provisioning records until an administrator has reconciled their resources.
|
||||
func (s *Store) AllocateNodePort(ctx context.Context, nodeID uint64) (int, error) {
|
||||
lease, err := s.LockNodeRegistry(ctx, nodeID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer lease.Close()
|
||||
var port int
|
||||
err = lease.conn.QueryRowContext(ctx, `SELECT GREATEST(20000,COALESCE(MAX(backend_port)+20,20000)) FROM projects WHERE node_id=?`, nodeID).Scan(&port)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if port > 59000 {
|
||||
return 0, errors.New("节点运行端口已耗尽")
|
||||
}
|
||||
return port, nil
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Account identities remain reserved after deletion so old imports and external
|
||||
// references cannot accidentally grant access to a different customer.
|
||||
type AccountProfile struct {
|
||||
ID uint64 `json:"id"`
|
||||
Slug string `json:"slug"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
DisplayName string `json:"displayName"`
|
||||
ProjectCount int `json:"projectCount"`
|
||||
}
|
||||
|
||||
func (s *Store) AccountProfile(ctx context.Context, id uint64) (AccountProfile, error) {
|
||||
var p AccountProfile
|
||||
err := s.db.QueryRowContext(ctx, `SELECT t.id,t.slug,t.name,u.email,u.display_name,(SELECT COUNT(*) FROM projects WHERE owner_tenant_id=t.id) FROM tenants t JOIN users u ON u.tenant_id=t.id AND u.role='tenant' WHERE t.id=? AND t.resource_namespace=FALSE AND t.deleted_at IS NULL ORDER BY u.id LIMIT 1`, id).Scan(&p.ID, &p.Slug, &p.Name, &p.Email, &p.DisplayName, &p.ProjectCount)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
err = ErrNotFound
|
||||
}
|
||||
return p, err
|
||||
}
|
||||
func (s *Store) UpdateAccount(ctx context.Context, id uint64, p AccountProfile) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var found uint64
|
||||
if err = tx.QueryRowContext(ctx, `SELECT id FROM tenants WHERE id=? AND resource_namespace=FALSE AND deleted_at IS NULL FOR UPDATE`, id).Scan(&found); err != nil {
|
||||
return ErrNotFound
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `UPDATE tenants SET name=? WHERE id=?`, p.Name, id); err != nil {
|
||||
return err
|
||||
}
|
||||
var conflict int
|
||||
if err = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM users WHERE (email=? OR login_name=?) AND (tenant_id IS NULL OR tenant_id<>?)", p.Email, p.Email, id).Scan(&conflict); err != nil {
|
||||
return err
|
||||
}
|
||||
if conflict > 0 {
|
||||
return errors.New("登录邮箱已被使用")
|
||||
}
|
||||
var previous string
|
||||
if err = tx.QueryRowContext(ctx, "SELECT email FROM users WHERE tenant_id=? AND role='tenant' ORDER BY id LIMIT 1 FOR UPDATE", id).Scan(&previous); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `UPDATE users SET login_name=IF(login_name=email,?,login_name),email=?,display_name=? WHERE tenant_id=? AND role='tenant'`, p.Email, p.Email, p.DisplayName, id); err != nil {
|
||||
return errors.New("登录邮箱已被使用或用户资料无法保存")
|
||||
}
|
||||
if previous != p.Email {
|
||||
for _, q := range []string{"DELETE s FROM sessions s JOIN users u ON u.id=s.user_id WHERE u.tenant_id=? AND u.role='tenant'", "DELETE i FROM impersonation_sessions i JOIN users u ON u.id=i.target_user_id WHERE u.tenant_id=? AND u.role='tenant'"} {
|
||||
if _, err = tx.ExecContext(ctx, q, id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
func (s *Store) DeleteAccount(ctx context.Context, id uint64) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var found uint64
|
||||
if err = tx.QueryRowContext(ctx, `SELECT id FROM tenants WHERE id=? AND resource_namespace=FALSE AND deleted_at IS NULL FOR UPDATE`, id).Scan(&found); err != nil {
|
||||
return ErrNotFound
|
||||
}
|
||||
var count int
|
||||
if err = tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM projects WHERE owner_tenant_id=?`, id).Scan(&count); err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
return errors.New("请先解绑或转移该用户名下的全部主机(包括回收中的主机)")
|
||||
}
|
||||
if err = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM host_ownership_changes WHERE target_owner_id=? AND state='pending'", id).Scan(&count); err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
return errors.New("该用户有未完成的主机归属任务")
|
||||
}
|
||||
for _, q := range []string{
|
||||
`UPDATE tenants SET deleted_at=UTC_TIMESTAMP(),status='suspended' WHERE id=?`,
|
||||
`UPDATE users SET status='disabled' WHERE tenant_id=? AND role='tenant'`,
|
||||
`UPDATE user_schedules SET enabled=FALSE,run_requested=FALSE,last_state='account_deleted' WHERE account_id=?`,
|
||||
`DELETE i FROM impersonation_sessions i JOIN users u ON u.id=i.target_user_id WHERE u.tenant_id=? AND u.role='tenant'`,
|
||||
`DELETE s FROM sessions s JOIN users u ON u.id=s.user_id WHERE u.tenant_id=? AND u.role='tenant'`,
|
||||
} {
|
||||
if _, err = tx.ExecContext(ctx, q, id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) RenameHost(ctx context.Context, id uint64, name string) error {
|
||||
result, err := s.db.ExecContext(ctx, `UPDATE projects SET slug=? WHERE id=? AND management_locked=FALSE AND manual_recycled_at IS NULL`, name, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, _ := result.RowsAffected()
|
||||
if n == 0 {
|
||||
var current string
|
||||
err = s.db.QueryRowContext(ctx, `SELECT slug FROM projects WHERE id=? AND management_locked=FALSE AND manual_recycled_at IS NULL`, id).Scan(¤t)
|
||||
}
|
||||
return err
|
||||
}
|
||||
func (s *Store) RecycleHost(ctx context.Context, id uint64, now time.Time) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var tenant uint64
|
||||
var locked bool
|
||||
var recycled *time.Time
|
||||
if err = tx.QueryRowContext(ctx, `SELECT tenant_id,management_locked,manual_recycled_at FROM projects WHERE id=? FOR UPDATE`, id).Scan(&tenant, &locked, &recycled); err != nil {
|
||||
return ErrNotFound
|
||||
}
|
||||
if locked {
|
||||
return ErrManagementLocked
|
||||
}
|
||||
if recycled != nil {
|
||||
return tx.Commit()
|
||||
} // Retries must not extend the recovery window.
|
||||
if _, err = tx.ExecContext(ctx, `UPDATE projects SET manual_recycled_at=?,lifecycle_state='recycle',purge_after=?,backup_purge_after=?,ownership_version=ownership_version+1,recycle_error='' WHERE id=?`, now, now.Add(7*24*time.Hour), now.Add(21*24*time.Hour), id); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, q := range []string{
|
||||
`UPDATE user_schedules SET enabled=FALSE,run_requested=FALSE,last_state='host_recycled' WHERE project_id=?`,
|
||||
`UPDATE users SET status='disabled' WHERE project_id=? AND role='host'`,
|
||||
`UPDATE ftp_accounts SET enabled=FALSE WHERE project_id=?`,
|
||||
`DELETE i FROM impersonation_sessions i JOIN users u ON u.id=i.target_user_id WHERE u.project_id=?`,
|
||||
`DELETE s FROM sessions s JOIN users u ON u.id=s.user_id WHERE u.project_id=?`,
|
||||
} {
|
||||
if _, err = tx.ExecContext(ctx, q, id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
func (s *Store) HostLifecycle(ctx context.Context, id uint64) (HostLifecycle, error) {
|
||||
var h HostLifecycle
|
||||
err := s.db.QueryRowContext(ctx, `SELECT id,tenant_id,node_id,lifecycle_state,expires_at,grace_until,purge_after,backup_purge_after FROM projects WHERE id=? AND management_locked=FALSE`, id).Scan(&h.ProjectID, &h.TenantID, &h.NodeID, &h.State, &h.ExpiresAt, &h.GraceUntil, &h.PurgeAfter, &h.BackupPurgeAfter)
|
||||
return h, err
|
||||
}
|
||||
func (s *Store) RecordRecycleError(ctx context.Context, id uint64, detail string) error {
|
||||
if len(detail) > 500 {
|
||||
detail = detail[:500]
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE projects SET recycle_error=? WHERE id=? AND manual_recycled_at IS NOT NULL`, detail, id)
|
||||
return err
|
||||
}
|
||||
func (s *Store) RestoreHost(ctx context.Context, id uint64, now time.Time) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var recycled, purge, expiry *time.Time
|
||||
var locked bool
|
||||
var identity bool
|
||||
if err = tx.QueryRowContext(ctx, `SELECT manual_recycled_at,purge_after,expires_at,management_locked,identity_verified FROM projects WHERE id=? FOR UPDATE`, id).Scan(&recycled, &purge, &expiry, &locked, &identity); err != nil {
|
||||
return ErrNotFound
|
||||
}
|
||||
if recycled == nil || purge == nil || !purge.After(now) {
|
||||
return errors.New("主机不在可恢复的 7 天回收期内")
|
||||
}
|
||||
if locked || !identity {
|
||||
return errors.New("请先完成主机身份核验或归属变更")
|
||||
}
|
||||
state := "active"
|
||||
if expiry != nil && !expiry.After(now) {
|
||||
state = "grace"
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `UPDATE projects SET manual_recycled_at=NULL,recycle_error='',lifecycle_state=?,grace_until=IF(?='grace',DATE_ADD(UTC_TIMESTAMP(),INTERVAL 3 DAY),NULL),purge_after=IF(?='grace',DATE_ADD(UTC_TIMESTAMP(),INTERVAL 10 DAY),NULL),backup_purge_after=IF(?='grace',DATE_ADD(UTC_TIMESTAMP(),INTERVAL 24 DAY),NULL),ownership_version=ownership_version+1 WHERE id=?`, state, state, state, state, id); err != nil {
|
||||
return err
|
||||
}
|
||||
// Web and FTP remain stopped; customer schedules require explicit re-enabling.
|
||||
if _, err = tx.ExecContext(ctx, `UPDATE users SET status='active' WHERE project_id=? AND role='host'`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func nodeResourceChecks(ctx context.Context, tx *sql.Tx, id uint64) error {
|
||||
for _, q := range []string{
|
||||
`SELECT COUNT(*) FROM projects WHERE node_id=?`,
|
||||
`SELECT COUNT(*) FROM tenant_backups WHERE node_id=? AND deleted_at IS NULL`,
|
||||
`SELECT COUNT(*) FROM control_tasks WHERE node_id=? AND state IN ('running','uncertain')`,
|
||||
`SELECT COUNT(*) FROM runtime_maintenance_jobs WHERE node_id=? AND active_key IS NOT NULL`,
|
||||
} {
|
||||
var count int
|
||||
if err := tx.QueryRowContext(ctx, q, id).Scan(&count); err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
return errors.New("节点仍有关联主机、备份或未完成任务,请先处理后再操作")
|
||||
}
|
||||
}
|
||||
// Pending batches contain encrypted placement inputs; conservatively wait for
|
||||
// all batches instead of guessing which node a queued item may later select.
|
||||
var batches int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM admin_batches WHERE state IN ('queued','running')`).Scan(&batches); err != nil {
|
||||
return err
|
||||
}
|
||||
if batches > 0 {
|
||||
return errors.New("请等待当前批量任务完成后再操作节点")
|
||||
}
|
||||
var raw []byte
|
||||
if err := tx.QueryRowContext(ctx, `SELECT registry_json FROM control_nodes WHERE id=?`, id).Scan(&raw); err != nil {
|
||||
return err
|
||||
}
|
||||
var registry map[string]json.RawMessage
|
||||
if json.Unmarshal(raw, ®istry) != nil {
|
||||
return errors.New("节点资源登记表损坏,请先核对")
|
||||
}
|
||||
for _, key := range []string{"sites", "ftp", "databases"} {
|
||||
var values map[string]json.RawMessage
|
||||
if json.Unmarshal(registry[key], &values) != nil || len(values) > 0 {
|
||||
return errors.New("节点仍有宝塔资源登记,请先完成资源核对")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Store) UpdateNodeMetadata(ctx context.Context, id uint64, input Node) error {
|
||||
lease, err := s.LockNodeRegistry(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer lease.Close()
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
current, err := scanNode(tx.QueryRowContext(ctx, `SELECT `+nodeColumns+` FROM control_nodes WHERE id=? AND deleted_at IS NULL FOR UPDATE`, id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current.Transport == "local" && (input.Endpoint != current.Endpoint || input.TenantRoot != current.TenantRoot) {
|
||||
return errors.New("本机执行入口和主机根目录由安装配置管理")
|
||||
}
|
||||
if input.Endpoint != current.Endpoint || input.TenantRoot != current.TenantRoot {
|
||||
if current.Enabled {
|
||||
return errors.New("修改执行入口或根目录前必须停用节点")
|
||||
}
|
||||
if err = nodeResourceChecks(ctx, tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `UPDATE control_nodes SET last_seen_at=IF(endpoint<>?,NULL,last_seen_at),name=?,endpoint=?,root_domain=?,tenant_root=?,ftp_certificate_domain=? WHERE id=?`, input.Endpoint, input.Name, input.Endpoint, input.RootDomain, input.TenantRoot, input.FTPCertificateDomain, id)
|
||||
if err != nil {
|
||||
return errors.New("节点配置无法保存,请检查执行入口是否重复")
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
func (s *Store) DeleteNode(ctx context.Context, id uint64) error {
|
||||
if id == 1 {
|
||||
return errors.New("本机节点禁止删除")
|
||||
}
|
||||
lease, err := s.LockNodeRegistry(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer lease.Close()
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var enabled bool
|
||||
if err = tx.QueryRowContext(ctx, `SELECT enabled FROM control_nodes WHERE id=? AND deleted_at IS NULL FOR UPDATE`, id).Scan(&enabled); err != nil {
|
||||
return ErrNotFound
|
||||
}
|
||||
if enabled {
|
||||
return errors.New("请先停用节点")
|
||||
}
|
||||
if err = nodeResourceChecks(ctx, tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `UPDATE control_nodes SET deleted_at=UTC_TIMESTAMP(),credentials=NULL,enabled=FALSE WHERE id=?`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `DELETE FROM ip_pool WHERE node_id=?`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) SetRuntimePolicy(ctx context.Context, id uint64, allowed bool) error {
|
||||
_, err := s.db.ExecContext(ctx, "UPDATE projects SET allow_runtime_change=? WHERE id=? AND management_locked=FALSE AND manual_recycled_at IS NULL", allowed, id)
|
||||
return err
|
||||
}
|
||||
func (s *Store) ChangeSiteLanguage(ctx context.Context, site Site, runtime, version, status string) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
r, err := tx.ExecContext(ctx, "UPDATE sites SET runtime=?,runtime_version=?,status=? WHERE id=? AND project_id=? AND runtime=? AND runtime_version=?", runtime, version, status, site.ID, site.ProjectID, site.Runtime, site.Version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, _ := r.RowsAffected()
|
||||
if n != 1 {
|
||||
return errors.New("站点环境已变更")
|
||||
}
|
||||
if site.Primary {
|
||||
if _, err = tx.ExecContext(ctx, "UPDATE projects SET runtime=?,runtime_version=?,status=? WHERE id=?", runtime, version, status, site.ProjectID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Keep website preferences; startup commands from another language are incompatible.
|
||||
if _, err = tx.ExecContext(ctx, "UPDATE site_preferences SET startup_cipher=NULL WHERE site_id=?", site.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// Recycled hosts may only be detached explicitly; they cannot be reassigned or restarted here.
|
||||
func (s *Store) DetachRecycledHost(ctx context.Context, id, version uint64, confirmation string) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var host string
|
||||
var actual uint64
|
||||
var recycled, locked bool
|
||||
if err = tx.QueryRowContext(ctx, "SELECT host_name,ownership_version,manual_recycled_at IS NOT NULL,management_locked FROM projects WHERE id=? FOR UPDATE", id).Scan(&host, &actual, &recycled, &locked); err != nil {
|
||||
return ErrNotFound
|
||||
}
|
||||
if !recycled || locked || actual != version || host != confirmation {
|
||||
return errors.New("主机状态或归属版本已变更,请刷新后重试")
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, "UPDATE projects SET owner_tenant_id=NULL,ownership_version=ownership_version+1 WHERE id=?", id); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"sea-vhost/internal/scope"
|
||||
"time"
|
||||
)
|
||||
|
||||
type RuntimeJob struct {
|
||||
OwnershipVersion *uint64 `json:"-"`
|
||||
NodeID uint64 `json:"nodeId"`
|
||||
ID uint64 `json:"id"`
|
||||
Action string `json:"action"`
|
||||
Runtime string `json:"runtime"`
|
||||
FromVersion string `json:"fromVersion"`
|
||||
TargetVersion string `json:"targetVersion"`
|
||||
EntryFile string `json:"entryFile,omitempty"`
|
||||
SiteID *uint64 `json:"siteId,omitempty"`
|
||||
Status string `json:"status"`
|
||||
Phase string `json:"phase"`
|
||||
Message string `json:"message"`
|
||||
RollbackData string `json:"-"`
|
||||
BackupAvailable bool `json:"backupAvailable"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
type RuntimeTarget struct {
|
||||
Site Site `json:"site"`
|
||||
Project Project `json:"-"`
|
||||
HostName string `json:"hostName"`
|
||||
InstalledVersion string `json:"installedVersion"`
|
||||
RunningVersion string `json:"runningVersion"`
|
||||
Healthy bool `json:"healthy"`
|
||||
Detail string `json:"detail"`
|
||||
CheckedAt *time.Time `json:"checkedAt,omitempty"`
|
||||
}
|
||||
|
||||
const runtimeJobColumns = `id,node_id,action,runtime,from_version,target_version,entry_file,site_id,status,phase,COALESCE(message,''),COALESCE(rollback_data,''),backup_available,created_at,updated_at,ownership_version`
|
||||
|
||||
func scanRuntimeJob(row interface{ Scan(...any) error }) (RuntimeJob, error) {
|
||||
var j RuntimeJob
|
||||
err := row.Scan(&j.ID, &j.NodeID, &j.Action, &j.Runtime, &j.FromVersion, &j.TargetVersion, &j.EntryFile, &j.SiteID, &j.Status, &j.Phase, &j.Message, &j.RollbackData, &j.BackupAvailable, &j.CreatedAt, &j.UpdatedAt, &j.OwnershipVersion)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
err = ErrNotFound
|
||||
}
|
||||
return j, err
|
||||
}
|
||||
func (s *Store) CreateRuntimeJob(ctx context.Context, j RuntimeJob) (uint64, error) {
|
||||
blocked, checkErr := s.NodeHasUnresolvedTask(scope.WithProject(ctx, 0, scope.Node(ctx)), scope.Node(ctx))
|
||||
if checkErr != nil {
|
||||
return 0, checkErr
|
||||
}
|
||||
if blocked {
|
||||
return 0, errors.New("请先核验该节点的待确认操作,再提交环境维护任务")
|
||||
}
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var nodeLock uint64
|
||||
if err = tx.QueryRowContext(ctx, "SELECT id FROM control_nodes WHERE id=? AND enabled=TRUE FOR UPDATE", scope.Node(ctx)).Scan(&nodeLock); err != nil {
|
||||
return 0, ErrNotFound
|
||||
}
|
||||
var pending int
|
||||
if err = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM runtime_maintenance_jobs WHERE node_id=? AND active_key IS NOT NULL", scope.Node(ctx)).Scan(&pending); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if pending >= 20 {
|
||||
return 0, errors.New("当前节点最多保留 20 项待处理的环境任务")
|
||||
}
|
||||
r, err := tx.ExecContext(ctx, `INSERT INTO runtime_maintenance_jobs(node_id,action,runtime,from_version,target_version,entry_file,site_id,active_key,ownership_version) VALUES(?,?,?,?,?,?,?,?,?)`, scope.Node(ctx), j.Action, j.Runtime, j.FromVersion, j.TargetVersion, j.EntryFile, j.SiteID, runtimeJobKey(scope.Node(ctx), j), j.OwnershipVersion)
|
||||
if err != nil {
|
||||
var dbErr *mysql.MySQLError
|
||||
if errors.As(err, &dbErr) && dbErr.Number == 1062 {
|
||||
return 0, errors.New("相同的运行环境任务已在队列中,请勿重复提交")
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
id, err := r.LastInsertId()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return uint64(id), nil
|
||||
}
|
||||
func (s *Store) RuntimeJobs(ctx context.Context) ([]RuntimeJob, error) {
|
||||
rows, err := s.db.QueryContext(ctx, "SELECT "+runtimeJobColumns+" FROM runtime_maintenance_jobs WHERE node_id=? ORDER BY id DESC LIMIT 50", scope.Node(ctx))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]RuntimeJob, 0)
|
||||
for rows.Next() {
|
||||
j, err := scanRuntimeJob(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, j)
|
||||
}
|
||||
return items, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) RuntimeMutationBlocked(ctx context.Context) (bool, error) {
|
||||
var count int
|
||||
// Panel component updates do not own tenant resources. Only an unfinished
|
||||
// configuration switch on this host may block its mutations.
|
||||
err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM runtime_maintenance_jobs WHERE node_id=? AND status IN ('running','interrupted') AND action IN ('migrate','runtime_change') AND ?<>0 AND site_id IN (SELECT id FROM sites WHERE project_id=?)`, scope.Node(ctx), scope.Project(ctx), scope.Project(ctx)).Scan(&count)
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
func (s *Store) RuntimeJob(ctx context.Context, id uint64) (RuntimeJob, error) {
|
||||
return scanRuntimeJob(s.db.QueryRowContext(ctx, "SELECT "+runtimeJobColumns+" FROM runtime_maintenance_jobs WHERE id=?", id))
|
||||
}
|
||||
func (s *Store) ClaimRuntimeJob(ctx context.Context) (RuntimeJob, error) {
|
||||
j, err := scanRuntimeJob(s.db.QueryRowContext(ctx, "SELECT "+runtimeJobColumns+" FROM runtime_maintenance_jobs WHERE status='queued' AND node_id IN (SELECT id FROM control_nodes WHERE enabled=TRUE) AND node_id NOT IN (SELECT running_node_id FROM runtime_maintenance_jobs WHERE running_node_id IS NOT NULL) ORDER BY id LIMIT 1"))
|
||||
if err != nil {
|
||||
return j, err
|
||||
}
|
||||
r, err := s.db.ExecContext(ctx, "UPDATE runtime_maintenance_jobs SET status='running' WHERE id=? AND status='queued'", j.ID)
|
||||
if err != nil {
|
||||
var conflict *mysql.MySQLError
|
||||
if errors.As(err, &conflict) && conflict.Number == 1062 {
|
||||
return j, ErrNotFound
|
||||
}
|
||||
return j, err
|
||||
}
|
||||
n, _ := r.RowsAffected()
|
||||
if n != 1 {
|
||||
return j, ErrNotFound
|
||||
}
|
||||
j.Status = "running"
|
||||
return j, nil
|
||||
}
|
||||
func (s *Store) UpdateRuntimeJob(ctx context.Context, id uint64, status, phase, message string) error {
|
||||
job, err := s.RuntimeJob(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var active any = runtimeJobKey(job.NodeID, job)
|
||||
if status == "completed" || status == "failed" || status == "rolled_back" {
|
||||
active = nil
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx, "UPDATE runtime_maintenance_jobs SET status=?,phase=?,message=?,active_key=? WHERE id=?", status, phase, message, active, id)
|
||||
return err
|
||||
}
|
||||
func (s *Store) SaveRuntimeRollback(ctx context.Context, id uint64, data string, backup bool) error {
|
||||
_, err := s.db.ExecContext(ctx, "UPDATE runtime_maintenance_jobs SET rollback_data=?,backup_available=? WHERE id=?", data, backup, id)
|
||||
return err
|
||||
}
|
||||
func (s *Store) InterruptRuntimeJobs(ctx context.Context) error {
|
||||
_, err := s.db.ExecContext(ctx, "UPDATE runtime_maintenance_jobs SET status='interrupted',message='服务重启,任务状态待核验。请执行恢复核验。' WHERE status='running'")
|
||||
return err
|
||||
}
|
||||
func (s *Store) RetryRuntimeJob(ctx context.Context, id uint64) error {
|
||||
r, err := s.db.ExecContext(ctx, "UPDATE runtime_maintenance_jobs SET status='queued' WHERE id=? AND node_id=? AND status='interrupted'", id, scope.Node(ctx))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, _ := r.RowsAffected()
|
||||
if n != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Store) RuntimeTargets(ctx context.Context) ([]RuntimeTarget, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT s.id,s.tenant_id,s.project_id,s.slug,s.assigned_domain,s.run_path,s.runtime,s.runtime_version,s.status,COALESCE(s.panel_site_id,0),COALESCE(s.backend_port,0),s.process_limit,s.is_primary,p.host_name,p.root_path,p.node_id,COALESCE(p.plan_id,0),COALESCE(o.installed_version,''),COALESCE(o.running_version,''),COALESCE(o.healthy,0),COALESCE(o.detail,''),o.checked_at FROM sites s JOIN projects p ON p.id=s.project_id LEFT JOIN site_runtime_observations o ON o.site_id=s.id WHERE s.status<>'failed' AND p.node_id=? ORDER BY s.id`, scope.Node(ctx))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]RuntimeTarget, 0)
|
||||
for rows.Next() {
|
||||
var t RuntimeTarget
|
||||
if err = rows.Scan(&t.Site.ID, &t.Site.TenantID, &t.Site.ProjectID, &t.Site.Name, &t.Site.Domain, &t.Site.RunPath, &t.Site.Runtime, &t.Site.Version, &t.Site.Status, &t.Site.PanelSiteID, &t.Site.BackendPort, &t.Site.ProcessLimit, &t.Site.Primary, &t.HostName, &t.Project.Path, &t.Project.NodeID, &t.Project.PlanID, &t.InstalledVersion, &t.RunningVersion, &t.Healthy, &t.Detail, &t.CheckedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.Project.ID = t.Site.ProjectID
|
||||
t.Project.TenantID = t.Site.TenantID
|
||||
t.Project.HostName = t.HostName
|
||||
items = append(items, t)
|
||||
}
|
||||
return items, rows.Err()
|
||||
}
|
||||
func (s *Store) SaveRuntimeObservation(ctx context.Context, siteID uint64, installed, running string, healthy bool, detail string) error {
|
||||
if len(detail) > 500 {
|
||||
detail = detail[:500]
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `INSERT INTO site_runtime_observations(site_id,installed_version,running_version,healthy,detail) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE installed_version=VALUES(installed_version),running_version=VALUES(running_version),healthy=VALUES(healthy),detail=VALUES(detail),checked_at=CURRENT_TIMESTAMP`, siteID, installed, running, healthy, detail)
|
||||
return err
|
||||
}
|
||||
func (s *Store) ChangeSiteRuntimeVersion(ctx context.Context, site Site, target string) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
r, err := tx.ExecContext(ctx, "UPDATE sites SET runtime_version=? WHERE id=? AND tenant_id=? AND project_id=? AND runtime_version=?", target, site.ID, site.TenantID, site.ProjectID, site.Version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, _ := r.RowsAffected()
|
||||
if n != 1 {
|
||||
return errors.New("站点版本已被其他任务修改")
|
||||
}
|
||||
if site.Primary {
|
||||
if _, err = tx.ExecContext(ctx, "UPDATE projects SET runtime_version=? WHERE id=? AND tenant_id=?", target, site.ProjectID, site.TenantID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
func (s *Store) NotifyRuntimeRelease(ctx context.Context, key, title, detail string) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
r, err := tx.ExecContext(ctx, "INSERT IGNORE INTO runtime_update_notices(node_id,release_key) VALUES(?,?)", scope.Node(ctx), key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, _ := r.RowsAffected()
|
||||
if n == 0 {
|
||||
return nil
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `INSERT INTO admin_notifications(severity,category,title,detail,next_attempt_at) VALUES('warning','runtime',?,?,UTC_TIMESTAMP())`, title, detail); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// A duplicate operation is rejected, while unrelated work may wait on the same node.
|
||||
func runtimeJobKey(node uint64, j RuntimeJob) string {
|
||||
var site uint64
|
||||
if j.SiteID != nil {
|
||||
site = *j.SiteID
|
||||
return fmt.Sprintf("site/%d", site)
|
||||
}
|
||||
return fmt.Sprintf("node/%d/%s/%s/%s/%d", node, j.Action, j.Runtime, j.TargetVersion, site)
|
||||
}
|
||||
|
||||
func (s *Store) HostOwnershipVersion(ctx context.Context, id uint64) (uint64, error) {
|
||||
var version uint64
|
||||
err := s.db.QueryRowContext(ctx, "SELECT ownership_version FROM projects WHERE id=? AND management_locked=FALSE AND manual_recycled_at IS NULL", id).Scan(&version)
|
||||
return version, err
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sea-vhost/internal/hosting"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Store) WebsiteSettings(ctx context.Context, id uint64) (hosting.WebsiteSettings, error) {
|
||||
v := hosting.DefaultWebsite()
|
||||
var raw []byte
|
||||
e := s.db.QueryRowContext(ctx, "SELECT website_json FROM site_preferences WHERE site_id=?", id).Scan(&raw)
|
||||
if errors.Is(e, sql.ErrNoRows) {
|
||||
return v, nil
|
||||
}
|
||||
if e == nil && len(raw) > 0 {
|
||||
e = json.Unmarshal(raw, &v)
|
||||
}
|
||||
return v, e
|
||||
}
|
||||
func (s *Store) SaveWebsiteSettings(ctx context.Context, id uint64, v hosting.WebsiteSettings) error {
|
||||
raw, e := json.Marshal(v)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
_, e = s.db.ExecContext(ctx, "INSERT INTO site_preferences(site_id,website_json) VALUES(?,?) ON DUPLICATE KEY UPDATE website_json=VALUES(website_json)", id, raw)
|
||||
return e
|
||||
}
|
||||
func (s *Store) StartupCipher(ctx context.Context, id uint64) ([]byte, error) {
|
||||
var v []byte
|
||||
e := s.db.QueryRowContext(ctx, "SELECT startup_cipher FROM site_preferences WHERE site_id=?", id).Scan(&v)
|
||||
if errors.Is(e, sql.ErrNoRows) {
|
||||
e = nil
|
||||
}
|
||||
return v, e
|
||||
}
|
||||
func (s *Store) SaveStartupCipher(ctx context.Context, id uint64, v []byte) error {
|
||||
_, e := s.db.ExecContext(ctx, "INSERT INTO site_preferences(site_id,startup_cipher) VALUES(?,?) ON DUPLICATE KEY UPDATE startup_cipher=VALUES(startup_cipher)", id, v)
|
||||
return e
|
||||
}
|
||||
|
||||
type HostMetric struct {
|
||||
SampledAt time.Time `json:"sampledAt"`
|
||||
CPUPercent float64 `json:"cpuPercent"`
|
||||
CPUTicks uint64 `json:"-"`
|
||||
MemoryBytes uint64 `json:"memoryBytes"`
|
||||
ProcessCount uint32 `json:"processCount"`
|
||||
StorageBytes uint64 `json:"storageBytes"`
|
||||
DatabaseBytes uint64 `json:"databaseBytes"`
|
||||
BandwidthBytes uint64 `json:"bandwidthBytes"`
|
||||
}
|
||||
|
||||
func (s *Store) RecordHostMetric(ctx context.Context, id uint64, v HostMetric) error {
|
||||
v.SampledAt = time.Now().UTC().Truncate(time.Minute)
|
||||
var ticks uint64
|
||||
var previous time.Time
|
||||
e := s.db.QueryRowContext(ctx, "SELECT sampled_at,cpu_ticks FROM host_metrics WHERE project_id=? AND sampled_at<? ORDER BY sampled_at DESC LIMIT 1", id, v.SampledAt).Scan(&previous, &ticks)
|
||||
if e == nil && v.CPUTicks >= ticks && v.SampledAt.Sub(previous) <= 10*time.Minute {
|
||||
v.CPUPercent = float64(v.CPUTicks-ticks) / v.SampledAt.Sub(previous).Seconds()
|
||||
}
|
||||
_, e = s.db.ExecContext(ctx, `INSERT INTO host_metrics(project_id,sampled_at,cpu_percent,cpu_ticks,memory_bytes,process_count,storage_bytes,database_bytes,bandwidth_bytes) VALUES(?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE memory_bytes=VALUES(memory_bytes),process_count=VALUES(process_count),storage_bytes=VALUES(storage_bytes),database_bytes=VALUES(database_bytes),bandwidth_bytes=VALUES(bandwidth_bytes)`, id, v.SampledAt, v.CPUPercent, v.CPUTicks, v.MemoryBytes, v.ProcessCount, v.StorageBytes, v.DatabaseBytes, v.BandwidthBytes)
|
||||
return e
|
||||
}
|
||||
func (s *Store) HostMetrics(ctx context.Context, id uint64, days int) ([]HostMetric, error) {
|
||||
if days < 1 || days > 30 {
|
||||
days = 1
|
||||
}
|
||||
rows, e := s.db.QueryContext(ctx, `SELECT sampled_at,cpu_percent,memory_bytes,process_count,storage_bytes,database_bytes,bandwidth_bytes FROM host_metrics WHERE project_id=? AND sampled_at>=? ORDER BY sampled_at`, id, time.Now().UTC().Add(-time.Duration(days)*24*time.Hour))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer rows.Close()
|
||||
values := []HostMetric{}
|
||||
for rows.Next() {
|
||||
var v HostMetric
|
||||
if e = rows.Scan(&v.SampledAt, &v.CPUPercent, &v.MemoryBytes, &v.ProcessCount, &v.StorageBytes, &v.DatabaseBytes, &v.BandwidthBytes); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
values = append(values, v)
|
||||
}
|
||||
if len(values) > 1440 {
|
||||
step := (len(values) + 1439) / 1440
|
||||
reduced := []HostMetric{}
|
||||
for i := 0; i < len(values); i += step {
|
||||
reduced = append(reduced, values[i])
|
||||
}
|
||||
values = reduced
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
func (s *Store) PruneHostMetrics(ctx context.Context) error {
|
||||
_, e := s.db.ExecContext(ctx, "DELETE FROM host_metrics WHERE sampled_at<DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 DAY)")
|
||||
return e
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
type PendingOIDCLogin struct {
|
||||
Provider string
|
||||
Subject string
|
||||
Email string
|
||||
DisplayName string
|
||||
EmailVerified bool
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
func (s *Store) CreateScopedOIDCState(ctx context.Context, state string, userID *uint64, mode, verifier, nonce, provider, sessionToken string, expires time.Time) error {
|
||||
hash := sha256.Sum256([]byte(state))
|
||||
var parent any
|
||||
if sessionToken != "" {
|
||||
value := sha256.Sum256([]byte(sessionToken))
|
||||
parent = value[:]
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx, `INSERT INTO oidc_states(state_hash,user_id,mode,verifier,nonce,expires_at,provider_key,session_token_hash) VALUES(?,?,?,?,?,?,?,?)`, hash[:], userID, mode, verifier, nonce, expires, provider, parent)
|
||||
return err
|
||||
}
|
||||
func (s *Store) CreatePendingOIDCLogin(ctx context.Context, token string, p PendingOIDCLogin) error {
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
_, err := s.db.ExecContext(ctx, `DELETE FROM oidc_pending_logins WHERE expires_at<=?`, time.Now().UTC())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx, `INSERT INTO oidc_pending_logins(token_hash,provider,subject,email,display_name,email_verified,expires_at) VALUES(?,?,?,?,?,?,?)`, hash[:], p.Provider, p.Subject, p.Email, p.DisplayName, p.EmailVerified, p.ExpiresAt)
|
||||
return err
|
||||
}
|
||||
func (s *Store) PendingOIDCLogin(ctx context.Context, token string) (PendingOIDCLogin, error) {
|
||||
var p PendingOIDCLogin
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
err := s.db.QueryRowContext(ctx, `SELECT provider,subject,email,display_name,email_verified,expires_at FROM oidc_pending_logins WHERE token_hash=? AND expires_at>?`, hash[:], time.Now().UTC()).Scan(&p.Provider, &p.Subject, &p.Email, &p.DisplayName, &p.EmailVerified, &p.ExpiresAt)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
err = ErrNotFound
|
||||
}
|
||||
return p, err
|
||||
}
|
||||
|
||||
// CompletePendingOIDC commits the identity and optional ordinary account together.
|
||||
// A consumed ticket, duplicate identity or duplicate email cannot leave an orphan account.
|
||||
func (s *Store) CompletePendingOIDC(ctx context.Context, token, expectedProvider string, targetID uint64, input *NewTenant) (uint64, error) {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
var p PendingOIDCLogin
|
||||
err = tx.QueryRowContext(ctx, `SELECT provider,subject,email,display_name,email_verified,expires_at FROM oidc_pending_logins WHERE token_hash=? FOR UPDATE`, hash[:]).Scan(&p.Provider, &p.Subject, &p.Email, &p.DisplayName, &p.EmailVerified, &p.ExpiresAt)
|
||||
if err != nil || p.Provider != expectedProvider || !p.ExpiresAt.After(time.Now().UTC()) {
|
||||
return 0, ErrNotFound
|
||||
}
|
||||
if input != nil {
|
||||
if !p.EmailVerified || p.Email != input.Email {
|
||||
return 0, errors.New("SSO 邮箱尚未验证")
|
||||
}
|
||||
// The supplied password is already an irreversible hash of an unguessable secret.
|
||||
result, e := tx.ExecContext(ctx, `INSERT INTO tenants(slug,name,plan_id) VALUES(?,?,?)`, input.Slug, input.Name, input.PlanID)
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
namespace, e := result.LastInsertId()
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
result, e = tx.ExecContext(ctx, `INSERT INTO users(tenant_id,login_name,email,display_name,password_hash,role) VALUES(?,?,?,?,?,'tenant')`, namespace, input.Email, input.Email, input.DisplayName, input.Password)
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
id, e := result.LastInsertId()
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
targetID = uint64(id)
|
||||
}
|
||||
var role, status string
|
||||
if err = tx.QueryRowContext(ctx, `SELECT u.role,u.status FROM users u LEFT JOIN tenants t ON t.id=u.tenant_id WHERE u.id=? AND (u.tenant_id IS NULL OR (t.status='active' AND t.deleted_at IS NULL)) FOR UPDATE`, targetID).Scan(&role, &status); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if role == "host" || status != "active" {
|
||||
return 0, errors.New("该账号不能绑定 SSO")
|
||||
}
|
||||
// Never silently replace an existing binding of the target account.
|
||||
if _, err = tx.ExecContext(ctx, `INSERT INTO sso_identities(user_id,provider,subject,email) VALUES(?,?,?,?)`, targetID, p.Provider, p.Subject, p.Email); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `DELETE FROM oidc_pending_logins WHERE token_hash=?`, hash[:]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return targetID, nil
|
||||
}
|
||||
|
||||
func (s *Store) ActiveOIDCBindSession(ctx context.Context, hash []byte, userID uint64) bool {
|
||||
if len(hash) != 32 {
|
||||
return false
|
||||
}
|
||||
var id uint64
|
||||
if s.db.QueryRowContext(ctx, `SELECT user_id FROM sessions WHERE token_hash=? AND user_id=? AND expires_at>NOW()`, hash, userID).Scan(&id) != nil {
|
||||
return false
|
||||
}
|
||||
u, e := s.UserByID(ctx, id)
|
||||
return e == nil && u.Role != "host"
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,266 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Store) ProjectOwnershipVersion(ctx context.Context, id uint64) (uint64, error) {
|
||||
var version uint64
|
||||
e := s.db.QueryRowContext(ctx, "SELECT ownership_version FROM projects WHERE id=?", id).Scan(&version)
|
||||
return version, e
|
||||
}
|
||||
func (s *Store) LastSchedulerTick(ctx context.Context) (*time.Time, error) {
|
||||
var v *time.Time
|
||||
e := s.db.QueryRowContext(ctx, "SELECT MAX(created_at) FROM scheduler_ticks").Scan(&v)
|
||||
return v, e
|
||||
}
|
||||
func (s *Store) ScheduleSitePort(ctx context.Context, id uint64, https bool) (int, error) {
|
||||
var port int
|
||||
column := "http_port"
|
||||
fallback := 80
|
||||
if https {
|
||||
column = "https_port"
|
||||
fallback = 443
|
||||
}
|
||||
e := s.db.QueryRowContext(ctx, "SELECT COALESCE(n."+column+",?) FROM sites s LEFT JOIN site_networks n ON n.site_id=s.id WHERE s.id=?", fallback, id).Scan(&port)
|
||||
return port, e
|
||||
}
|
||||
|
||||
type UserSchedule struct {
|
||||
SecretRef string `json:"-"`
|
||||
ConfigCipher []byte `json:"-"`
|
||||
ID uint64 `json:"id"`
|
||||
UserID uint64 `json:"-"`
|
||||
AccountID uint64 `json:"-"`
|
||||
ProjectID uint64 `json:"projectId"`
|
||||
SiteID uint64 `json:"siteId"`
|
||||
OwnershipVersion uint64 `json:"-"`
|
||||
Name string `json:"name"`
|
||||
Cron string `json:"cron"`
|
||||
Timezone string `json:"timezone"`
|
||||
Kind string `json:"kind"`
|
||||
Version string `json:"version"`
|
||||
Target string `json:"target"`
|
||||
Arguments []string `json:"arguments"`
|
||||
UseHTTPS bool `json:"useHTTPS"`
|
||||
Enabled bool `json:"enabled"`
|
||||
NextRunAt time.Time `json:"nextRunAt"`
|
||||
LastState string `json:"lastState"`
|
||||
}
|
||||
|
||||
const scheduleFields = `id,user_id,account_id,project_id,site_id,ownership_version,name,cron_expression,timezone,kind,runtime_version,target,arguments_json,use_https,enabled,next_run_at,last_state,secret_ref,config_cipher`
|
||||
|
||||
func scanSchedule(row rowScanner) (UserSchedule, error) {
|
||||
var v UserSchedule
|
||||
var args []byte
|
||||
e := row.Scan(&v.ID, &v.UserID, &v.AccountID, &v.ProjectID, &v.SiteID, &v.OwnershipVersion, &v.Name, &v.Cron, &v.Timezone, &v.Kind, &v.Version, &v.Target, &args, &v.UseHTTPS, &v.Enabled, &v.NextRunAt, &v.LastState, &v.SecretRef, &v.ConfigCipher)
|
||||
if e == nil {
|
||||
e = json.Unmarshal(args, &v.Arguments)
|
||||
}
|
||||
return v, e
|
||||
}
|
||||
func (s *Store) UserSchedules(ctx context.Context, user uint64) ([]UserSchedule, error) {
|
||||
rows, e := s.db.QueryContext(ctx, "SELECT "+scheduleFields+" FROM user_schedules WHERE user_id=? ORDER BY id DESC", user)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []UserSchedule{}
|
||||
for rows.Next() {
|
||||
v, e := scanSchedule(rows)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (s *Store) UserSchedule(ctx context.Context, user, id uint64) (UserSchedule, error) {
|
||||
return scanSchedule(s.db.QueryRowContext(ctx, "SELECT "+scheduleFields+" FROM user_schedules WHERE user_id=? AND id=?", user, id))
|
||||
}
|
||||
func (s *Store) SaveUserSchedule(ctx context.Context, v UserSchedule) (uint64, error) {
|
||||
tx, e := s.db.BeginTx(ctx, nil)
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var owner, version uint64
|
||||
var locked bool
|
||||
if e = tx.QueryRowContext(ctx, "SELECT COALESCE(owner_tenant_id,0),ownership_version,management_locked FROM projects WHERE id=? FOR UPDATE", v.ProjectID).Scan(&owner, &version, &locked); e != nil || locked || owner != v.AccountID || version != v.OwnershipVersion {
|
||||
return 0, ErrNotFound
|
||||
}
|
||||
var uid uint64
|
||||
if e = tx.QueryRowContext(ctx, "SELECT id FROM users WHERE id=? AND tenant_id=? AND role='tenant' AND status='active' FOR UPDATE", v.UserID, v.AccountID).Scan(&uid); e != nil {
|
||||
return 0, ErrNotFound
|
||||
}
|
||||
var count int
|
||||
if e = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM user_schedules WHERE user_id=?", v.UserID).Scan(&count); e != nil {
|
||||
return 0, e
|
||||
}
|
||||
if v.ID == 0 && count >= 10 {
|
||||
return 0, errors.New("每个用户最多 10 条计划任务")
|
||||
}
|
||||
args, _ := json.Marshal(v.Arguments)
|
||||
if v.ID == 0 {
|
||||
r, e := tx.ExecContext(ctx, `INSERT INTO user_schedules(user_id,account_id,project_id,site_id,ownership_version,name,cron_expression,timezone,kind,runtime_version,target,arguments_json,use_https,enabled,next_run_at,secret_ref,config_cipher) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, v.UserID, v.AccountID, v.ProjectID, v.SiteID, v.OwnershipVersion, v.Name, v.Cron, v.Timezone, v.Kind, v.Version, v.Target, args, v.UseHTTPS, v.Enabled, v.NextRunAt, v.SecretRef, v.ConfigCipher)
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
id, _ := r.LastInsertId()
|
||||
v.ID = uint64(id)
|
||||
} else {
|
||||
var running *time.Time
|
||||
if e = tx.QueryRowContext(ctx, "SELECT running_until FROM user_schedules WHERE id=? AND user_id=? FOR UPDATE", v.ID, v.UserID).Scan(&running); e != nil {
|
||||
return 0, e
|
||||
}
|
||||
if running != nil && running.After(time.Now()) {
|
||||
return 0, errors.New("任务正在运行,暂不能编辑")
|
||||
}
|
||||
_, e = tx.ExecContext(ctx, `UPDATE user_schedules SET project_id=?,site_id=?,ownership_version=?,name=?,cron_expression=?,timezone=?,kind=?,runtime_version=?,target=?,arguments_json=?,use_https=?,enabled=?,next_run_at=?,secret_ref=?,config_cipher=?,last_state='ready' WHERE id=? AND user_id=?`, v.ProjectID, v.SiteID, v.OwnershipVersion, v.Name, v.Cron, v.Timezone, v.Kind, v.Version, v.Target, args, v.UseHTTPS, v.Enabled, v.NextRunAt, v.SecretRef, v.ConfigCipher, v.ID, v.UserID)
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
}
|
||||
return v.ID, tx.Commit()
|
||||
}
|
||||
func (s *Store) DeleteUserSchedule(ctx context.Context, user, id uint64) error {
|
||||
r, e := s.db.ExecContext(ctx, "DELETE FROM user_schedules WHERE user_id=? AND id=? AND (running_until IS NULL OR running_until<UTC_TIMESTAMP())", user, id)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
n, _ := r.RowsAffected()
|
||||
if n != 1 {
|
||||
return errors.New("任务不存在或正在执行")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Store) RequestUserScheduleRun(ctx context.Context, user, id uint64) error {
|
||||
r, e := s.db.ExecContext(ctx, "UPDATE user_schedules SET run_requested=TRUE WHERE user_id=? AND id=? AND (running_until IS NULL OR running_until<UTC_TIMESTAMP()) AND last_state<>'ownership_paused'", user, id)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
n, _ := r.RowsAffected()
|
||||
if n < 1 {
|
||||
return errors.New("任务不存在、归属已变更或正在运行")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type ScheduleRun struct {
|
||||
ID uint64 `json:"id"`
|
||||
ScheduleID uint64 `json:"scheduleId"`
|
||||
State string `json:"state"`
|
||||
ExitCode *int `json:"exitCode"`
|
||||
StartedAt time.Time `json:"startedAt"`
|
||||
FinishedAt *time.Time `json:"finishedAt"`
|
||||
OutputCipher []byte `json:"-"`
|
||||
Output string `json:"output"`
|
||||
}
|
||||
|
||||
func (s *Store) ScheduleRuns(ctx context.Context, user, id uint64) ([]ScheduleRun, error) {
|
||||
rows, e := s.db.QueryContext(ctx, `SELECT r.id,r.schedule_id,r.state,r.exit_code,r.started_at,r.finished_at,r.output_cipher FROM user_schedule_runs r JOIN user_schedules t ON t.id=r.schedule_id WHERE t.user_id=? AND t.id=? ORDER BY r.id DESC LIMIT 30`, user, id)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []ScheduleRun{}
|
||||
for rows.Next() {
|
||||
var v ScheduleRun
|
||||
if e = rows.Scan(&v.ID, &v.ScheduleID, &v.State, &v.ExitCode, &v.StartedAt, &v.FinishedAt, &v.OutputCipher); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (s *Store) DueSchedules(ctx context.Context) ([]UserSchedule, error) {
|
||||
rows, e := s.db.QueryContext(ctx, "SELECT "+scheduleFields+" FROM user_schedules WHERE ((enabled=TRUE AND next_run_at<=UTC_TIMESTAMP()) OR run_requested=TRUE) AND (running_until IS NULL OR running_until<UTC_TIMESTAMP()) ORDER BY next_run_at,id LIMIT 100")
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []UserSchedule{}
|
||||
for rows.Next() {
|
||||
v, e := scanSchedule(rows)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (s *Store) ClaimSchedule(ctx context.Context, id uint64, next time.Time, expectedRef string) (uint64, error) {
|
||||
tx, e := s.db.BeginTx(ctx, nil)
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
defer tx.Rollback()
|
||||
v, e := scanSchedule(tx.QueryRowContext(ctx, "SELECT "+scheduleFields+" FROM user_schedules WHERE id=? AND ((enabled=TRUE AND next_run_at<=UTC_TIMESTAMP()) OR run_requested=TRUE) AND (running_until IS NULL OR running_until<UTC_TIMESTAMP()) FOR UPDATE", id))
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
if v.SecretRef != expectedRef {
|
||||
return 0, nil
|
||||
}
|
||||
var valid bool
|
||||
e = tx.QueryRowContext(ctx, `SELECT p.owner_tenant_id=t.account_id AND p.ownership_version=t.ownership_version AND p.management_locked=FALSE AND u.status='active' AND u.role='tenant' AND p.lifecycle_state='active' AND p.status='running' AND (p.expires_at IS NULL OR p.expires_at>UTC_TIMESTAMP()) AND s.status='running' FROM user_schedules t JOIN projects p ON p.id=t.project_id JOIN sites s ON s.id=t.site_id AND s.project_id=p.id JOIN users u ON u.id=t.user_id WHERE t.id=?`, id).Scan(&valid)
|
||||
if e != nil || !valid {
|
||||
_, e = tx.ExecContext(ctx, "UPDATE user_schedules SET next_run_at=?,run_requested=FALSE,last_state='skipped' WHERE id=?", next, id)
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
return 0, tx.Commit()
|
||||
}
|
||||
_, e = tx.ExecContext(ctx, "UPDATE user_schedule_runs SET state='uncertain',finished_at=UTC_TIMESTAMP() WHERE schedule_id=? AND state='running'", id)
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
_, e = tx.ExecContext(ctx, "UPDATE user_schedules SET next_run_at=?,run_requested=FALSE,running_until=DATE_ADD(UTC_TIMESTAMP(),INTERVAL 310 SECOND),last_state='running' WHERE id=?", next, id)
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
r, e := tx.ExecContext(ctx, "INSERT INTO user_schedule_runs(schedule_id,state,started_at) VALUES(?,'running',UTC_TIMESTAMP())", v.ID)
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
run, _ := r.LastInsertId()
|
||||
if _, e = tx.ExecContext(ctx, "UPDATE user_schedules SET running_run_id=? WHERE id=?", run, id); e != nil {
|
||||
return 0, e
|
||||
}
|
||||
return uint64(run), tx.Commit()
|
||||
}
|
||||
func (s *Store) FinishSchedule(ctx context.Context, id, run uint64, state string, code int, cipher []byte) error {
|
||||
tx, e := s.db.BeginTx(ctx, nil)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
defer tx.Rollback()
|
||||
_, e = tx.ExecContext(ctx, "UPDATE user_schedule_runs SET state=?,exit_code=?,output_cipher=?,finished_at=UTC_TIMESTAMP() WHERE id=? AND schedule_id=? AND state='running'", state, code, cipher, run, id)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
_, e = tx.ExecContext(ctx, "UPDATE user_schedules SET running_until=NULL,running_run_id=NULL,last_state=? WHERE id=? AND running_run_id=?", state, id, run)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
func (s *Store) ClaimSchedulerTick(ctx context.Context, node uint64) (bool, error) {
|
||||
r, e := s.db.ExecContext(ctx, "INSERT IGNORE INTO scheduler_ticks(tick_minute,node_id) VALUES(?,?)", time.Now().UTC().Truncate(time.Minute), node)
|
||||
if e != nil {
|
||||
return false, e
|
||||
}
|
||||
n, _ := r.RowsAffected()
|
||||
return n == 1, nil
|
||||
}
|
||||
func (s *Store) PruneSchedules(ctx context.Context) error {
|
||||
_, e := s.db.ExecContext(ctx, "DELETE FROM user_schedule_runs WHERE started_at<DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 DAY)")
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
_, e = s.db.ExecContext(ctx, "DELETE FROM scheduler_ticks WHERE tick_minute<DATE_SUB(UTC_TIMESTAMP(),INTERVAL 2 DAY)")
|
||||
return e
|
||||
}
|
||||
Reference in new issue
Block a user