246 lines
7.4 KiB
Go
246 lines
7.4 KiB
Go
package fileops
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"gitea.maximumdirect.net/eric/narratio/internal/pathsafe"
|
|
)
|
|
|
|
// AttemptViews records previous managed targets so a stage that self-skips can
|
|
// restore its navigation views without touching unrelated workspace content.
|
|
type AttemptViews struct {
|
|
root, runID, name string
|
|
previous map[string]*string
|
|
}
|
|
|
|
// EnsureWorkspaceDirectoryUnderRoot creates real directories beneath an
|
|
// existing root and rejects symlink components instead of following them.
|
|
func EnsureWorkspaceDirectoryUnderRoot(rootPath, relative string) error {
|
|
if _, err := pathsafe.NormalizeRelativeDestination(relative); err != nil {
|
|
return err
|
|
}
|
|
root, err := os.OpenRoot(rootPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer root.Close()
|
|
return ensureAttemptDirectory(root, relative)
|
|
}
|
|
|
|
func ensureAttemptDirectory(root *os.Root, relative string) error {
|
|
current := ""
|
|
for _, component := range strings.Split(filepath.ToSlash(relative), "/") {
|
|
if component == "" || component == "." || component == ".." {
|
|
return fmt.Errorf("invalid directory component %q", component)
|
|
}
|
|
current = filepath.Join(current, component)
|
|
info, err := root.Lstat(current)
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
if err := root.Mkdir(current, WorkspaceDirectoryMode.Perm()); err != nil && !errors.Is(err, os.ErrExist) {
|
|
return err
|
|
}
|
|
info, err = root.Lstat(current)
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
|
|
return fmt.Errorf("workspace directory %q is not a real directory", current)
|
|
}
|
|
if err := root.Chmod(current, WorkspaceDirectoryMode); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// BeginAttemptViews creates actual diagnostics directories and atomically
|
|
// advances each managed relative link. It accepts no arbitrary link targets.
|
|
func BeginAttemptViews(sessionRoot, runID, name string) (*AttemptViews, error) {
|
|
if err := pathsafe.ValidateOpaqueSegment(runID); err != nil {
|
|
return nil, fmt.Errorf("run identity: %w", err)
|
|
}
|
|
if runID == ".preflight" || runID == ".validation" {
|
|
return nil, fmt.Errorf("run identity %q is reserved for probes", runID)
|
|
}
|
|
if err := pathsafe.ValidateOpaqueSegment(name); err != nil {
|
|
return nil, fmt.Errorf("diagnostic name: %w", err)
|
|
}
|
|
root, err := os.OpenRoot(sessionRoot)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer root.Close()
|
|
for _, relative := range []string{filepath.Join("runs", runID, name, "logs"), filepath.Join("runs", runID, name, "debug"), "logs", "debug"} {
|
|
if err := ensureAttemptDirectory(root, relative); err != nil {
|
|
return nil, fmt.Errorf("prepare attempt directory %q: %w", relative, err)
|
|
}
|
|
}
|
|
views := &AttemptViews{root: sessionRoot, runID: runID, name: name, previous: map[string]*string{}}
|
|
for _, category := range []string{"logs", "debug"} {
|
|
parent, err := root.OpenRoot(category)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
previous, err := existingManagedView(parent, name, category)
|
|
_ = parent.Close()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
views.previous[category] = previous
|
|
}
|
|
var updated []string
|
|
for _, category := range []string{"logs", "debug"} {
|
|
parent, err := root.OpenRoot(category)
|
|
if err != nil {
|
|
return nil, errors.Join(err, views.revertCategories(updated))
|
|
}
|
|
target := attemptTarget(runID, name, category)
|
|
err = replaceManagedView(parent, name, category, target)
|
|
_ = parent.Close()
|
|
if err != nil {
|
|
return nil, errors.Join(err, views.revertCategories(updated))
|
|
}
|
|
updated = append(updated, category)
|
|
}
|
|
return views, nil
|
|
}
|
|
|
|
func attemptTarget(runID, name, category string) string {
|
|
return "../runs/" + runID + "/" + name + "/" + category
|
|
}
|
|
|
|
func existingManagedView(parent *os.Root, name, category string) (*string, error) {
|
|
info, err := parent.Lstat(name)
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if info.Mode()&os.ModeSymlink == 0 {
|
|
return nil, fmt.Errorf("managed %s view %q conflicts with existing content", category, name)
|
|
}
|
|
target, err := parent.Readlink(name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
parts := strings.Split(target, "/")
|
|
if len(parts) != 5 || parts[0] != ".." || parts[1] != "runs" || parts[3] != name || parts[4] != category || parts[2] == ".preflight" || parts[2] == ".validation" || pathsafe.ValidateOpaqueSegment(parts[2]) != nil {
|
|
return nil, fmt.Errorf("managed %s view %q has an unexpected target %q", category, name, target)
|
|
}
|
|
return &target, nil
|
|
}
|
|
|
|
// ManagedAttemptTargets returns run-relative diagnostic directories selected by
|
|
// the session's managed navigation links. It never follows link targets.
|
|
func ManagedAttemptTargets(sessionRoot, runID string, names []string) ([]string, error) {
|
|
if err := pathsafe.ValidateOpaqueSegment(runID); err != nil {
|
|
return nil, fmt.Errorf("run identity: %w", err)
|
|
}
|
|
root, err := os.OpenRoot(sessionRoot)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer root.Close()
|
|
var targets []string
|
|
for _, category := range []string{"logs", "debug"} {
|
|
info, err := root.Lstat(category)
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
continue
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
|
|
return nil, fmt.Errorf("managed %s directory is unsafe", category)
|
|
}
|
|
parent, err := root.OpenRoot(category)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, name := range names {
|
|
if err := pathsafe.ValidateOpaqueSegment(name); err != nil {
|
|
_ = parent.Close()
|
|
return nil, fmt.Errorf("invalid managed %s view %q: %w", category, name, err)
|
|
}
|
|
target, err := existingManagedView(parent, name, category)
|
|
if err != nil {
|
|
_ = parent.Close()
|
|
return nil, err
|
|
}
|
|
if target != nil && *target == attemptTarget(runID, name, category) {
|
|
targets = append(targets, filepath.Join(name, category))
|
|
}
|
|
}
|
|
_ = parent.Close()
|
|
}
|
|
return targets, nil
|
|
}
|
|
|
|
func replaceManagedView(parent *os.Root, name, category, target string) error {
|
|
if _, err := existingManagedView(parent, name, category); err != nil {
|
|
return err
|
|
}
|
|
var random [16]byte
|
|
if _, err := rand.Read(random[:]); err != nil {
|
|
return err
|
|
}
|
|
temporary := "." + name + "." + hex.EncodeToString(random[:]) + ".link"
|
|
if err := parent.Symlink(target, temporary); err != nil {
|
|
return fmt.Errorf("create managed %s view: %w", category, err)
|
|
}
|
|
defer parent.Remove(temporary)
|
|
if _, err := existingManagedView(parent, name, category); err != nil {
|
|
return err
|
|
}
|
|
if err := parent.Rename(temporary, name); err != nil {
|
|
return fmt.Errorf("install managed %s view: %w", category, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Revert restores prior links only if they still point to this attempt.
|
|
func (v *AttemptViews) Revert() error {
|
|
if v == nil {
|
|
return nil
|
|
}
|
|
return v.revertCategories([]string{"logs", "debug"})
|
|
}
|
|
|
|
func (v *AttemptViews) revertCategories(categories []string) error {
|
|
root, err := os.OpenRoot(v.root)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer root.Close()
|
|
for _, category := range categories {
|
|
parent, err := root.OpenRoot(category)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
current, err := existingManagedView(parent, v.name, category)
|
|
if err == nil && (current == nil || *current != attemptTarget(v.runID, v.name, category)) {
|
|
err = fmt.Errorf("managed %s view changed during attempt", category)
|
|
}
|
|
if err == nil {
|
|
if previous := v.previous[category]; previous != nil {
|
|
err = replaceManagedView(parent, v.name, category, *previous)
|
|
} else {
|
|
err = parent.Remove(v.name)
|
|
}
|
|
}
|
|
_ = parent.Close()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|