216 lines
8.0 KiB
Go
216 lines
8.0 KiB
Go
package worker
|
|
|
|
import (
|
|
"context"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"os"
|
|
"otche/internal/store"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func workerTestDB(t *testing.T) (context.Context, *pgxpool.Pool) {
|
|
t.Helper()
|
|
dsn := os.Getenv("OTCHE_TEST_DATABASE_URL")
|
|
if dsn == "" {
|
|
t.Skip("OTCHE_TEST_DATABASE_URL required for isolated PostgreSQL regression")
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
t.Cleanup(cancel)
|
|
admin, err := pgxpool.New(ctx, dsn)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(admin.Close)
|
|
schema := "test_" + strings.ReplaceAll(newID(), "-", "")
|
|
if _, err = admin.Exec(ctx, "CREATE SCHEMA "+schema); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { _, _ = admin.Exec(context.Background(), "DROP SCHEMA "+schema+" CASCADE") })
|
|
cfg, err := pgxpool.ParseConfig(dsn)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
cfg.ConnConfig.RuntimeParams["search_path"] = schema
|
|
db, err := pgxpool.NewWithConfig(ctx, cfg)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(db.Close)
|
|
if err = store.Migrate(ctx, db); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return ctx, db
|
|
}
|
|
|
|
// Old workers must not regain authority when the same process reclaims a lease.
|
|
func TestLeaseGenerationFencesExpiredClaimAndAllowsCancelledCleanup(t *testing.T) {
|
|
ctx, db := workerTestDB(t)
|
|
owner, profile, revision, upload, job, run, aid, command := newID(), newID(), newID(), newID(), newID(), newID(), newID(), newID()
|
|
statements := []struct {
|
|
sql string
|
|
args []any
|
|
}{
|
|
{"INSERT INTO users(id,username,password_hash,role)VALUES($1,'lease-owner','unused','operator')", []any{owner}},
|
|
{"INSERT INTO profiles(id,name,os,architecture)VALUES($1,'lease-profile','Windows','x64')", []any{profile}},
|
|
{"INSERT INTO revisions(id,profile_id,source_ref,fingerprint,config_digest)VALUES($1,$2,'source','fp','cfg')", []any{revision, profile}},
|
|
{"INSERT INTO uploads(id,owner_id,filename,size,sha256,storage_key)VALUES($1,$2,'safe.exe',1,'hash','test-upload')", []any{upload, owner}},
|
|
{"INSERT INTO jobs(id,owner_id,upload_id,execution_filename,settings)VALUES($1,$2,$3,'safe.exe','{}')", []any{job, owner, upload}},
|
|
{"INSERT INTO runs(id,job_id,profile_id,revision_id,profile_name)VALUES($1,$2,$3,$4,'Lease fixture')", []any{run, job, profile, revision}},
|
|
{"INSERT INTO attempts(id,run_id,command_id)VALUES($1,$2,$3)", []any{aid, run, command}},
|
|
}
|
|
for _, s := range statements {
|
|
if _, err := db.Exec(ctx, s.sql, s.args...); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
e := engine{db: db, cfg: Config{Concurrent: 1, Owners: map[string]Binding{owner: {MaxActiveAttempts: 1}}}, id: "same-process"}
|
|
first, err := e.claim(ctx)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var claimedAt time.Time
|
|
if err = db.QueryRow(ctx, "SELECT claimed_at FROM attempts WHERE id=$1", aid).Scan(&claimedAt); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
old := e
|
|
old.id = first.Lease
|
|
if err = old.phase(ctx, first, "provisioning"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err = e.claim(ctx); !isNoRows(err) {
|
|
t.Fatalf("active lease allowed second claim: %v", err)
|
|
}
|
|
if _, err = db.Exec(ctx, "UPDATE attempts SET lease_until=now()-interval '1 second' WHERE id=$1", aid); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
second, err := e.claim(ctx)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if first.Lease == second.Lease {
|
|
t.Fatal("reclaimed attempt reused old lease generation")
|
|
}
|
|
var reclaimedAt time.Time
|
|
if err = db.QueryRow(ctx, "SELECT claimed_at FROM attempts WHERE id=$1", aid).Scan(&reclaimedAt); err != nil || !reclaimedAt.Equal(claimedAt) {
|
|
t.Fatalf("reclaim changed initial claim timestamp: %v", err)
|
|
}
|
|
current := e
|
|
current.id = second.Lease
|
|
if old.leaseAlive(ctx, first) == nil || old.phase(ctx, first, "running") == nil {
|
|
t.Fatal("expired generation retained mutation authority")
|
|
}
|
|
if err = current.phase(ctx, second, "collecting"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err = db.Exec(ctx, "UPDATE jobs SET cancel_requested=true WHERE id=$1", job); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if current.fence(ctx, second) == nil {
|
|
t.Fatal("cancel failed to revoke execution permission")
|
|
}
|
|
if err = current.leaseAlive(ctx, second); err != nil {
|
|
t.Fatalf("cancel must retain cleanup authority: %v", err)
|
|
}
|
|
var phase string
|
|
if err = db.QueryRow(ctx, "SELECT phase FROM attempts WHERE id=$1", aid).Scan(&phase); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if phase != "collecting" {
|
|
t.Fatalf("stale worker overwrote phase: %s", phase)
|
|
}
|
|
}
|
|
|
|
// Cancelling a running Job must interrupt execution promptly through the lease
|
|
// supervisor, yet keep renewing the lease the finalizer needs for salvage/stop.
|
|
func TestCancelInterruptsExecutionAndKeepsCleanupLease(t *testing.T) {
|
|
ctx, db := workerTestDB(t)
|
|
owner, profile, revision, upload, job, run, aid := newID(), newID(), newID(), newID(), newID(), newID(), newID()
|
|
for _, s := range []struct {
|
|
sql string
|
|
args []any
|
|
}{
|
|
{"INSERT INTO users(id,username,password_hash,role)VALUES($1,'cancel-owner','unused','operator')", []any{owner}},
|
|
{"INSERT INTO profiles(id,name,os,architecture)VALUES($1,'cancel-profile','Windows','x64')", []any{profile}},
|
|
{"INSERT INTO revisions(id,profile_id,source_ref,fingerprint,config_digest)VALUES($1,$2,'source','fp','cfg')", []any{revision, profile}},
|
|
{"INSERT INTO uploads(id,owner_id,filename,size,sha256,storage_key)VALUES($1,$2,'safe.exe',1,'hash','test-upload')", []any{upload, owner}},
|
|
{`INSERT INTO jobs(id,owner_id,upload_id,execution_filename,settings,status)VALUES($1,$2,$3,'safe.exe','{"duration_seconds":1800}','running')`, []any{job, owner, upload}},
|
|
{"INSERT INTO runs(id,job_id,profile_id,revision_id,profile_name,status)VALUES($1,$2,$3,$4,'Cancel fixture','running')", []any{run, job, profile, revision}},
|
|
{"INSERT INTO attempts(id,run_id,command_id)VALUES($1,$2,$3)", []any{aid, run, newID()}},
|
|
} {
|
|
if _, err := db.Exec(ctx, s.sql, s.args...); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
e := engine{db: db, cfg: Config{Concurrent: 1, Owners: map[string]Binding{owner: {MaxActiveAttempts: 1}}}, id: "cancel-worker"}
|
|
claimed, err := e.claim(ctx)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
e.id = claimed.Lease
|
|
if err = e.phase(ctx, claimed, "running"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
execution, cancel := context.WithCancel(ctx)
|
|
defer cancel()
|
|
done := make(chan struct{})
|
|
stopped := make(chan struct{})
|
|
go func() {
|
|
defer close(stopped)
|
|
e.superviseLease(claimed, 20*time.Millisecond, cancel, done)
|
|
}()
|
|
select {
|
|
case <-execution.Done():
|
|
t.Fatal("supervisor cancelled an uncancelled running attempt")
|
|
case <-time.After(200 * time.Millisecond):
|
|
}
|
|
if _, err = db.Exec(ctx, "UPDATE jobs SET cancel_requested=true WHERE id=$1", job); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
select {
|
|
case <-execution.Done():
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("cancel_requested did not interrupt running execution")
|
|
}
|
|
if err = e.fence(ctx, claimed); err == nil || err.Error() != "cancelled" {
|
|
t.Fatalf("finalizer would not classify the interruption as cancelled: %v", err)
|
|
}
|
|
var before time.Time
|
|
if err = db.QueryRow(ctx, "SELECT lease_until FROM attempts WHERE id=$1", aid).Scan(&before); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
deadline := time.Now().Add(5 * time.Second)
|
|
for {
|
|
var after time.Time
|
|
if err = db.QueryRow(ctx, "SELECT lease_until FROM attempts WHERE id=$1", aid).Scan(&after); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if after.After(before) {
|
|
break
|
|
}
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("cancelled attempt stopped renewing the cleanup lease")
|
|
}
|
|
time.Sleep(20 * time.Millisecond)
|
|
}
|
|
if err = e.leaseAlive(ctx, claimed); err != nil {
|
|
t.Fatalf("finalizer lost authority to salvage and stop the owned clone: %v", err)
|
|
}
|
|
close(done)
|
|
<-stopped
|
|
}
|
|
|
|
func TestRunLimitsDurationBoundaries(t *testing.T) {
|
|
for _, seconds := range []int{1, 45, 1800} {
|
|
if err := runLimits(settings{Duration: seconds, Privilege: "admin"}); err != nil {
|
|
t.Fatalf("%d rejected: %v", seconds, err)
|
|
}
|
|
}
|
|
for _, opts := range []settings{{Duration: 0, Privilege: "user"}, {Duration: 1801, Privilege: "user"}, {Duration: -1, Privilege: "user"}, {Duration: 60, Privilege: "system"}} {
|
|
if runLimits(opts) == nil {
|
|
t.Fatalf("invalid immutable limits accepted: %+v", opts)
|
|
}
|
|
}
|
|
}
|