bootstrap

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 36 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 bootstrap handles infrastructure bootstrapping operations for OCFP environments.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNoStateForRollback      = errors.New("no state available for rollback")
	ErrRollbackPartiallyFailed = errors.New("rollback partially failed")
)

Bootstrap errors.

View Source
var (
	ErrInvalidCIDROffsetNegative = errors.New("CIDR offset must be non-negative")
	ErrInvalidCIDR               = errors.New("invalid CIDR")
	ErrOffsetOutOfRange          = errors.New("offset out of range for uint32")
)

Network configuration errors.

View Source
var (
	ErrRecycleNoBastion    = errors.New("no bastion recorded for this bloc; nothing to recycle")
	ErrRecycleNoDataVolume = errors.New("no preserved data volume recorded; the disk to carry across is unknown")
	ErrRecycleImageMissing = errors.New(
		"the configured image is not present on the cluster. Build it first with `ocfp pve template provision <name>`")
	ErrArchiveUnsupported = errors.New(
		"this provider cannot take an archive from the CLI; take one yourself before continuing")
)

Errors returned by the recycle adapter.

View Source
var ErrArtifactsVaultUnavailable = errors.New("vault access unavailable for this bootstrap run")

ErrArtifactsVaultUnavailable is the cause wrapped into the actionable internal-ca vault error when this bootstrap run never obtained vault access at all (SetSafe was never called — see executeBootstrap in internal/commands/bootstrap.go), as opposed to a specific dial/auth failure from vault.NewManagerFromEnv.

View Source
var ErrBootstrapCanceled = errors.New("bootstrap canceled by user")

ErrBootstrapCanceled is returned when user cancels bootstrap operation.

View Source
var ErrNoSafetyCopy = errors.New(
	"a recycle destroys the original VM's boot disk. Name a backup storage with --archive-storage, " +
		"or pass --safety-copy-taken to confirm you already have one")

ErrNoSafetyCopy is returned when a recycle would run with nothing protecting the OS disk it is about to destroy.

View Source
var (
	ErrNoSuitableSubnetFoundForBastion = errors.New("no suitable subnet found for bastion; ensure subnets phase created at least one subnet")
)

Bootstrap errors.

View Source
var ErrPublicIPCreateFailed = errors.New("public IP creation failed")

ErrPublicIPCreateFailed reports addresses that could not be allocated after every retry. The bootstrap runner aborts on it rather than reporting a completed step for work that did not happen.

Functions

func BastionProxyCommand

func BastionProxyCommand(keyPath, user, bastionHost string, batchMode bool) (string, error)

BastionProxyCommand returns the ssh ProxyCommand that reaches a host behind the bloc bastion. It relays through the bastion with -W and gives the jump hop the bastion's own host-key options, accept-new against the real known_hosts, which `-o ProxyJump=…` would leave to the user's ssh config (see artifactsSSHArgs). A bastion seen for the first time is recorded, and one whose key has changed is refused. The jump hop authenticates with the same key and login user as the final hop. ssh runs the ProxyCommand through a shell, so keyPath, user, and bastionHost are shell-quoted like every other value in it. The inner ssh reads the user's ssh config as usual, so settings such as a port for the bastion still apply.

An empty keyPath leaves authentication to the operator's own ssh setup. The jump hop then drops -i and IdentitiesOnly, so the agent, the default keys, and the ssh config apply, while the host-key options stay exactly as they are with a key. It keeps BatchMode=yes only when batchMode is set, which callers do for any run that is not interactive, so a passphrase or password prompt can reach a person but never stalls a script. With a key the jump hop is always in batch mode and batchMode is ignored.

It returns an error only when the bastion's host key options cannot be built (see ssh.BastionHostKeyOptions).

func CIDRFirstIP

func CIDRFirstIP(cidr string) string

CIDRFirstIP returns the first IP address in a CIDR block. Exported for testing and utility use.

func CIDRGatewayIP

func CIDRGatewayIP(parentCIDR string) string

CIDRGatewayIP returns the gateway IP for a CIDR block. Exported for testing and utility use.

func CIDRLastUsableIP

func CIDRLastUsableIP(cidr string) string

CIDRLastUsableIP returns the last usable IP address in a CIDR block. Exported for testing and utility use.

func CalculateIPFromCIDR

func CalculateIPFromCIDR(cidr string, offset int) (string, error)

CalculateIPFromCIDR calculates an IP address from CIDR and offset. This matches the Perl implementation's cidrhost() function. Example: CalculateIPFromCIDR("10.0.0.0/24", 3) returns "10.0.0.3".

func DefaultSecurityGroupRules

func DefaultSecurityGroupRules(cfg *config.Config) map[string][]*cpi.SecurityRule

DefaultSecurityGroupRules returns the rule definitions for every default security group, keyed by short group name (e.g. "bastion"), derived from cfg exactly as bootstrap derives them. `ocfp configure` uses this to reconcile existing groups after config changes (e.g. allowed_ingress_ips) without re-running bootstrap.

func ErrBastionSecurityGroupNotFound

func ErrBastionSecurityGroupNotFound(sgName string) error

ErrBastionSecurityGroupNotFound returns an error when the bastion security group cannot be found.

func ErrBastionSubnetNotFound

func ErrBastionSubnetNotFound(bastionSubnet string) error

ErrBastionSubnetNotFound returns an error when the specified bastion subnet cannot be found.

func ErrBucketCreationErrors

func ErrBucketCreationErrors(errs []error) error

ErrBucketCreationErrors returns an error wrapping multiple bucket creation failures.

func ErrInvalidCIDRTypeForResource

func ErrInvalidCIDRTypeForResource(resourceName string) error

ErrInvalidCIDRTypeForResource returns an error for an invalid CIDR type on a resource.

func ErrInvalidCIDRTypeForSubnet

func ErrInvalidCIDRTypeForSubnet(subnetName string) error

ErrInvalidCIDRTypeForSubnet returns an error for an invalid CIDR type on a subnet.

func ErrInvalidNetworkID

func ErrInvalidNetworkID(networkID interface{}) error

ErrInvalidNetworkID returns an error for an invalid network identifier.

func ErrInvalidNetworkIDInState

func ErrInvalidNetworkIDInState(networkID interface{}) error

ErrInvalidNetworkIDInState returns an error for an invalid network_id value found in state.

func ErrInvalidSGBastionIDInState

func ErrInvalidSGBastionIDInState(sgID interface{}) error

ErrInvalidSGBastionIDInState returns an error for an invalid sg_bastion_id value found in state.

func FormatMetadataForDisplay

func FormatMetadataForDisplay(tags map[string]string) string

FormatMetadataForDisplay formats metadata tags for display in tables. Returns a compact string representation: "key1=val1, key2=val2". FormatMetadataForDisplay formats metadata tags for display in tables. Returns a compact string representation: "key1=val1, key2=val2". Note: Requires strict metadata format with hyphenated keys (managed-by, created-at). Resources without proper metadata will not be displayed.

func IsSubnetWithinParent

func IsSubnetWithinParent(parentCIDR, childCIDR string) bool

IsSubnetWithinParent validates that a child subnet CIDR is completely contained within the parent network CIDR. This ensures carved subnets don't overflow the parent network boundaries. Exported for testing and validation use.

func RulesMatch

func RulesMatch(r1, r2 *cpi.SecurityRule) bool

RulesMatch reports whether the current rule r1 satisfies the desired rule r2. Direction, protocol, and remote address are compared in normalized form, so a rule read back from a provider ("in", "TCP", a bare IP) matches the desired rule ("ingress", "tcp", a host CIDR). A current rule that does anything other than plainly accept the traffic (it drops, is disabled, or is narrowed by a destination, source port, macro, interface, or port list) never satisfies a desired rule, because the desired rule is an allow rule.

func SplitIntoN

func SplitIntoN(parentCIDR string, count int) []string

SplitIntoN splits a parent CIDR into N equal subnets. Exported for testing and utility use.

func SplitParentIntoTwo

func SplitParentIntoTwo(parentCIDR string) (string, string)

SplitParentIntoTwo splits a parent CIDR into two equal subnets.

func SplitToTargetPrefix

func SplitToTargetPrefix(parentCIDR string, targetPrefix, count int) []string

SplitToTargetPrefix splits a parent CIDR into `count` consecutive subnets of the requested `targetPrefix` length, walking the address space in fixed-size strides anchored at the parent's base address.

Returns nil when the parent cannot accommodate count*2^(targetPrefix-parentPrefix) addresses, when the target prefix is not strictly longer than the parent's, or when any input is malformed. This is the semantic backbone of the PVE /22 carve: parent 10.64.64.0/18 → /22 × 4 yields [10.64.64.0/22, 10.64.68.0/22, 10.64.72.0/22, 10.64.76.0/22].

Types

type Archiver

type Archiver interface {
	ArchiveInstance(ctx context.Context, instanceID, storage string) error
}

Archiver is the optional capability of taking a backup that survives the VM being destroyed.

It is optional because a snapshot is universal and an archive is not: on Proxmox it is a vzdump to a backup-capable storage, which has no equivalent on every provider. A provider that cannot do it says so rather than pretending the safety copy exists.

type BastionRecycleCluster

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

BastionRecycleCluster adapts the bootstrap manager to recycle.Cluster.

It lives here rather than in the recycle package so it can reuse the bastion build path that already knows how to resolve the image, the flavor, the subnet, the static address, and the SMBIOS payload. Duplicating that in a second place is how the replacement quietly stops matching what a fresh bootstrap produces.

func NewBastionRecycleCluster

func NewBastionRecycleCluster(mgr *Manager, archiveStorage string) *BastionRecycleCluster

NewBastionRecycleCluster returns a recycle.Cluster for this bloc's bastion.

func (*BastionRecycleCluster) AdoptReplacement

func (c *BastionRecycleCluster) AdoptReplacement(ctx context.Context) error

AdoptReplacement renames the replacement, rewrites the state entry, and starts it.

func (*BastionRecycleCluster) Archive

func (c *BastionRecycleCluster) Archive(ctx context.Context) error

Archive takes a copy that survives the VM being destroyed.

func (*BastionRecycleCluster) BuildReplacement

func (c *BastionRecycleCluster) BuildReplacement(ctx context.Context) error

BuildReplacement creates the replacement under the transient name, stopped.

It goes through the same bastion build path a fresh bootstrap uses, so the replacement matches what a new bloc would get rather than drifting from it.

func (*BastionRecycleCluster) ClearJournal

func (c *BastionRecycleCluster) ClearJournal(_ context.Context) error

ClearJournal removes the progress record after a successful run.

func (*BastionRecycleCluster) DeleteReplacement

func (c *BastionRecycleCluster) DeleteReplacement(ctx context.Context) error

DeleteReplacement removes the replacement. This is a compensation.

func (*BastionRecycleCluster) HandOverDisk

func (c *BastionRecycleCluster) HandOverDisk(ctx context.Context) error

HandOverDisk moves the data disk from the original to the replacement.

func (*BastionRecycleCluster) LoadJournal

func (c *BastionRecycleCluster) LoadJournal(_ context.Context) (*recycle.Journal, error)

LoadJournal reads a recycle in progress, or nil when there is none.

func (*BastionRecycleCluster) Observe

Observe reports the three facts that place an interrupted run.

func (*BastionRecycleCluster) Provision

func (c *BastionRecycleCluster) Provision(_ context.Context) error

Provision runs the role's provisioning. The bastion's is `ocfp bastion init`, driven over SSH from the workstation, which the recycle command invokes separately so its long output is not buried inside a phase.

func (*BastionRecycleCluster) RetireOriginal

func (c *BastionRecycleCluster) RetireOriginal(ctx context.Context) error

RetireOriginal destroys the VM being replaced. Past this, nothing can be undone.

func (*BastionRecycleCluster) ReturnDisk

func (c *BastionRecycleCluster) ReturnDisk(ctx context.Context) error

ReturnDisk moves the data disk back. This is a compensation.

func (*BastionRecycleCluster) SaveJournal

func (c *BastionRecycleCluster) SaveJournal(_ context.Context, j *recycle.Journal) error

SaveJournal writes the recycle's progress into the bloc state file.

func (*BastionRecycleCluster) Snapshot

func (c *BastionRecycleCluster) Snapshot(ctx context.Context) error

Snapshot takes the recycle's safety copy.

It deliberately does NOT take a VM snapshot, despite the name the engine gives the phase. A snapshot pins every disk in the VM's config, and Proxmox then refuses to move or detach any of them, so snapshotting here would deadlock the handover two phases later. recycleSafetyCopyRationale explains it at length, and a test pins the reasoning.

The copy that works is a vzdump archive: it pins nothing, it survives the VM being destroyed, and with the data disk marked backup=0 it captures exactly the half that is about to be thrown away.

func (*BastionRecycleCluster) StartOriginal

func (c *BastionRecycleCluster) StartOriginal(ctx context.Context) error

StartOriginal restarts the VM the quiesce stopped. This is a compensation, run only on abort.

func (*BastionRecycleCluster) StopOriginal

func (c *BastionRecycleCluster) StopOriginal(ctx context.Context) error

StopOriginal stops the VM being replaced. Proxmox requires this before a disk can be reassigned out of it.

func (*BastionRecycleCluster) Verify

func (c *BastionRecycleCluster) Verify(ctx context.Context) error

Verify checks the replacement is healthy enough to hand back.

func (*BastionRecycleCluster) WithSafetyCopyTaken

func (c *BastionRecycleCluster) WithSafetyCopyTaken(taken bool) *BastionRecycleCluster

WithSafetyCopyTaken records that the operator already holds a copy of the OS disk, so the recycle need not take one.

type Manager

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

Manager handles the bootstrap process.

func NewManager

func NewManager(cfg *config.Config, provider cpi.Provider, stateManager *state.Manager, opts *Options) *Manager

NewManager creates a new bootstrap manager.

func (*Manager) ConfigureIngressDNS

func (m *Manager) ConfigureIngressDNS(ctx context.Context) error

ConfigureIngressDNS points <base> and *.<base> A records at the bastion's tailnet IP when the resolved ingress provider is tailscale. Runs after the bastion exists (it must have joined the tailnet). Soft-skips on any missing prerequisite — ingress must never fail bootstrap.

func (*Manager) CreateArtifacts

func (m *Manager) CreateArtifacts(ctx context.Context) error

CreateArtifacts provisions the ocfp-artifacts VM when the bloc opts into Artifacts.Enabled. The step performs:

  1. Resolve networking from the bastion subnet (same infra subnet).
  2. Resolve credentials + TLS material.
  3. Render cloud-init.
  4. Create the VM and preserve any returned handle on failure.
  5. Create + attach the data volume; retain both resources for recovery.
  6. Record the VM and data volume in state and save it to disk, before any long wait, so a killed run never leaves a VM that teardown cannot see.
  7. Deliver provisioning and poll the RustFS S3 endpoint until ready.
  8. Create the configured buckets directly via the artifacts endpoint.

The step is idempotent: if state already records an artifacts VM and the readiness probe succeeds, it returns nil without touching anything.

func (*Manager) CreateBastion

func (m *Manager) CreateBastion(ctx context.Context) error

CreateBastion creates the bastion host.

func (*Manager) CreateBuckets

func (m *Manager) CreateBuckets(ctx context.Context) error

CreateBuckets creates the required storage buckets.

func (*Manager) CreateCloudflareTunnel

func (m *Manager) CreateCloudflareTunnel(ctx context.Context) error

CreateCloudflareTunnel ensures the per-bloc tunnel exists, pushes ingress, upserts the wildcard CNAMEs, persists the tunnel id/token to vault, and stashes the connector token on the Manager for the bastion SMBIOS payload. No-op (soft) when cloudflare is disabled or the API token is unavailable.

func (*Manager) CreateNetwork

func (m *Manager) CreateNetwork(ctx context.Context) error

CreateNetwork creates the network/VPC.

func (*Manager) CreatePublicIPs

func (m *Manager) CreatePublicIPs(ctx context.Context) error

CreatePublicIPs creates public IPs for the bootstrap environment (exported for testing).

func (*Manager) CreateSecurityGroups

func (m *Manager) CreateSecurityGroups(ctx context.Context) error

CreateSecurityGroups creates all default security groups (exported for testing).

func (*Manager) CreateSubnets

func (m *Manager) CreateSubnets(ctx context.Context) error

CreateSubnets creates the network subnets.

func (*Manager) EnsureBastionDataVolume

func (m *Manager) EnsureBastionDataVolume(ctx context.Context) error

EnsureBastionDataVolume creates and attaches the bastion's persistent data disk, or re-attaches the existing one.

This is a convergence pass rather than a create, and it is a separate bootstrap step rather than a tail on CreateBastion for one reason: CreateBastion returns early the moment a bastion already exists, which is the ordinary case on every re-run and on the rebuild flow this disk exists to serve. Anything bolted onto the end of that function would never run when the disk most needs re-attaching.

func (*Manager) EnsureBastionGuestOptions

func (m *Manager) EnsureBastionGuestOptions(ctx context.Context) error

EnsureBastionGuestOptions converges the bastion's provider-level options.

It is a bootstrap step of its own for the same reason the data disk is: CreateBastion returns early whenever a bastion already exists, which is the ordinary case on every re-run, so anything bolted onto the end of that function would never reach the bastions that need it most.

func (*Manager) Execute

func (m *Manager) Execute(ctx context.Context) error

Execute executes the bootstrap process.

func (*Manager) NativeRecycle

func (m *Manager) NativeRecycle() bool

NativeRecycle reports whether this manager uses the native cloud runner.

func (*Manager) SetSafe

func (m *Manager) SetSafe(safe vault.SafeInterface)

SetSafe wires a vault Safe client into the bootstrap manager. When set, the artifacts step calls ArtifactsWriter.WriteArtifacts to populate blobstore vault paths. When unset, bootstrap proceeds without writing vault (a warning is printed) so bare-cluster bootstraps without vault still succeed.

func (*Manager) StateManager

func (m *Manager) StateManager() *state.Manager

StateManager returns the state manager.

type MetadataManager

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

MetadataManager handles resource metadata generation and management.

func NewMetadataManager

func NewMetadataManager(blocName string) *MetadataManager

NewMetadataManager creates a new metadata manager.

func (*MetadataManager) BuildBaseLabels

func (m *MetadataManager) BuildBaseLabels() map[string]string

BuildBaseLabels is an alias for BuildBaseTags to support STACKIT's label terminology.

func (*MetadataManager) BuildBaseTags

func (m *MetadataManager) BuildBaseTags() map[string]string

BuildBaseTags generates the core metadata tags for all resources. Returns a map with bloc, managed-by, created-by, created-at, and updated-at fields.

func (*MetadataManager) MergeTags

func (m *MetadataManager) MergeTags(customTags map[string]string) map[string]string

MergeTags combines base metadata tags with custom tags. Custom tags take precedence over base tags if there are conflicts.

func (*MetadataManager) UpdateTimestamp

func (m *MetadataManager) UpdateTimestamp(tags map[string]string) map[string]string

UpdateTimestamp updates the updated-at timestamp in the provided tags. Returns a new map with the updated timestamp.

type NativeBastionRecycle

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

NativeBastionRecycle replaces only the boot disk of a cloud bastion.

func NewNativeBastionRecycle

func NewNativeBastionRecycle(mgr *Manager) (*NativeBastionRecycle, error)

func (*NativeBastionRecycle) Complete

func (*NativeBastionRecycle) DeleteReplacement

func (c *NativeBastionRecycle) DeleteReplacement(ctx context.Context, j *recycle.NativeJournal) error

func (*NativeBastionRecycle) Load

func (*NativeBastionRecycle) Plan

func (*NativeBastionRecycle) Prepare

func (*NativeBastionRecycle) Restore

func (*NativeBastionRecycle) Retire

func (*NativeBastionRecycle) Run

func (c *NativeBastionRecycle) Run(ctx context.Context, abort, pause bool) error

Run locks before reloading authoritative state, preventing concurrent recycle mutations.

func (*NativeBastionRecycle) Save

func (*NativeBastionRecycle) Snapshot

func (*NativeBastionRecycle) Start

func (*NativeBastionRecycle) Stop

func (*NativeBastionRecycle) Switch

func (*NativeBastionRecycle) Verify

type Options

type Options struct {
	BlocName       string
	Provider       string
	Region         string
	Force          bool
	Yes            bool
	DryRun         bool
	All            bool
	Bastion        bool
	Artifacts      bool
	Servers        bool
	Volumes        bool
	Snapshots      bool
	Buckets        bool
	SecurityGroups bool
	Network        bool
	PublicIPs      bool
	KeyPairs       bool
	Output         string
	Timeout        time.Duration
}

Options represents bootstrap options.

Jump to

Keyboard shortcuts

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