dr

package
v1.2.3 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: AGPL-3.0 Imports: 24 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 dr coordinates disaster recovery (ADR-0069): protection groups replicate a set of machines from one host to another (through internal/zfsrep) with an RPO target, and recovery plans bring whole stacks back up — as a test in isolated networks or for real, with failback reversing the replication direction.

Index

Constants

View Source
const (
	StatusProtected   = "protected"
	StatusRPOBreached = "rpo_breached"
	StatusSyncing     = "syncing"
	StatusFailedOver  = "failed_over"
	StatusError       = "error"
)

Status values of a protection group.

View Source
const (
	ModeTestFailover ExecutionMode  = "test_failover"
	ModeTestCleanup  ExecutionMode  = "test_cleanup"
	ModeRealFailover ExecutionMode  = "real_failover"
	ModeFailback     ExecutionMode  = "failback"
	StateRunning     ExecutionState = "running"
	StateSucceeded   ExecutionState = "succeeded"
	StateFailed      ExecutionState = "failed"
	StateTestActive  ExecutionState = "test_active"
	StateTestCleaned ExecutionState = "test_cleaned"
)

ExecutionMode is what an execution run does, ExecutionState what it ended up as.

View Source
const DRPrefix = "virtomir-dr-"

DRPrefix marks snapshots DR itself makes on the target host; replication snapshots keep zfsrep.SnapPrefix.

Variables

View Source
var (
	ErrNotFound = errors.New("not found")
	ErrInvalid  = errors.New("invalid")
	ErrConflict = errors.New("conflict")
	ErrBusy     = errors.New("busy")
)

ErrNotFound marks an unknown ID, ErrInvalid a group or plan that cannot be saved, ErrConflict an ID that exists already and ErrBusy a delete that would break a reference (a plan over a protection group).

Functions

func BuildDRDomainXML

func BuildDRDomainXML(origDoc string, drName string, diskMap map[string]string, netMap map[string]string, seedISOPath string) (string, error)

BuildDRDomainXML turns a source machine's definition into one that can run on the DR host from the replicated (or cloned) disks: a new name and UUID, disks repointed at the DR copies, networks remapped, old installation media ejected, the cloud-init seed (re)attached, and machine-specific state (UEFI variables, TPM) left behind so a fresh instance starts here.

func DestroyTestClones

func DestroyTestClones(ctx context.Context, r ZFSRunner, clones []CloneInfo) error

DestroyTestClones removes every clone a test failover made, collecting any errors instead of stopping at the first, so one stubborn clone cannot leak the rest. Cleanup runs even when ctx was cancelled, like rollbackClones: a torn-down test must not leave clones behind just because its run was.

func FindLatestReplicaSnapshot

func FindLatestReplicaSnapshot(ctx context.Context, r ZFSRunner, dataset string, prefix string) (string, error)

FindLatestReplicaSnapshot returns the tag (the part after "@") of the newest snapshot of dataset whose tag begins with prefix. An empty prefix means the replication snapshots of zfsrep.SnapPrefix. Snapshots come back oldest first (zfs list -s creation), so the last matching line is the newest one.

func GenerateCloudInitNetworkISO

func GenerateCloudInitNetworkISO(hostname string, ipConf IPConfig, targetPath string) error

GenerateCloudInitNetworkISO writes a NoCloud seed image (ISO 9660, volume label "cidata") to targetPath: minimal user-data, a DR-flavoured meta-data and a network-config that re-addresses the replica's interface. The replica keeps the source MAC, so it must not answer on the real network under its old address.

func PromoteReplica

func PromoteReplica(ctx context.Context, r ZFSRunner, disks []ReplicatedDisk) error

PromoteReplica makes the replicas writable for a real failover: a zfs receive lands readonly, so the DR host can start the machine but not write to its disks until readonly is turned off.

Types

type AlertNotifier

type AlertNotifier interface {
	Notice(subject, message string)
}

AlertNotifier delivers news (not alerts): nothing but ENGINE.Notice, so DR can post through the alert channels (internal/alerts).

type BootGroup

type BootGroup struct {
	ID           string   `json:"id"`
	Name         string   `json:"name"`
	Order        int      `json:"order"`
	DelaySeconds int      `json:"delaySeconds"`
	VMs          []PlanVM `json:"vms"`
}

BootGroup starts its machines together, at a given Order, DelaySeconds after the group before it (databases first, then middle tiers, then front ends).

type CloneInfo

type CloneInfo struct {
	SourceDataset string `json:"sourceDataset"`
	Snapshot      string `json:"snapshot"`
	CloneDataset  string `json:"cloneDataset"`
	TargetDev     string `json:"targetDev"`
}

CloneInfo is one test clone DR made from a disk's latest replica snapshot.

func CreateTestClones

func CreateTestClones(ctx context.Context, r ZFSRunner, targetPool string, disks []ReplicatedDisk, runID string) ([]CloneInfo, error)

CreateTestClones clones each disk's latest replica snapshot into the target pool, so a test failover runs on throwaway copies that leave the replica itself (and production) untouched. The clone of disk SourceVolume is named <targetPool>/virtomir-test-<runID>-<SourceVolume>. If any clone fails, the clones made so far are destroyed in reverse order and the error is returned.

type DefaultHookRunner

type DefaultHookRunner struct {
	Shell []string // program and flags, e.g. ["sh", "-c"]
}

DefaultHookRunner runs a script with `sh -c` (or `bash -c`), waits up to timeout, and returns the combined output of stdout and stderr.

func NewDefaultHookRunner

func NewDefaultHookRunner() *DefaultHookRunner

NewDefaultHookRunner picks the first shell it finds, sh before bash.

func (*DefaultHookRunner) RunHook

func (h *DefaultHookRunner) RunHook(ctx context.Context, script string, env []string, timeout time.Duration) ([]byte, error)

RunHook executes the script in a subshell with env appended to the process environment; without a shell it is a configuration error, not a crash. The shell runs in its own process group: when the deadline fires the whole group — the shell and any children it spawned — is killed, and the same kill bounds the output wait when the shell has already exited but a child still holds the pipe (`sh -c 'sleep 300 &'` returns while sleep keeps the write end open). Either way the run stops within its deadline, and a caller's cancellation of ctx is handled the same way.

type ExecutionMode

type ExecutionMode string

ExecutionMode is what an execution run is doing; ExecutionState is where the run (or an active test) stands.

type ExecutionRun

type ExecutionRun struct {
	ID           string         `json:"id"`
	PlanID       string         `json:"planId"`
	Mode         ExecutionMode  `json:"mode"`
	State        ExecutionState `json:"state"`
	Started      time.Time      `json:"started"`
	Finished     *time.Time     `json:"finished,omitempty"`
	ErrorMessage string         `json:"errorMessage,omitempty"`
	Steps        []StepLog      `json:"steps"`
}

ExecutionRun is one run of a recovery plan (a test or the real thing), with every step it performed and how each went.

func ExecuteFailback

func ExecuteFailback(
	ctx context.Context,
	planID string,
	prodVirt VirtController,
	drVirt VirtController,
	zfs ZFSRunner,
	hooks HookRunner,
	report func(StepLog),
) (ExecutionRun, error)

ExecuteFailback executes reverse replication and failback on DefaultOrchestrator.

func ExecuteRealFailover

func ExecuteRealFailover(
	ctx context.Context,
	planID string,
	opts FailoverOpts,
	prodVirt VirtController,
	drVirt VirtController,
	zfs ZFSRunner,
	rep ReplicationSyncer,
	hooks HookRunner,
	report func(StepLog),
) (ExecutionRun, error)

ExecuteRealFailover executes real disaster failover on DefaultOrchestrator.

type ExecutionState

type ExecutionState string

type FailoverEngine

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

FailoverEngine executes real disaster failover and failback, holding the controllers and runners its steps need so callers only pass a plan, options and a report. It wraps the orchestrator's ExecuteRealFailover and ExecuteFailback with pre-bound prodVirt, drVirt, zfs, rep and hooks.

func NewFailoverEngine

func NewFailoverEngine(o *Orchestrator, prodVirt, drVirt VirtController, zfs ZFSRunner, rep ReplicationSyncer, hooks HookRunner, log *slog.Logger) *FailoverEngine

NewFailoverEngine wires a failover engine over the orchestrator and the drivers its steps call: prodVirt (the production host) and drVirt (the DR host). When drVirt is nil it falls back to the orchestrator's own virt controller; when prodVirt is nil the pre-sync reachability check is skipped (forced failover only).

func (*FailoverEngine) ExecuteFailback

func (e *FailoverEngine) ExecuteFailback(ctx context.Context, planID string, report func(StepLog)) (ExecutionRun, error)

ExecuteFailback runs a failback for planID, using the engine's bound controllers and runners.

func (*FailoverEngine) ExecuteRealFailover

func (e *FailoverEngine) ExecuteRealFailover(ctx context.Context, planID string, opts FailoverOpts, report func(StepLog)) (ExecutionRun, error)

ExecuteRealFailover runs a real failover for planID, using the engine's bound controllers and runners instead of accepting them per-call.

func (*FailoverEngine) SyncGroup

func (e *FailoverEngine) SyncGroup(ctx context.Context, groupID string) (time.Time, error)

SyncGroup triggers an immediate replication pass for the protection group identified by groupID. It asks the replication layer (internal/zfsrep) to start a pass; an empty rep means DR sync is not configured on this host.

type FailoverOpts

type FailoverOpts struct {
	Force       bool `json:"force"`
	SkipPreSync bool `json:"skipPreSync"`
}

FailoverOpts configures real disaster failover execution.

type HookRunner

type HookRunner interface {
	RunHook(ctx context.Context, script string, env []string, timeout time.Duration) ([]byte, error)
}

HookRunner runs a recovery plan's hook scripts in the DR host's shell.

type IPConfig

type IPConfig struct {
	InterfaceMAC string   `json:"interfaceMac,omitempty"`
	IPv4Address  string   `json:"ipv4Address"`
	IPv4Gateway  string   `json:"ipv4Gateway,omitempty"`
	Nameservers  []string `json:"nameservers,omitempty"`
}

IPConfig re-addresses one interface of a failover copy: the replica keeps the source machine's MAC, so it needs a new address before it may talk.

type NetworkMap

type NetworkMap struct {
	SourceNetwork       string `json:"sourceNetwork"`
	TargetNetwork       string `json:"targetNetwork"`
	IsolatedTestNetwork string `json:"isolatedTestNetwork,omitempty"`
}

NetworkMap sends the traffic of the source network to another one on the target; IsolatedTestNetwork keeps test-failover copies off the real networks.

type Orchestrator

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

Orchestrator executes recovery plans on the DR host: a test failover runs the plan's machines from fresh test clones in isolated networks until its cleanup releases them. One run may be active per plan (activeRuns), and xmlCache keeps the last source definition seen of each machine so a failed live fetch can still fall back to it.

var DefaultOrchestrator *Orchestrator

DefaultOrchestrator is the orchestrator used by package-level ExecuteRealFailover and ExecuteFailback.

func NewOrchestrator

func NewOrchestrator(store *Store, zfs ZFSRunner, virt VirtController, hooks HookRunner, log *slog.Logger, stateDir string) *Orchestrator

NewOrchestrator wires an orchestrator over the store and its ZFS, libvirt and hook runners; stateDir is where a run's seed ISO lands ("" if nowhere).

func (*Orchestrator) ExecuteFailback

func (o *Orchestrator) ExecuteFailback(
	ctx context.Context,
	planID string,
	prodVirt VirtController,
	drVirt VirtController,
	zfs ZFSRunner,
	hooks HookRunner,
	report func(StepLog),
) (ExecutionRun, error)

ExecuteFailback executes reverse replication and failback to the restored primary host (ADR-0069).

func (*Orchestrator) ExecuteRealFailover

func (o *Orchestrator) ExecuteRealFailover(
	ctx context.Context,
	planID string,
	opts FailoverOpts,
	prodVirt VirtController,
	drVirt VirtController,
	zfs ZFSRunner,
	rep ReplicationSyncer,
	hooks HookRunner,
	report func(StepLog),
) (ExecutionRun, error)

ExecuteRealFailover executes real disaster failover (ADR-0069).

func (*Orchestrator) ExecuteTestCleanup

func (o *Orchestrator) ExecuteTestCleanup(ctx context.Context, planID, runID string, report func(StepLog)) (ExecutionRun, error)

ExecuteTestCleanup stops and undefines the test domains of an active test failover, destroys its clones and removes its seed ISO, closing the run as test_cleaned. The newest record of the run decides whether it is active, so a retry after a partial cleanup still sees the right state.

func (*Orchestrator) ExecuteTestFailover

func (o *Orchestrator) ExecuteTestFailover(ctx context.Context, planID string, report func(StepLog)) (ExecutionRun, error)

ExecuteTestFailover runs the plan as a test: it verifies every machine of the protection group has a fresh replica snapshot, clones those replicas, defines throwaway domains on the clones in the plan's boot order (isolated networks and re-addressing applied) and runs the plan's hooks around it. The run stays active — with the test domains still running — until ExecuteTestCleanup releases it.

func (*Orchestrator) GetDiskMappings

func (o *Orchestrator) GetDiskMappings(ctx context.Context, group ProtectionGroup) ([]VMDiskMapping, error)

GetDiskMappings reads every machine of the protection group and returns its replicated disk mapping: which source volume maps to which target volume, the pool and volume names, and the latest replica snapshot found, so the UI can show the group's VM disk mappings on the group details page.

type PlanVM

type PlanVM struct {
	VMUUID          string       `json:"vmUuid"`
	SourceName      string       `json:"sourceName"`
	DRVMName        string       `json:"drVmName,omitempty"`
	NetworkMappings []NetworkMap `json:"networkMappings,omitempty"`
	IPReaddressing  *IPConfig    `json:"ipReaddressing,omitempty"`
	StopOnError     bool         `json:"stopOnError"`
}

PlanVM is one machine inside a boot group of a recovery plan.

type ProtectionGroup

type ProtectionGroup struct {
	ID                  string    `json:"id"`
	Name                string    `json:"name"`
	Description         string    `json:"description,omitempty"`
	SourceHost          string    `json:"sourceHost"`
	TargetHost          string    `json:"targetHost"`
	ActiveHost          string    `json:"activeHost,omitempty"`
	TargetPool          string    `json:"targetPool"`
	VMUUIDs             []string  `json:"vmUuids"`
	RPOMinutes          int       `json:"rpoMinutes"`
	ReplicationInterval int       `json:"replicationInterval"`
	Enabled             bool      `json:"enabled"`
	Status              string    `json:"status"` // protected, rpo_breached, syncing, failed_over, error
	Created             time.Time `json:"created"`
	Updated             time.Time `json:"updated"`
}

ProtectionGroup watches a set of machines that is replicated from one host to another, with an RPO target (how much data loss in minutes is tolerable) and a replication interval.

type RPOStatus

type RPOStatus struct {
	GroupID           string    `json:"groupId"`
	RPOMinutes        int       `json:"rpoMinutes"`
	LastSync          time.Time `json:"lastSync,omitzero"`
	LagMinutes        int       `json:"lagMinutes"`
	Breached          bool      `json:"breached"`
	CompliancePercent float64   `json:"compliancePercent"`
}

RPOStatus is a protection group's replication lag against its RPO target.

func CalculateRPO

func CalculateRPO(group ProtectionGroup, lastSync, now time.Time) RPOStatus

CalculateRPO computes how far a group's replication lags behind its RPO target: without a last sync it counts from the group's creation, otherwise from the last successful sync. Compliance is how close the lag is to the target (100 % means within it, 0 % unusably late).

func CheckRPOCompliance

func CheckRPOCompliance(store *Store, getReplicationLastSync func(group ProtectionGroup) (time.Time, error), notifier AlertNotifier, now time.Time) []RPOStatus

CheckRPOCompliance runs the RPO check over every enabled protection group: a breached group is marked rpo_breached and a notice is sent, a compliant group is marked protected again. The getReplicationLastSync hook asks the replication layer (internal/zfsrep) when the group last synced.

type RecoveryPlan

type RecoveryPlan struct {
	ID                string      `json:"id"`
	Name              string      `json:"name"`
	Description       string      `json:"description,omitempty"`
	ProtectionGroupID string      `json:"protectionGroupId"`
	BootGroups        []BootGroup `json:"bootGroups"`
	PreHookScript     string      `json:"preHookScript,omitempty"`
	PostHookScript    string      `json:"postHookScript,omitempty"`
	HookTimeoutSec    int         `json:"hookTimeoutSec,omitempty"`
	Created           time.Time   `json:"created"`
	Updated           time.Time   `json:"updated"`
}

RecoveryPlan brings a protection group back up: which machines, in which order, on which networks, with hook scripts around the whole run.

type ReplicatedDisk

type ReplicatedDisk struct {
	Dev              string    `json:"dev"`
	SourcePool       string    `json:"sourcePool"`
	SourceVolume     string    `json:"sourceVolume"`
	TargetPool       string    `json:"targetPool"`
	TargetVolume     string    `json:"targetVolume"`
	LatestSnapshot   string    `json:"latestSnapshot,omitempty"`
	LastSync         time.Time `json:"lastSync,omitzero"`
	BytesTransferred uint64    `json:"bytesTransferred,omitempty"`
}

ReplicatedDisk is one disk of a machine and where its replica lives.

type ReplicationSyncer

type ReplicationSyncer interface {
	Start(id string) (zfsrep.Status, error)
}

ReplicationSyncer triggers immediate replication passes (internal/zfsrep).

type StepLog

type StepLog struct {
	ID          string     `json:"id"`
	Name        string     `json:"name"`
	BootGroupID string     `json:"bootGroupId,omitempty"`
	VMUUID      string     `json:"vmUuid,omitempty"`
	DomainUUID  string     `json:"domainUuid,omitempty"` // the test domain the step defined, so cleanup can stop it
	Status      StepStatus `json:"status"`
	Output      string     `json:"output,omitempty"`
	Error       string     `json:"error,omitempty"`
	Started     time.Time  `json:"started"`
	Finished    *time.Time `json:"finished,omitempty"`
}

StepLog records how one step of an execution run went.

type StepStatus

type StepStatus string

StepStatus is where one step of an execution run stands.

const (
	StepPending   StepStatus = "pending"
	StepRunning   StepStatus = "running"
	StepSucceeded StepStatus = "succeeded"
	StepFailed    StepStatus = "failed"
	StepSkipped   StepStatus = "skipped"
)

StepStatus values of one step of an execution run.

type Store

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

Store keeps protection groups, recovery plans and execution-run history in one JSON file (<state-dir>/dr.json).

func Open

func Open(path string) (*Store, error)

Open loads path (a missing file is fine).

func (*Store) CreatePlan

func (s *Store) CreatePlan(p RecoveryPlan) (RecoveryPlan, error)

CreatePlan adds a recovery plan; an empty ID gets a generated one.

func (*Store) CreateProtectionGroup

func (s *Store) CreateProtectionGroup(g ProtectionGroup) (ProtectionGroup, error)

CreateProtectionGroup adds a group; an empty ID gets a generated one.

func (*Store) DeletePlan

func (s *Store) DeletePlan(id string) error

DeletePlan removes a recovery plan.

func (*Store) DeleteProtectionGroup

func (s *Store) DeleteProtectionGroup(id string) error

DeleteProtectionGroup removes a group; plans over it have to go first.

func (*Store) GetPlan

func (s *Store) GetPlan(id string) (RecoveryPlan, bool)

GetPlan returns one recovery plan.

func (*Store) GetProtectionGroup

func (s *Store) GetProtectionGroup(id string) (ProtectionGroup, bool)

GetProtectionGroup returns one protection group.

func (*Store) GetRun

func (s *Store) GetRun(id string) (ExecutionRun, bool)

GetRun returns one execution run from the history (newest first).

func (*Store) ListPlans

func (s *Store) ListPlans(protectionGroupID string) []RecoveryPlan

ListPlans returns recovery plans (filtered by protection group when given), by name.

func (*Store) ListProtectionGroups

func (s *Store) ListProtectionGroups() []ProtectionGroup

ListProtectionGroups returns every protection group, by ID.

func (*Store) ListRuns

func (s *Store) ListRuns(planID string) []ExecutionRun

ListRuns returns execution runs, newest first (optionally filtered by plan).

func (*Store) RecordRun

func (s *Store) RecordRun(run ExecutionRun) error

RecordRun appends an execution run to the history; only the newest maxRuns stay.

func (*Store) SetGroupActiveHost

func (s *Store) SetGroupActiveHost(id, activeHost, status string) error

SetGroupActiveHost updates a protection group's active host and status.

func (*Store) UpdatePlan

func (s *Store) UpdatePlan(p RecoveryPlan) error

UpdatePlan changes a recovery plan's fields (not its created time).

func (*Store) UpdateProtectionGroup

func (s *Store) UpdateProtectionGroup(g ProtectionGroup) error

UpdateProtectionGroup changes a group's fields (not its created time or status).

type VMDiskMapping

type VMDiskMapping struct {
	VMUUID     string           `json:"vmUuid"`
	DomainName string           `json:"domainName"`
	Disks      []ReplicatedDisk `json:"disks"`
}

VMDiskMapping records which replica disk belongs to which source machine, so start-from-replica knows what to clone and failback knows what to send back.

type VirtController

type VirtController interface {
	GetDomainXML(uuid string) (string, error)
	DefineDomain(xmlDoc string) (string, error)
	StartDomain(uuid string) error
	StopDomain(uuid string, force bool) error
	UndefineDomain(uuid string) error
	DomainState(uuid string) (string, error)
}

VirtController is the seam the orchestrator uses to read source definitions and run the test domains on a host; internal/api wires it to libvirt, cluster forwarding included.

type ZFSRunner

type ZFSRunner interface {
	Run(ctx context.Context, name string, args ...string) ([]byte, error)
}

ZFSRunner runs zfs commands (internal/zfsrep.Exec on a real host, a fake in tests). It mirrors the subset of zfsrep.Runner DR needs to inspect and clone replicas, without opening an ssh pipe.

Jump to

Keyboard shortcuts

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