Files
narratio/internal/stage/cleanup.go

174 lines
4.9 KiB
Go

package stage
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
)
const (
cleanupSkipReason = "cleanup policies are disabled"
cleanupSemanticConfigVersion = 2
)
type cleanupStage struct{}
type cleanupSemanticConfig struct {
DeleteWorkspace bool `json:"delete_workspace"`
WorkspaceRoot string `json:"workspace_root"`
}
func (cleanupStage) Name() string { return "cleanup" }
func (cleanupStage) RequiresRunWorkspace() bool { return false }
func (cleanupStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*StageResult, error) {
plan, err := buildCleanupPlan(env, m)
if err != nil {
return nil, err
}
if !plan.enabled {
return &StageResult{
Disposition: StageDispositionSkipped,
SkipReason: cleanupSkipReason,
}, nil
}
completedPolicies := make([]string, 0, len(plan.targets))
for _, target := range plan.targets {
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("cleanup canceled before %s: %w", target.policy, err)
}
_, err := inspectCleanupTarget(target.root, target.target)
if err == nil {
err = fileops.RemoveManagedAttemptViews(filepath.Dir(target.target), cleanupManagedNames())
if errors.Is(err, os.ErrNotExist) {
err = nil
}
}
if err == nil {
if err = ctx.Err(); err == nil {
err = fileops.RemoveAllUnderRoot(target.root, target.target)
}
}
if err != nil {
return nil, fmt.Errorf("apply %s: %w", target.policy, err)
}
completedPolicies = append(completedPolicies, target.policy)
}
return &StageResult{Metadata: map[string]any{
"stage": "cleanup",
"published_run_id": plan.publishedRunID,
"completed_policies": completedPolicies,
}}, nil
}
func (cleanupStage) SemanticConfigFingerprint(env *Env) (manifest.SemanticConfigFingerprint, error) {
if env == nil || env.Config == nil || env.Config.Pipeline == nil {
return manifest.SemanticConfigFingerprint{}, fmt.Errorf("resolved pipeline configuration is required")
}
pipeline := env.Config.Pipeline
return FingerprintSemanticConfig(cleanupSemanticConfigVersion, cleanupSemanticConfig{
DeleteWorkspace: pipeline.Workspace.CleanupAfterPublish,
WorkspaceRoot: normalizedCleanupRoot(pipeline.Workspace.Root),
})
}
func (cleanupStage) ValidateResume(ctx context.Context, env *Env, m *manifest.Manifest) (ResumeValidation, error) {
plan, err := buildCleanupPlan(env, m)
if err != nil {
return ResumeValidation{}, err
}
if !plan.enabled {
return NonResumable(cleanupSkipReason), nil
}
for _, target := range plan.targets {
if err := ctx.Err(); err != nil {
return ResumeValidation{}, fmt.Errorf("validate cleanup resume for %s: %w", target.policy, err)
}
pending, err := inspectCleanupTarget(target.root, target.target)
if err != nil {
return ResumeValidation{}, err
}
if pending {
return NonResumable(fmt.Sprintf("cleanup target for %s exists", target.policy)), nil
}
}
return Resumable(), nil
}
func normalizedCleanupRoot(root string) string {
root = strings.TrimSpace(root)
if root == "" {
return ""
}
return filepath.Clean(root)
}
func cleanupManagedNames() []string {
names := []string{"restore"}
for _, item := range All() {
names = append(names, item.Name())
}
return names
}
// inspectCleanupTarget checks the session path and runs directory without creating
// anything, then inspects managed views independently of their targets.
func inspectCleanupTarget(workspaceRoot, runsDir string) (bool, error) {
workspace, err := filepath.Abs(workspaceRoot)
if err != nil {
return false, err
}
session, err := filepath.Abs(filepath.Dir(runsDir))
if err != nil {
return false, err
}
rel, err := filepath.Rel(workspace, session)
if err != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return false, fmt.Errorf("cleanup session must be below workspace root")
}
root, err := os.OpenRoot(workspace)
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
if err != nil {
return false, err
}
defer root.Close()
current := ""
for _, component := range strings.Split(rel, string(filepath.Separator)) {
current = filepath.Join(current, component)
info, err := root.Lstat(current)
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
if err != nil {
return false, err
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return false, fmt.Errorf("unsafe cleanup session directory %q", current)
}
}
info, err := root.Lstat(filepath.Join(rel, "runs"))
runsExist := err == nil
if err != nil && !errors.Is(err, os.ErrNotExist) {
return false, err
}
if runsExist && (!info.IsDir() || info.Mode()&os.ModeSymlink != 0) {
return false, fmt.Errorf("unsafe run cleanup directory %q", runsDir)
}
viewsExist, err := fileops.InspectManagedAttemptViews(session, cleanupManagedNames())
if err != nil {
return false, err
}
return runsExist || viewsExist, nil
}