Protect validation probes with the session lock
Some checks failed
ci/woodpecker/push/verify Pipeline was canceled
Some checks failed
ci/woodpecker/push/verify Pipeline was canceled
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
@@ -74,10 +75,9 @@ func validateSelectedSession(ctx context.Context, input *sessionInspectionInput,
|
||||
return inspectSessionValidation(ctx, cfg, deps)
|
||||
}
|
||||
|
||||
func inspectSessionValidation(ctx context.Context, cfg *config.Config, deps commandDependencies) (*sessionValidationReport, error) {
|
||||
func inspectSessionValidation(ctx context.Context, cfg *config.Config, deps commandDependencies) (report *sessionValidationReport, resultErr error) {
|
||||
deps = normalizeCommandDependencies(deps)
|
||||
report := &sessionValidationReport{Campaign: cfg.Session.Campaign, SessionID: cfg.Session.SessionID, SessionSource: sessionSourceSummary(cfg), Findings: []finding{}}
|
||||
var resultErr error
|
||||
report = &sessionValidationReport{Campaign: cfg.Session.Campaign, SessionID: cfg.Session.SessionID, SessionSource: sessionSourceSummary(cfg), Findings: []finding{}}
|
||||
fail := func(category string, err error) {
|
||||
if err != nil {
|
||||
report.Findings = append(report.Findings, errorFinding(category, err.Error()))
|
||||
@@ -126,6 +126,37 @@ func inspectSessionValidation(ctx context.Context, cfg *config.Config, deps comm
|
||||
if targetErr != nil {
|
||||
fail("preflight", targetErr)
|
||||
} else {
|
||||
probeStore := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root)
|
||||
paths := probeStore.SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
|
||||
if targets.Polish || targets.Notarius {
|
||||
// Check presence only before locking. Prepared evidence is read below
|
||||
// while locked; missing preparation must not bootstrap a workspace.
|
||||
_, statErr := os.Stat(paths.ManifestPath)
|
||||
if statErr == nil {
|
||||
lock, lockErr := probeStore.AcquireSessionLockForContext(ctx, cfg.Session.Campaign, cfg.Session.SessionID)
|
||||
if lockErr != nil {
|
||||
fail("workspace", fmt.Errorf("acquire validation session lock: %w", lockErr))
|
||||
targets.Polish, targets.Notarius = false, false
|
||||
} else {
|
||||
defer func() {
|
||||
fail("workspace", probeStore.ReleaseSessionLock(lock))
|
||||
report.Valid = resultErr == nil
|
||||
}()
|
||||
}
|
||||
} else {
|
||||
if errors.Is(statErr, os.ErrNotExist) {
|
||||
if targets.Polish {
|
||||
fail("audita", fmt.Errorf("prepared inputs are unavailable; run prepare"))
|
||||
}
|
||||
if targets.Notarius {
|
||||
fail("notarius", fmt.Errorf("prepared inputs are unavailable; run prepare"))
|
||||
}
|
||||
} else {
|
||||
fail("workspace", fmt.Errorf("inspect prepared manifest: %w", statErr))
|
||||
}
|
||||
targets.Polish, targets.Notarius = false, false
|
||||
}
|
||||
}
|
||||
var inspector scriptorium.Runner
|
||||
if len(targets.Scriptorium) > 0 {
|
||||
inspector = deps.newScriptorium()
|
||||
@@ -134,7 +165,6 @@ func inspectSessionValidation(ctx context.Context, cfg *config.Config, deps comm
|
||||
var request audita.PolishRequest
|
||||
if targets.Polish {
|
||||
report.Findings = append(report.Findings, infoFinding("audita", "preflight uses a synthetic transcript, probes destinations, and may contact providers"))
|
||||
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
|
||||
local, present, loadErr := loadManifestAtPathIfPresent(ctx, &manifest.LocalStore{}, paths.ManifestPath)
|
||||
if loadErr != nil {
|
||||
fail("audita", fmt.Errorf("load prepared manifest; run prepare: %w", loadErr))
|
||||
@@ -173,7 +203,6 @@ func inspectSessionValidation(ctx context.Context, cfg *config.Config, deps comm
|
||||
var native notarius.ReadinessChecker
|
||||
var probe stage.NotariusReadiness
|
||||
if targets.Notarius {
|
||||
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
|
||||
local, present, loadErr := loadManifestAtPathIfPresent(ctx, &manifest.LocalStore{}, paths.ManifestPath)
|
||||
switch {
|
||||
case loadErr != nil:
|
||||
|
||||
@@ -230,6 +230,10 @@ func TestSessionValidationReportsPreparedAndProviderFailures(t *testing.T) {
|
||||
if err == nil || report.Valid || !strings.Contains(err.Error(), "run prepare") || len(fake.PreflightRequests) != 0 {
|
||||
t.Fatalf("missing evidence: %+v %v", report, err)
|
||||
}
|
||||
missingPaths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
|
||||
if _, err := os.Lstat(missingPaths.Root); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("missing preparation created a workspace: %v", err)
|
||||
}
|
||||
paths := seedValidationPrepared(t, cfg)
|
||||
failure := errors.New("synthetic provider failure")
|
||||
fake.PreflightErr = failure
|
||||
|
||||
156
internal/app/session_validation_lock_test.go
Normal file
156
internal/app/session_validation_lock_test.go
Normal file
@@ -0,0 +1,156 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/audita"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/notarius"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/scriptorium"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/stage"
|
||||
)
|
||||
|
||||
type lockedAuditaProbe struct {
|
||||
audita.FakeRunner
|
||||
check func(context.Context, string, string) error
|
||||
}
|
||||
|
||||
func (p *lockedAuditaProbe) Preflight(ctx context.Context, req audita.PolishRequest) (audita.PreflightResult, error) {
|
||||
return audita.PreflightResult{}, p.check(ctx, "", req.ReportDir)
|
||||
}
|
||||
|
||||
type lockedNotariusProbe struct {
|
||||
notarius.FakeRunner
|
||||
check func(context.Context, string, string) error
|
||||
}
|
||||
|
||||
func (p *lockedNotariusProbe) Preflight(ctx context.Context, req notarius.ReadinessRequest) (notarius.ReadinessResult, error) {
|
||||
if err := p.check(ctx, req.InputPath, filepath.Dir(req.ReportPath)); err != nil {
|
||||
return notarius.ReadinessResult{}, err
|
||||
}
|
||||
return p.FakeRunner.Preflight(ctx, req)
|
||||
}
|
||||
|
||||
func TestSessionValidationHoldsLockUntilProbeFilesAreFinished(t *testing.T) {
|
||||
for _, tool := range []string{"audita", "notarius"} {
|
||||
t.Run(tool, func(t *testing.T) {
|
||||
pipeline, campaign, session := writeValidConfigFiles(t, t.TempDir())
|
||||
cfg, err := config.Load(pipeline, campaign, session)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tool == "notarius" {
|
||||
configureNotariusProbe(t, cfg)
|
||||
}
|
||||
cfg.Pipeline.Workspace.CleanupAfterPublish = true
|
||||
cfg.Pipeline.Publish = &config.PublishConfig{Enabled: boolPtr(true), UploadRun: boolPtr(true)}
|
||||
cfg.Pipeline.Storage.Backend = config.StorageBackendS3
|
||||
cfg.Pipeline.Storage.S3 = &config.StorageS3Config{Bucket: "archive", RootPrefix: "dnd"}
|
||||
paths := seedValidationPrepared(t, cfg)
|
||||
m, err := (&manifest.LocalStore{}).Load(context.Background(), paths.ManifestPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.RunID = "published-run"
|
||||
m.S3SessionPrefix = artifacts.S3SessionPrefix("dnd", m.Campaign, m.SessionID)
|
||||
m.MarkStageSucceeded("publish", time.Now().UTC(), nil)
|
||||
m.Stages["publish"].Metadata = cleanupPublishMetadata(m)
|
||||
if err := (&manifest.LocalStore{}).Save(context.Background(), paths.ManifestPath, m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
check := func(ctx context.Context, input, logs string) error {
|
||||
close(entered)
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
if input != "" {
|
||||
if _, err := os.ReadFile(input); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return fileops.WriteFileAtomic(filepath.Join(logs, "finished.yml"), []byte("ready: true\n"), fileops.WorkspaceFileMode)
|
||||
}
|
||||
deps := fakeCommandDependencies(&storage.FakeBackend{}, nil)
|
||||
deps.newScriptorium = func() scriptorium.Runner { return &scriptorium.FakeRunner{} }
|
||||
deps.newAudita = func(*config.Config) (audita.Runner, error) {
|
||||
if tool == "audita" {
|
||||
return &lockedAuditaProbe{check: check}, nil
|
||||
}
|
||||
return &audita.FakeRunner{}, nil
|
||||
}
|
||||
deps.newNotarius = func() notarius.Runner { return &lockedNotariusProbe{check: check} }
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := inspectSessionValidation(ctx, cfg, deps); done <- err }()
|
||||
select {
|
||||
case <-entered:
|
||||
case err := <-done:
|
||||
t.Fatalf("validation stopped before probe: %v", err)
|
||||
case <-ctx.Done():
|
||||
t.Fatal(ctx.Err())
|
||||
}
|
||||
store := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root)
|
||||
lock, err := store.AcquireSessionLockFor(cfg.Session.Campaign, cfg.Session.SessionID)
|
||||
if lock != nil {
|
||||
_ = store.ReleaseSessionLock(lock)
|
||||
}
|
||||
if !errors.Is(err, artifacts.ErrLockConflict) {
|
||||
close(release)
|
||||
<-done
|
||||
t.Fatalf("active validation did not exclude cleanup's session lock: %v", err)
|
||||
}
|
||||
close(release)
|
||||
if err := <-done; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
summary, err := executePlanWithDependencies(ctx, cfg, BoundedPlan{stages: []stage.Stage{selectedCleanupStage(t)}}, RunOptions{}, cleanupOrchestrationDependencies())
|
||||
if err != nil || !summary.Complete {
|
||||
t.Fatalf("cleanup after validation: %#v, %v", summary, err)
|
||||
}
|
||||
if _, err := os.Lstat(paths.RunsDir); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("completed probes survived cleanup: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionValidationCancellationWhileSessionIsLocked(t *testing.T) {
|
||||
pipeline, campaign, session := writeValidConfigFiles(t, t.TempDir())
|
||||
cfg, err := config.Load(pipeline, campaign, session)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
paths := seedValidationPrepared(t, cfg)
|
||||
store := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root)
|
||||
lock, err := store.AcquireSessionLockFor(cfg.Session.Campaign, cfg.Session.SessionID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.ReleaseSessionLock(lock)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
probe := &audita.FakeRunner{}
|
||||
deps := fakeCommandDependencies(&storage.FakeBackend{}, nil)
|
||||
deps.newAudita = func(*config.Config) (audita.Runner, error) { return probe, nil }
|
||||
deps.newScriptorium = func() scriptorium.Runner { return &scriptorium.FakeRunner{} }
|
||||
report, err := inspectSessionValidation(ctx, cfg, deps)
|
||||
if !errors.Is(err, context.DeadlineExceeded) || report.Valid || len(probe.PreflightRequests) != 0 {
|
||||
t.Fatalf("waiting validation: %+v, %v", report, err)
|
||||
}
|
||||
if _, err := os.Lstat(paths.RunsDir); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("waiting validation created probe paths: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user