267 lines
11 KiB
Go
267 lines
11 KiB
Go
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
|
|
}
|