Files
fluxer/fluxer_rexctl/cmd/migrate_objects.go
T

422 lines
15 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package cmd
import (
"context"
"errors"
"fmt"
"maps"
"slices"
"strings"
"time"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/deploy"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/migrate"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/native"
rt "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/runtime"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
)
var objectsSettable = append(slices.Clone(migrate.S3Keys), "FLUXER_S3_BUCKET_CDN", "FLUXER_S3_BUCKET_UPLOADS", "FLUXER_S3_BUCKET_REPORTS", "FLUXER_S3_BUCKET_HARVESTS")
func objectsOption(v string) bool { return v == migrate.ToS3 || v == migrate.ToFiles }
func routeObjects(ctx context.Context, app *App, inst *instance.Instance, f *migrateFlags) (bool, error) {
if len(f.Set) > 0 && f.Migrate != migrate.ToS3 {
return true, ui.Usage("Pass --set only with --migrate s3.")
}
switch {
case objectsOption(f.Migrate):
return true, runObjectsMove(ctx, app, inst, f)
case objectsOption(f.Undo):
return true, runObjectsUndo(ctx, app, inst, f.Undo)
case f.CleanUp && inst.State.MovedFrom == nil && !movedNotCleaned(inst):
st, err := migrate.LoadState(inst.Dir)
switch {
case err != nil:
return false, nil
case st.Objects.Pending():
return true, runObjectsCleanUp(ctx, app, inst, &st, f.Confirm)
case rt.KindOf(inst) == rt.Container:
app.UI.OK("No old data is left from rexctl migrate.")
return true, nil
}
return false, nil
}
return false, nil
}
type objectsHost struct {
app *App
inst *instance.Instance
r rt.Runtime
}
func (h *objectsHost) Settings() map[string]string { return maps.Clone(h.inst.State.Settings) }
func (h *objectsHost) ObjectsRoot() string { return rt.ContainerObjects }
func (h *objectsHost) Env(with map[string]string) (map[string]string, error) {
env, _, err := rt.ContainerEnvWith(h.r, with)
return env, err
}
func changePointers(changes map[string]string) map[string]*string {
out := make(map[string]*string, len(changes))
for k, v := range changes {
if v == "" {
out[k] = nil
continue
}
out[k] = &v
}
return out
}
func (h *objectsHost) CheckTarget(ctx context.Context, changes map[string]string) error {
p, err := deploy.Prepare(h.inst, changePointers(changes))
if err != nil {
return err
}
return h.r.Settings().Validate(ctx, p)
}
func (h *objectsHost) Backup(ctx context.Context) (string, error) {
return backupWith(ctx, h.app, h.inst, h.r, rt.BackupOptions{Reason: "migrate"}, nil, "Backing up your instance")
}
func (h *objectsHost) Stop(ctx context.Context, services []string) error {
n := rt.FluxerdStack(h.r)
entries, err := n.Entries(ctx)
if err != nil {
return err
}
single := n.RustSingle()
var stop []string
for _, s := range services {
name := stack.RunsIn(s, single)
if slices.ContainsFunc(entries, func(e native.PsEntry) bool { return e.Name == name }) && !slices.Contains(stop, name) {
stop = append(stop, name)
}
}
if len(stop) == 0 {
return nil
}
return n.Stop(ctx, stop...)
}
func (h *objectsHost) Apply(_ context.Context, changes map[string]string) error {
p, err := deploy.Prepare(h.inst, changePointers(changes))
if err != nil {
return err
}
h.inst.State.Settings, h.inst.State.Secrets = p.Settings, p.Secrets
return saveInstance(h.inst)
}
func (h *objectsHost) Start(ctx context.Context) error { return migrateStart(ctx, h.app, h.inst) }
func (h *objectsHost) Run(ctx context.Context, with map[string]string, j migrate.Job) error {
return rt.ExecAPI(ctx, h.r, with, engine.ExecOptions{Stdout: j.Stdout, Stderr: j.Stderr}, j.Command(rt.ContainerNode, rt.ContainerMigrate)...)
}
func objectsJournal(dir string) func(*migrate.ObjectsMove) error {
return func(m *migrate.ObjectsMove) error {
st, err := migrate.LoadState(dir)
if err != nil {
return err
}
st.Objects = m
return st.Save(dir)
}
}
func objectsRuntime(ctx context.Context, app *App, inst *instance.Instance) (*objectsHost, error) {
if rt.KindOf(inst) != rt.Container {
return nil, ui.Refused("rexctl moves uploads between plain files and S3 only on one container for now.", "")
}
if err := managed(inst); err != nil {
return nil, err
}
r, err := app.Runtime(ctx, inst)
if err != nil {
return nil, err
}
return &objectsHost{app: app, inst: inst, r: r}, nil
}
type objectsState struct {
files bool
endpoint string
buckets []string
}
func currentObjects(h *objectsHost) (objectsState, error) {
env, err := h.Env(h.Settings())
if err != nil {
return objectsState{}, err
}
return objectsState{
files: strings.TrimSpace(env["FLUXER_STORAGE_BACKEND"]) == settings.StorageFilesystem,
endpoint: strings.TrimSpace(env["FLUXER_S3_ENDPOINT"]),
buckets: migrate.OldBuckets(env),
}, nil
}
func objectsChanges(app *App, h *objectsHost, f *migrateFlags, cur objectsState) (map[string]string, error) {
if f.Migrate == migrate.ToFiles {
if cur.files || cur.endpoint == "" {
return nil, ui.Refused("Uploads are already plain files on this machine.", "")
}
return migrate.FilesChanges(h.Settings()), nil
}
if !cur.files {
return nil, ui.Refused(fmt.Sprintf("Uploads are already in the object store at %s.", cur.endpoint), "To move them back to plain files, run "+migrateCommand+" --migrate files.")
}
changes := map[string]string{settings.StorageBackend: settings.StorageS3}
stdin := false
for _, a := range f.Set {
name, value, ok := strings.Cut(a, "=")
name = strings.TrimSpace(name)
if !ok || name == "" {
return nil, ui.Usage(fmt.Sprintf("%q isn't a setting=value pair.", a))
}
if !slices.Contains(objectsSettable, name) {
return nil, ui.Usage(fmt.Sprintf("--set takes %s, not %s.", ui.JoinAnd(objectsSettable), name))
}
if _, dup := changes[name]; dup {
return nil, ui.Usage(fmt.Sprintf("%s is in the command twice.", name))
}
if value == "-" {
if stdin {
return nil, ui.Usage("Only one setting can take its value from stdin.")
}
stdin = true
v, err := readSecret(app, "-", name)
if err != nil {
return nil, err
}
value = v
}
if strings.TrimSpace(value) == "" {
return nil, ui.Usage(fmt.Sprintf("%s needs a value.", name))
}
changes[name] = value
}
for _, k := range []string{settings.StorageEndpoint, settings.StorageAccess, settings.StorageSecret} {
if changes[k] != "" {
continue
}
if !app.UI.Interactive() || k == settings.StorageEndpoint {
return nil, ui.Usage(fmt.Sprintf("Pass %s with --set, as in %s.", k, objectsExample))
}
v, err := readSecret(app, "-", k)
if err != nil {
return nil, err
}
changes[k] = v
}
return changes, nil
}
const objectsExample = "rexctl migrate --migrate s3 --set storage.endpoint=https://s3.example.com --set storage.access_key=KEY --set storage.secret_key=-"
func objectsDest(to string) string {
if to == migrate.ToS3 {
return "to S3"
}
return "to plain files"
}
func objectsTitle(to string) string {
if to == migrate.ToS3 {
return "Plain files to S3"
}
return "S3 to plain files"
}
func objectsPlan(inst *instance.Instance, to string, cur objectsState, target map[string]string, planned migrate.ObjectsTotals, buckets []string) []ui.PlanItem {
where := "the buckets " + ui.JoinAnd(buckets) + " at " + strings.TrimSpace(target[settings.StorageEndpoint])
copyText := fmt.Sprintf("Copy %d files (%s) to %s", planned.Objects, ui.Bytes(planned.Bytes), where)
switchText := "Switch Fluxer to the object store at " + strings.TrimSpace(target[settings.StorageEndpoint])
keep := ui.PlanItem{Verb: ui.PlanKeep, Text: "Keep the plain files", Detail: "until " + migrateCommand + " --clean-up deletes them"}
if to == migrate.ToFiles {
copyText = fmt.Sprintf("Copy %d files (%s) from the buckets %s at %s to plain files on this machine", planned.Objects, ui.Bytes(planned.Bytes), ui.JoinAnd(cur.buckets), cur.endpoint)
switchText = "Switch Fluxer to plain files"
keep = ui.PlanItem{Verb: ui.PlanKeep, Text: "Keep the files in the buckets " + ui.JoinAnd(cur.buckets), Detail: "rexctl doesn't delete them, even after " + migrateCommand + " --clean-up"}
}
return []ui.PlanItem{
{Verb: ui.PlanCreate, Text: "Back up your instance", Detail: inst.BackupDir()},
{Verb: ui.PlanChange, Text: copyText, Detail: "stops " + ui.JoinAnd(objectsWriters) + " while the files move"},
{Verb: ui.PlanRun, Text: "Check the count and size of every file and the checksums of a sample"},
{Verb: ui.PlanChange, Text: switchText},
{Verb: ui.PlanRun, Text: "Start Fluxer and check attachments through media-proxy", Detail: "if anything fails, rexctl puts everything back"},
keep,
}
}
var objectsWriters = migrate.NewStorageStep().Writers()
func objectsProgress(app *App) func(migrate.Phase) {
return func(p migrate.Phase) { app.UI.Info("%s", sentence(phaseWords(p))) }
}
func objectsReason(err error) string {
if errors.Is(err, migrate.ErrObjectsRelease) {
return "This Fluxer release can't move uploads between plain files and S3. Run rexctl upgrade, then try again."
}
return migrateReason(err)
}
func runObjectsMove(ctx context.Context, app *App, inst *instance.Instance, f *migrateFlags) error {
h, err := objectsRuntime(ctx, app, inst)
if err != nil {
return err
}
st, err := migrate.LoadState(inst.Dir)
if err != nil {
return err
}
if m := st.Objects; m.Pending() {
return ui.Refused(fmt.Sprintf("The last move of the uploads %s isn't finished.", objectsDest(m.To)), fmt.Sprintf("Run %s --undo %s to go back, or %s --clean-up to keep it.", migrateCommand, m.To, migrateCommand))
}
cur, err := currentObjects(h)
if err != nil {
return err
}
changes, err := objectsChanges(app, h, f, cur)
if err != nil {
return err
}
o := &migrate.ObjectsRun{Host: h, To: f.Migrate, Changes: changes, Log: migrateOutput(app), Journal: objectsJournal(inst.Dir), OnPhase: objectsProgress(app)}
target := merged(h.Settings(), changes)
targetEnv, err := h.Env(target)
if err != nil {
return err
}
if err := o.Preflight(ctx); err != nil {
return &ui.ExitError{Code: ui.ExitRefused, Msg: "rexctl didn't change anything.", Fix: objectsReason(err), Err: err}
}
plan := objectsPlan(inst, f.Migrate, cur, target, o.Planned, migrate.OldBuckets(targetEnv))
if f.DryRun {
app.UI.Plan("rexctl would do this", plan...)
app.UI.Info("Dry run. Nothing changed.")
return nil
}
app.UI.Plan("rexctl will do this", plan...)
ok, err := app.UI.Confirm("Move the uploads?", true)
if err != nil {
return err
}
if !ok {
app.UI.Info("Nothing changed.")
return nil
}
app.UI.Section(objectsTitle(f.Migrate))
err = app.Locked(ctx, inst, func() error { return o.Execute(ctx) })
if err != nil {
return objectsFailure(err, o.Backup)
}
for _, n := range o.Notes {
app.UI.Info("%s", n)
}
app.UI.OK("Moved the uploads. The backup from before the move is %s.", o.Backup)
if f.Migrate == migrate.ToS3 {
app.UI.Info("The plain files stay on this machine. To go back, run %s --undo s3. Once uploads look right, %s --clean-up deletes the plain files.", migrateCommand, migrateCommand)
} else {
app.UI.Info("The files stay in the buckets %s. To go back, run %s --undo files. Once uploads look right, run %s --clean-up, then delete the buckets yourself.", ui.JoinAnd(cur.buckets), migrateCommand, migrateCommand)
}
return nil
}
func objectsFailure(err error, backup string) error {
var fail *migrate.Failure
if !errors.As(err, &fail) {
return err
}
reason := objectsReason(fail.Err)
switch {
case fail.Phase == migrate.PhasePreflight:
return &ui.ExitError{Code: ui.ExitRefused, Msg: "rexctl didn't change anything.", Fix: reason, Err: err}
case backup == "":
return ui.Wrap(err, "rexctl didn't change anything.", reason)
case fail.Rollback == nil:
return ui.Wrap(err, "The move didn't work, and rexctl put your instance back as it was. "+reason, "The backup from before the move is "+backup+".")
}
return ui.Wrap(err, "The move didn't work, and rexctl couldn't put everything back. "+reason+" "+sentence(migrateReason(fail.Rollback)), "Run rexctl status to check Fluxer, or restore the backup from before the move with rexctl restore "+backup+".")
}
func runObjectsUndo(ctx context.Context, app *App, inst *instance.Instance, to string) error {
h, err := objectsRuntime(ctx, app, inst)
if err != nil {
return err
}
st, err := migrate.LoadState(inst.Dir)
if err != nil {
return err
}
m := st.Objects
if !m.Pending() || m.To != to {
return ui.Refused(fmt.Sprintf("rexctl migrate didn't move the uploads %s on this instance, or the move is already cleaned up.", objectsDest(to)), "Run "+migrateCommand+" --dry-run --migrate "+to+" to see what's possible.")
}
what := "This copies the uploads that came in since the move into the plain files, switches Fluxer back to them and deletes the objects in the buckets."
if to == migrate.ToFiles {
what = "This copies the uploads that came in since the move into the buckets, switches Fluxer back to the object store and deletes the plain files."
}
app.UI.Info("%s", what)
if ok, err := app.UI.Confirm("Go back?", false); err != nil || !ok {
return err
}
o := &migrate.ObjectsRun{Host: h, To: to, Log: migrateOutput(app), Journal: objectsJournal(inst.Dir), OnPhase: objectsProgress(app)}
if err := app.Locked(ctx, inst, func() error { return migrate.UndoObjects(ctx, o, m) }); err != nil {
return ui.Wrap(err, "Couldn't go back. Fluxer still uses the storage it moved to.", objectsReason(err))
}
for _, n := range o.Notes {
app.UI.Info("%s", n)
}
if to == migrate.ToS3 {
app.UI.OK("Went back to plain files.")
} else {
app.UI.OK("Went back to the object store.")
}
return nil
}
func runObjectsCleanUp(ctx context.Context, app *App, inst *instance.Instance, st *migrate.State, confirm string) error {
h, err := objectsRuntime(ctx, app, inst)
if err != nil {
return err
}
m := st.Objects
if m.To == migrate.ToS3 {
if err := app.UI.ConfirmDestructive(fmt.Sprintf("This deletes the plain files in %s in Fluxer's container, which Fluxer no longer uses since the move to S3. Backups made before the move still have them.", rt.ContainerObjects), inst.Domain(), confirm); err != nil {
return err
}
}
prev := merged(h.Settings(), m.Previous)
env, err := h.Env(prev)
if err != nil {
return err
}
err = app.Locked(ctx, inst, func() error {
if err := migrate.CleanUpObjects(ctx, h, m, time.Now(), migrateOutput(app)); err != nil {
return err
}
return st.Save(inst.Dir)
})
if err != nil {
return ui.Wrap(err, "Couldn't clean up after the move of the uploads.", objectsReason(err))
}
if m.To == migrate.ToS3 {
app.UI.OK("Deleted the plain files.")
return nil
}
app.UI.OK("The move to plain files is complete.")
app.UI.Info("rexctl doesn't delete objects in your own object store. The files from before the move are still in the buckets %s at %s. Delete them there once you no longer need them.", ui.JoinAnd(migrate.OldBuckets(env)), strings.TrimSpace(env["FLUXER_S3_ENDPOINT"]))
return nil
}