restore

package
v0.0.0-...-95891f2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: AGPL-3.0 Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package restore provides the admin-facing UI for restoring a previous backup. The actual restore mechanics live in scripts/restore.sh; this package decides when it may run, closes the site while it does, and brings the site back afterwards.

Restore is the highest-blast-radius action chronicle exposes: it overwrites every MariaDB table and replaces the media tree on disk (ADR-036). The admin types the literal string "RESTORE"; then Chronicle enters maintenance (internal/maintenance), waits for requests in flight, runs the script against itself with --from-inside, and on success migrates the restored schema and re-checks every session before opening again. On failure it stays closed and shows the admin what happened (ADR-073).

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrAlreadyRunning is returned when another restore is in flight.
	ErrAlreadyRunning = fmt.Errorf("restore already running")
	// ErrInvalidManifest is returned for a manifest name that is not a
	// restorable file under BACKUP_DIR.
	ErrInvalidManifest = errors.New("invalid manifest")
)

Errors returned by Start.

Functions

func RegisterRoutes

func RegisterRoutes(admin *echo.Group, h *Handler, reauth echo.MiddlewareFunc, state *maintenance.State)

RegisterRoutes mounts the admin restore routes on the given group. The caller is responsible for the auth gate; this package assumes the group already requires site-admin.

Restore is rate-limited (3/hour) because each invocation replaces every shared resource; a failed attempt must still leave room for a retry while the site is closed. The single-flight in the maintenance state means click-flooding cannot start a second restore: at worst the operator sees 409s.

reauth runs before the rate limit so an unconfirmed attempt does not use up the hour's allowance.

state is the shared maintenance state: while it is closed the global gate serves the restoring admin through h.OwnerView, so these routes are only reached while the site is open.

func ResolveManifestPath

func ResolveManifestPath(backupDir, name string) (string, error)

ResolveManifestPath validates a manifest basename against BACKUP_DIR, rejects path-traversal attempts, and returns the absolute path. Same shape as backup.ResolveArtifactPath but additionally enforces that the file is a backup, pre-update or pre-restore manifest — restore.sh would refuse other inputs anyway, but failing fast at the HTTP boundary surfaces the wrong-file error to the operator rather than burying it in a shell exit code.

Types

type ActivityRecorder

type ActivityRecorder interface {
	RecordAdminChangeAs(ctx context.Context, userID, action, targetType, targetID, label string)
}

ActivityRecorder is the slice of the admin change log this plugin writes to. It is declared here, not imported from the admin plugin, so the plugins stay independent; app wiring supplies an adapter. The restore finishes in a background goroutine, so entries carry the admin's id rather than a request. Recording is best-effort: implementations must not fail the restore.

type Config

type Config struct {
	// ScriptPath is the absolute path to restore.sh. Required.
	ScriptPath string

	// BackupDir is where backup artifacts live (also where manifests
	// resolve from). Required.
	BackupDir string

	// Timeout caps a single RunRestore invocation. Default 30 minutes.
	Timeout time.Duration

	// State is the shared maintenance state the global gate also reads. If
	// nil the service keeps a private one in BackupDir, which is only right
	// for tests: nothing would close the site.
	State *maintenance.State

	// Hooks are the application-side steps; may be nil.
	Hooks Hooks

	// Activity receives the audit entries; may be nil.
	Activity ActivityRecorder

	// DrainTimeout is how long to wait for requests in flight before the
	// script starts. Default 15 seconds.
	DrainTimeout time.Duration

	// ComposeService names the docker compose service used in the
	// hand-restore command. Default "chronicle".
	ComposeService string
}

Config holds tunables for the service. Defaults match production expectations: 30-minute timeout (restore can take longer than backup because mariadb is doing imports under FK constraints).

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler renders the restore page and accepts the "run restore" action. All routes are mounted under /admin/restore and inherit RequireSiteAdmin from the parent group.

func NewHandler

func NewHandler(svc Service) *Handler

NewHandler constructs a Handler against the given Service.

func (*Handler) OwnerView

func (h *Handler) OwnerView(c *echo.Context) (bool, error)

OwnerView is the maintenance.OwnerHandler: it serves the restoring admin's progress page, status poll and "leave maintenance" button with no database and no router. The gate only calls it for the session that started the restore, so nothing here re-checks who the caller is.

func (*Handler) Page

func (h *Handler) Page(c *echo.Context) error

Page renders the restore dashboard (GET /admin/restore).

func (*Handler) Run

func (h *Handler) Run(c *echo.Context) error

Run starts a restore (POST /admin/restore/run). Requires:

  • manifest=<basename>: which backup to restore from.
  • confirm=RESTORE: literal-string confirmation; the typed-in confirmation surface that distinguishes a deliberate restore from a mis-click. Anything else is rejected before the site closes.

It returns as soon as the site is closed; the restore itself runs in the background and the admin's page follows it through the status endpoint.

func (*Handler) SetActor

func (h *Handler) SetActor(fn func(*echo.Context) string)

SetActor tells the handler how to read the signed-in admin's user id. The auth plugin owns that lookup, so app wiring supplies it. Optional: without it the audit trail records no user.

func (*Handler) Status

func (h *Handler) Status(c *echo.Context) error

Status answers the progress poll (GET /admin/restore/status), site admins only. While the site is closed the gate serves the same answer through OwnerView, because the router and database are not available then.

type Hooks

type Hooks interface {
	// Quiesce disconnects clients the gate cannot refuse because they are
	// already connected (websockets).
	Quiesce(ctx context.Context)
	// ResetConnections drops pooled database connections. DROP DATABASE
	// leaves a pooled connection with no default database, and nothing
	// re-selects it when the database is created again.
	ResetConnections()
	// Migrate brings the restored schema up to this build, the same way a
	// normal start does (the backup may be older than the running image).
	Migrate(ctx context.Context) error
	// FlushCaches clears caches that held the old database's answers and
	// forces every live session to be re-checked against the restored
	// accounts. The returned text is a short plain-language result.
	FlushCaches(ctx context.Context) (string, error)
}

Hooks are the steps that need the rest of the application. The app wires them; a nil Hooks makes each a no-op (tests).

type ManifestSummary

type ManifestSummary struct {
	// Name is the basename of the manifest file. Used as the parameter
	// the operator submits to /admin/restore/run.
	Name string

	// ModTime is the manifest's mtime. Stand-in for "when this backup
	// was taken" since we sort and label by it.
	ModTime time.Time

	// ChronicleVersion and MigrationVersion are pulled from the manifest
	// body. Operators use these to sanity-check whether the live binary
	// is compatible with the snapshot they're about to roll back to.
	ChronicleVersion string
	MigrationVersion string

	// DBFile, MediaFile, RedisFile are the basenames of the bundled
	// artifacts. An empty string means that artifact was not produced
	// (Redis is best-effort; media may be empty if MEDIA_PATH was unset).
	DBFile    string
	MediaFile string
	RedisFile string

	// PreUpdate marks the automatic capture taken just before an update
	// changed the database, so the list can say why it exists.
	PreUpdate bool

	// PreRestore marks the copy of the database that restore.sh saves just
	// before replacing it, so a restore can be undone.
	PreRestore bool

	// SizeBytes is the manifest file size itself. Ancillary; the bundled
	// artifact sizes appear in the manifest body but we don't surface
	// them in the list view to keep the UI scannable.
	SizeBytes int64

	// ParseError is populated when the manifest exists but couldn't be
	// fully parsed. Surfaced in the UI so the operator knows not to
	// trust the row before clicking Restore.
	ParseError string
}

ManifestSummary is the parsed view of one backup manifest: either a chronicle_manifest_*.txt from scripts/backup.sh or a chronicle_pre_migrate_manifest_*.txt written automatically before an update applied migrations. We surface enough information that an operator can confirm which backup they're about to restore — chronicle version, migration version, the artifacts the restore will touch, and the file size for each.

type RunResult

type RunResult struct {
	StartedAt    time.Time
	FinishedAt   time.Time
	ManifestName string
	ExitCode     int
	Stdout       string
	Stderr       string
	TimedOut     bool
	ErrorString  string
}

RunResult captures the outcome of one restore invocation.

func (*RunResult) Duration

func (r *RunResult) Duration() time.Duration

Duration returns how long the restore took.

func (*RunResult) Succeeded

func (r *RunResult) Succeeded() bool

Succeeded reports whether the restore finished cleanly.

type Service

type Service interface {
	// Start closes the site and runs the restore in the background. It
	// returns once the site is closed. ErrAlreadyRunning means a restore is
	// in progress (or the site is still closed after a failed one);
	// ErrInvalidManifest means the manifest name was rejected.
	Start(ctx context.Context, req StartRequest) error

	// Leave opens the site after a failed or interrupted restore, on an
	// admin's say-so. userID is recorded in the audit trail.
	Leave(ctx context.Context, userID string) error

	// Status is a copy of the maintenance state for the page and the poll.
	Status() maintenance.Snapshot

	// LeaveToken is the value the owner's page must send back to leave
	// maintenance; CheckLeaveToken verifies one in constant time.
	LeaveToken() string
	CheckLeaveToken(token string) bool

	// RunRestore invokes scripts/restore.sh with --manifest pointing to
	// the chosen artifact under BACKUP_DIR and waits for it. Start drives
	// it; it is separate so the script's lifecycle (timeout, process group,
	// single-flight) is testable on its own. Returns ErrAlreadyRunning if
	// the script is already running.
	RunRestore(ctx context.Context, manifestName string) (*RunResult, error)

	// ListManifests returns every backup, pre-update and pre-restore
	// manifest in BACKUP_DIR, newest first, parsed for display.
	ListManifests() ([]ManifestSummary, error)

	// LastRun returns the most recent restore RunResult observed by this
	// service instance, or nil if no restore has run since boot.
	LastRun() *RunResult

	// IsRunning reports whether a restore is currently in flight.
	IsRunning() bool

	// BackupDir returns the configured backup directory path.
	BackupDir() string

	// HandRestoreCommand is the exact shell command that restores the named
	// manifest by hand, for the failure page.
	HandRestoreCommand(manifestName string) string
}

Service is the admin-facing restore operations interface.

func NewService

func NewService(cfg Config) Service

NewService constructs a Service.

type StartRequest

type StartRequest struct {
	// Manifest is the manifest basename under BACKUP_DIR.
	Manifest string
	// UserID is the signed-in admin, for the audit trail.
	UserID string
	// SessionHash is the hex SHA-256 of that admin's session token
	// (maintenance.SessionHash). Only that session can see progress and
	// leave maintenance while the site is closed.
	SessionHash string
}

StartRequest says who is starting which restore.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL