Add cutover; drop rollback in favour of operator-provided recovery
Two changes that arrived together: the cutover phase (ARCHITECTURE.md 4.5) is implemented, and the rollback phase is deleted. Recovery from a failed migration is now explicitly the operator's own snapshot or backup, and out of scope for this tool. internal/cutover implements 4.5 as seven checkpointed steps: verify the staged binary's version, install it, preserve and rewrite the service definition, reload, start, wait for a healthy JMAP session, recalculate quotas. The unit is rewritten in place rather than generated from a template. An operator's unit carries hardening options, limits and dependencies this tool has no business having an opinion about, and regenerating it would silently drop them. It repoints ExecStart (preserving systemd's -@:+! prefix characters and every argument after the executable), updates --config, and strips recovery-mode Environment lines - leaving STALWART_RECOVERY_MODE=1 set would recovery-boot the service on every restart, forever. It refuses on a unit with no ExecStart, and on an Environment line mixing a recovery variable with others: a line it only partly understands is one it must not edit. Quota recalculation is the one step allowed to fail without failing the phase. Its wire format is grounded in Stalwart's x:Task schema reference - Task/set creating one AccountMaintenance per account with maintenanceType recalculateQuota - but the upgrade guide only documents the WebUI path, so two details remain inferred and are called out in stalwartapi/task.go: whether the schema's "read-only" annotation on accountId/maintenanceType means "immutable after creation", and whether a finished task simply leaves the queue (TaskStatus documents Pending/Retry/Failed with no success state). Warning rather than failing is the honest response to that uncertainty, and stale counters are an accounting problem next to calling for a restore of a machine that is otherwise migrated and serving mail. Docker deployments are refused outright: cutting a container over means pulling an image and recreating it, not swapping a binary. On removing rollback. The implementation worked and was tested, and it was removed because restoring bytes correctly is not the hard part. It copied file contents and permissions and verified every restored file against a manifest - and did not preserve ownership. Run as root, as this tool requires, it would have produced a byte-perfect, checksum-verified, root-owned data directory that Stalwart, running as its own user, could not open, and it would have reported success. The PostgreSQL path was worse: pg_dump without --clean emits CREATE TABLE + COPY, which fails replaying into a database whose tables still exist, and the ON_ERROR_STOP=1 added so a half-applied restore couldn't be reported as success turned that into a hard failure. None of it had ever run against a real server. A filesystem snapshot has none of these failure modes, because it never lost the metadata to begin with. So cutover's gate is no longer rollback.CanRollBack but an explicit RecoveryPointConfirmed acknowledgement. That is an assertion, not a check - this tool cannot verify someone else's snapshot - and its only value is that nobody migrates a production mail server having never been asked the question. Two consequences are accepted deliberately: restoring any pre-migration recovery point discards mail delivered since, and a failed migration now stops and reports rather than undoing itself. What the tool still does to make a manual restore easier: the old binary is preserved and never deleted, the original service definition is preserved before the rewrite, the settings and principals dumps stay on disk, and every artifact path and checksum stays in the checkpoint where `status <run-id>` can print it. Also removed: the `confirm` command stub and RollbackWindowClosed, whose only purpose was closing a rollback window that no longer exists, and checkpoint.PhaseRollback. Old state.json files still load - JSON ignores the now-unknown field. Still open, and recorded in 8: cutover ignores systemd drop-ins, so an ExecStart or Environment override in stalwart.service.d/*.conf is invisible to the rewrite - including the recovery variable it exists to strip; nothing prevents concurrent runs on the same run-id; and nothing in this repo has ever run against a real Stalwart, real systemd, or a real store.
This commit is contained in:
@@ -0,0 +1,128 @@
|
||||
package cutover
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// recoveryEnvVars are the two variables that must never survive into the
|
||||
// live service definition. ARCHITECTURE.md §4.5 calls leaving
|
||||
// STALWART_RECOVERY_MODE=1 set a documented footgun, and it is: the service
|
||||
// would recovery-boot on every restart from then on, quietly, forever.
|
||||
//
|
||||
// This tool never puts them in a unit itself - internal/recovery runs
|
||||
// recovery mode as a supervised child process, not through systemd - so
|
||||
// finding them here means an operator followed the manual upgrade guide by
|
||||
// hand at some point. That's exactly the case worth catching.
|
||||
var recoveryEnvVars = []string{"STALWART_RECOVERY_MODE", "STALWART_RECOVERY_ADMIN"}
|
||||
|
||||
// RewriteUnit points a systemd unit's ExecStart at a new binary (and, if
|
||||
// configPath is non-empty, a new --config path) and strips any recovery-mode
|
||||
// environment lines, returning the rewritten file.
|
||||
//
|
||||
// It rewrites in place rather than generating a unit from a template: the
|
||||
// operator's unit is theirs, and it may carry hardening options, resource
|
||||
// limits, dependencies and overrides this tool has no business having an
|
||||
// opinion about. Replacing it with something generated would silently drop
|
||||
// all of that.
|
||||
//
|
||||
// It refuses rather than guesses in two cases: a unit with no ExecStart at
|
||||
// all, and an Environment line that mixes a recovery variable with other
|
||||
// variables. Both mean the file isn't shaped the way this rewrite assumes,
|
||||
// and editing it anyway risks producing a unit that starts something other
|
||||
// than what the operator intended.
|
||||
func RewriteUnit(unit, binaryPath, configPath string) (string, error) {
|
||||
lines := strings.Split(unit, "\n")
|
||||
out := make([]string, 0, len(lines))
|
||||
execStarts := 0
|
||||
|
||||
for _, line := range lines {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
|
||||
if strings.HasPrefix(trimmed, "ExecStart=") {
|
||||
rewritten, err := rewriteExecStart(line, binaryPath, configPath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
execStarts++
|
||||
out = append(out, rewritten)
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.HasPrefix(trimmed, "Environment=") || strings.HasPrefix(trimmed, "Environment ") {
|
||||
mentions, only := classifyEnvironmentLine(trimmed)
|
||||
if mentions && !only {
|
||||
return "", fmt.Errorf(
|
||||
"cutover: the unit's %q line sets a recovery-mode variable alongside others, and this tool won't edit a line it "+
|
||||
"only partly understands - remove the STALWART_RECOVERY_* assignment by hand and re-run", trimmed)
|
||||
}
|
||||
if mentions {
|
||||
continue // the whole line is recovery-only: drop it
|
||||
}
|
||||
}
|
||||
|
||||
out = append(out, line)
|
||||
}
|
||||
|
||||
if execStarts == 0 {
|
||||
return "", fmt.Errorf("cutover: the service definition has no ExecStart= line, so there's nothing to point at the new binary - is this the right unit file?")
|
||||
}
|
||||
return strings.Join(out, "\n"), nil
|
||||
}
|
||||
|
||||
// rewriteExecStart replaces the executable in an ExecStart line, preserving
|
||||
// every argument after it (and any leading whitespace or systemd prefix
|
||||
// characters like "-" or "@"), then updates --config if asked to.
|
||||
func rewriteExecStart(line, binaryPath, configPath string) (string, error) {
|
||||
indent := line[:len(line)-len(strings.TrimLeft(line, " \t"))]
|
||||
value := strings.TrimSpace(line)[len("ExecStart="):]
|
||||
|
||||
// systemd allows prefix characters on the executable ("-", "@", ":",
|
||||
// "+", "!"). Preserve whatever is there rather than dropping semantics
|
||||
// the operator chose deliberately.
|
||||
prefix := ""
|
||||
for len(value) > 0 && strings.ContainsRune("-@:+!", rune(value[0])) {
|
||||
prefix += string(value[0])
|
||||
value = value[1:]
|
||||
}
|
||||
|
||||
fields := strings.Fields(value)
|
||||
if len(fields) == 0 {
|
||||
return "", fmt.Errorf("cutover: the unit's ExecStart= line names no executable")
|
||||
}
|
||||
fields[0] = binaryPath
|
||||
|
||||
if configPath != "" {
|
||||
replaced := false
|
||||
for i := 0; i < len(fields)-1; i++ {
|
||||
if fields[i] == "--config" || fields[i] == "-c" {
|
||||
fields[i+1] = configPath
|
||||
replaced = true
|
||||
}
|
||||
}
|
||||
if !replaced {
|
||||
fields = append(fields, "--config", configPath)
|
||||
}
|
||||
}
|
||||
return indent + "ExecStart=" + prefix + strings.Join(fields, " "), nil
|
||||
}
|
||||
|
||||
// classifyEnvironmentLine reports whether an Environment= line mentions a
|
||||
// recovery variable at all, and whether that's all it sets.
|
||||
func classifyEnvironmentLine(trimmed string) (mentions, only bool) {
|
||||
value := trimmed[strings.Index(trimmed, "=")+1:]
|
||||
assignments := strings.Fields(value)
|
||||
if len(assignments) == 0 {
|
||||
return false, false
|
||||
}
|
||||
recoveryCount := 0
|
||||
for _, a := range assignments {
|
||||
a = strings.Trim(a, `"'`)
|
||||
for _, name := range recoveryEnvVars {
|
||||
if strings.HasPrefix(a, name+"=") {
|
||||
recoveryCount++
|
||||
}
|
||||
}
|
||||
}
|
||||
return recoveryCount > 0, recoveryCount == len(assignments)
|
||||
}
|
||||
Reference in New Issue
Block a user