provision

package
v1.5.8 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 38 Imported by: 0

Documentation

Overview

Package provision creates and tears down cloud VMs at a provider (Hetzner, DigitalOcean, Azure, GCP) so a fresh node can join the fleet through the existing join-token enrollment flow, without an operator manually clicking through a cloud console first.

Index

Constants

View Source
const (
	CapabilityGranted = "granted"
	CapabilityMissing = "missing"
	CapabilityUnknown = "unknown"
)

Capability states. granted needs evidence, missing needs a 401 or 403 for that exact probe, unknown covers everything a safe read cannot prove.

View Source
const (
	EvidenceProbeOK    = "probe_ok"
	EvidenceProbe403   = "probe_403"
	EvidenceProbe404   = "probe_404"
	EvidenceLearnedOK  = "learned_ok"
	Evidence403Learned = "learned_403"
	EvidenceNotProbed  = "not_probed"
	EvidenceProbeError = "probe_error"
)

Evidence values say how a state was reached.

View Source
const (
	OracleScopeTenancy     = "tenancy"
	OracleScopeCompartment = "compartment"
	// OracleScopeAccessible is a partial tenancy view: only the compartments
	// the key may read, so hidden ones are not counted.
	OracleScopeAccessible = "accessible compartments"
)

Oracle usage scopes: which compartments the counts cover.

View Source
const (
	SectionOK           = "ok"
	SectionScopeMissing = "scope_missing"
	SectionUnavailable  = "unavailable"
)

Section states shared by discovery and spend answers. A scope_missing section always names the scope to add, never a bare 403.

View Source
const OracleNetworkNote = "network_read_missing"

OracleNetworkNote marks rows whose addresses are blank because the key lacks virtual-network read.

Variables

View Source
var (
	ErrInstanceNotFound    = errors.New("provision: instance not found")
	ErrInstanceConflict    = errors.New("provision: instance is in a state that does not allow this")
	ErrInstanceForbidden   = errors.New("provision: credential may not do this to the instance")
	ErrInstanceThrottled   = errors.New("provision: provider rate limit reached")
	ErrInstanceInvalid     = errors.New("provision: provider rejected the request")
	ErrInstanceUnsupported = errors.New("provision: this provider cannot do that")
	ErrInstanceReadOnly    = errors.New("provision: instance is not managed here and is read only")
	ErrInstanceCapacity    = errors.New("provision: provider has no capacity for this")
)

Instance error classes. Callers branch with errors.Is, never on provider text.

Functions

func AppendBootstrapScript

func AppendBootstrapScript(userData, agentName, body string) (string, error)

AppendBootstrapScript adds an operator-saved script to rendered cloud-init user data. It is written base64-encoded so no script byte can break the YAML, and runs last, after the built-in bootstrap.

func FailureDomain

func FailureDomain(provider, regionID string) (region, zone string)

FailureDomain maps the region id a server was created in to the region and zone labels stored on its node. Providers whose location is a single datacenter (hetzner, digitalocean) report it as both; gcp ids are zones.

func IsOracleA1Shape

func IsOracleA1Shape(shape string) bool

IsOracleA1Shape reports an Ampere A1 shape name.

func IsOracleE2MicroShape

func IsOracleE2MicroShape(shape string) bool

IsOracleE2MicroShape reports the AMD micro shape name.

func NewAzureTokenSource

func NewAzureTokenSource(credentialJSON, scope, loginBase string) (oauth2.TokenSource, error)

NewAzureTokenSource returns an AAD token source for scope from the same stored Azure credential EC2-style provisioning uses. loginBase overrides the login host and is empty outside tests.

func RenderCloudInit

func RenderCloudInit(p CloudInitParams) (string, error)

RenderCloudInit renders the user-data cloud-init runs on first boot: it installs Docker if missing (install.sh's own get.docker.com convention), then runs the agent as a systemd-managed container that joins the control plane with a one-time token. The join token and CA fingerprint go in a root-only env file, not container run args, so they don't show up in `ps`; they remain visible via `docker inspect`, a known limitation documented in docs/node-provisioning.md. The agent runs as root (--user 0:0, it needs docker.sock and NET_ADMIN), so the bind-mounted identity directory is created root-owned with mode 0700.

Types

type AWS

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

AWS implements Provisioner against the EC2 API (ec2API, aws_network.go), the same aws-sdk-go-v2 dependency internal/objectstore (S3) and internal/email (SES) already use. Unlike Hetzner/DigitalOcean's single bearer token and location-agnostic server id, an EC2 instance id is only valid in the region it was created in, so client builds a region-scoped client lazily per call rather than storing one fixed *ec2.Client.

func NewAWS

func NewAWS(creds AWSCredentials, shortName string) *AWS

NewAWS returns an AWS provisioner authenticating with creds. shortName namespaces the security group it creates (brand.Brand.ShortName; the product name never appears in source, so this is passed in, not looked up, the convention internal/network.WithShortName already establishes).

func NewAWSFromToken

func NewAWSFromToken(token, shortName string) (*AWS, error)

NewAWSFromToken builds an AWS provisioner from the JSON-encoded AWSCredentials a NodeProviderSecrets lookup returns.

func (*AWS) CreateServer

func (a *AWS) CreateServer(ctx context.Context, opts CreateOpts) (serverID, ipAddr string, err error)

CreateServer launches an EC2 instance: resolves the current Ubuntu AMI, the account's default VPC and subnet, ensures the shared no-inbound security group exists, and runs one instance with opts as its user-data.

func (*AWS) DeleteServer

func (a *AWS) DeleteServer(ctx context.Context, id string) error

DeleteServer terminates the EC2 instance. The shared security group ensureSecurityGroup creates or reuses is never deleted here: it's shared across every AWS-provisioned node, not created fresh per instance, so a single DeleteServer call is never its sole owner and cannot safely tell whether other nodes still depend on it. A group ensureDedicatedSSHSecurityGroup created for this one instance (CreateOpts.AllowSSHInbound) is a different story: it's tagged as dedicated at creation, so cleanupDedicatedSecurityGroups can safely delete it once confirmed no other instance references it. No key pair is created either way (there is no SSH key input yet), so there is nothing to clean up there.

func (*AWS) GetServer

func (a *AWS) GetServer(ctx context.Context, id string) (ServerStatus, string, error)

GetServer calls EC2 DescribeInstances.

func (*AWS) ListRegions

func (a *AWS) ListRegions(ctx context.Context) ([]Region, error)

ListRegions calls EC2 DescribeRegions.

func (*AWS) ListResources

func (a *AWS) ListResources(ctx context.Context) ([]ProviderResource, error)

ListResources lists the instances in the credentials' default region so the shared discovery endpoint works for AWS. Read-only.

func (*AWS) ListServers

func (a *AWS) ListServers(ctx context.Context, region string) ([]ProviderResource, error)

ListServers pages through DescribeInstances for region (the credentials' default when empty) and keeps running and stopped instances only, so terminated ones never show up as import candidates. IDs use the same region/instance form GetServer decodes, so enrollment matching lines up.

func (*AWS) ListSizes

func (a *AWS) ListSizes(_ context.Context, _ string) ([]Size, error)

ListSizes returns awsCuratedSizes: a static list, not a live API call (unlike Hetzner/DigitalOcean, EC2's own catalog is too large to be a useful picker, see awsCuratedSizes). region is accepted to satisfy Provisioner but unused: every listed type is available in essentially every commercial AWS region.

func (*AWS) PreflightCreate

func (a *AWS) PreflightCreate(ctx context.Context, opts CreateOpts) error

PreflightCreate runs the guard alone so callers can refuse with a 4xx before queueing work.

func (*AWS) SetCreateGuard

func (a *AWS) SetCreateGuard(g EC2CreateGuard)

SetCreateGuard injects the mandatory create guard; without one every create is refused.

type AWSCredentials

type AWSCredentials struct {
	AccessKeyID     string `json:"access_key_id,omitempty"`
	SecretAccessKey string `json:"secret_access_key,omitempty"`
	SessionToken    string `json:"session_token,omitempty"`
	Region          string `json:"region,omitempty"`
	// RoleARN, when set, is assumed via STS AssumeRole on top of
	// whichever base credentials resolve below: the base credentials
	// then only need sts:AssumeRole on this one ARN, not direct EC2
	// permissions, matching least-privilege IAM practice.
	RoleARN string `json:"role_arn,omitempty"`
	// UseAmbientCredentials, with AccessKeyID/SecretAccessKey both
	// empty, resolves this control plane's own AWS identity (env vars,
	// shared config, or an EC2 instance profile) instead of a stored
	// static key: only meaningful when the control plane itself runs on
	// AWS. Full AssumeRoleWithWebIdentity (OIDC federation, the way
	// GitHub Actions authenticates to AWS) is not implemented: it needs
	// this control plane to be its own trusted OIDC token issuer, which
	// does not exist. RoleARN plus a static key, or plus this ambient
	// chain, are the two supported ways to avoid a long-lived key with
	// direct EC2 permissions.
	UseAmbientCredentials bool `json:"use_ambient_credentials,omitempty"`
	// ExternalID is presented when assuming RoleARN, for roles that trust an account by external id.
	ExternalID string `json:"external_id,omitempty"`
}

AWSCredentials is the JSON shape node-provider/aws's stored credential value holds under NodeProviderTokenEnvKey (store.NodeProviderSecretsKey): EC2 has no single bearer token the way Hetzner and DigitalOcean do, so that envKey carries this struct JSON-encoded instead of a raw string.

func ParseAWSCredentials

func ParseAWSCredentials(token string) (AWSCredentials, error)

ParseAWSCredentials decodes and validates the JSON a node-provider "aws" secret holds, so other packages reuse the same identity modes.

func (AWSCredentials) CredentialsProvider

func (c AWSCredentials) CredentialsProvider(ctx context.Context, region string) (aws.CredentialsProvider, error)

CredentialsProvider resolves static, ambient or assumed-role credentials for region, the same chain EC2 provisioning uses.

func (AWSCredentials) DefaultRegion

func (c AWSCredentials) DefaultRegion() string

DefaultRegion is the stored region, or the package default.

type AWSInstanceSettings

type AWSInstanceSettings struct {
	// TagPrefix namespaces the ownership tags, derived from the brand short name when empty.
	TagPrefix    string
	PollInterval time.Duration
	WaitTimeout  time.Duration
	// AllowedRegions limits every call; empty means any region.
	AllowedRegions []string
}

AWSInstanceSettings are the tunables a settings slice can feed live.

type AWSInstances

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

AWSInstances implements InstanceManager over EC2.

func NewAWSInstances

func NewAWSInstances(creds AWSCredentials, shortName string, s AWSInstanceSettings) *AWSInstances

NewAWSInstances builds the manager; the region comes from the account config.

func (*AWSInstances) DescribeInstance

func (a *AWSInstances) DescribeInstance(ctx context.Context, id string) (InstanceDetail, error)

DescribeInstance reads the instance with its type specs and boot volume size.

func (*AWSInstances) InstanceAction

func (a *AWSInstances) InstanceAction(ctx context.Context, id string, kind InstanceActionKind) error

InstanceAction maps a power action to EC2. Stop forces, soft_stop is the graceful default, soft_reboot is RebootInstances; hard reboot is unsupported.

func (*AWSInstances) InstanceCapabilities

func (a *AWSInstances) InstanceCapabilities() CapabilityMatrix

InstanceCapabilities lists what EC2 can do. EC2 has no hard reboot, and its stop is graceful by default, so stop forces and soft_stop does not.

func (*AWSInstances) InstanceEvents

func (a *AWSInstances) InstanceEvents(ctx context.Context, id string, since time.Time) ([]InstanceEvent, error)

InstanceEvents returns scheduled events from DescribeInstanceStatus.

func (*AWSInstances) ListInstanceTypes

func (a *AWSInstances) ListInstanceTypes(ctx context.Context, region, arch string) ([]Size, error)

ListInstanceTypes returns the types the API offers in a region, optionally limited to one CPU architecture. Nothing is hardcoded.

func (*AWSInstances) ListInstances

func (a *AWSInstances) ListInstances(ctx context.Context, scope InstanceScope) ([]Instance, error)

ListInstances pages through DescribeInstances, hiding terminated instances. Instances without the ownership tags are returned read only.

func (*AWSInstances) ResizeInstance

func (a *AWSInstances) ResizeInstance(ctx context.Context, id string, spec ResizeSpec) error

ResizeInstance changes the instance type. Steps: validate, stop if running, wait stopped, modify, start only if it was running. If the modify fails after our own stop, a start is attempted so the instance is not left down.

func (*AWSInstances) ResizeQuota

func (a *AWSInstances) ResizeQuota(ctx context.Context, id, newType string) (limit, projected float64, known bool, err error)

ResizeQuota says whether the vCPU quota in the instance's region fits the new type. known is false when the quota could not be read, which callers treat as no signal.

func (*AWSInstances) SetInstanceTags

func (a *AWSInstances) SetInstanceTags(ctx context.Context, id string, tags map[string]string) error

SetInstanceTags upserts tags and deletes keys given an empty value. The ownership and provider-reserved keys are refused so a user cannot reclaim or release an instance through this call.

func (*AWSInstances) TerminateInstance

func (a *AWSInstances) TerminateInstance(ctx context.Context, id string, keepBootVolume bool) error

TerminateInstance sets the root volume's DeleteOnTermination to match keepBootVolume when it differs, then terminates.

type Azure

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

Azure implements Provisioner against the Azure Resource Manager REST API (https://learn.microsoft.com/en-us/rest/api/compute/), OAuth2 client-credentials auth, no SDK. Unlike Hetzner/DigitalOcean's static bearer token, every request needs a fresh access token: httpClient's tokenFunc seam (httpclient.go) resolves one from ts on each call.

func NewAzure

func NewAzure(credentialJSON string) (*Azure, error)

NewAzure returns an Azure provisioner authenticating with credentialJSON (see azureCredential): a client secret by default, or workload identity federation when credentialJSON sets federated_token_file instead.

func (*Azure) CreateServer

func (a *Azure) CreateServer(ctx context.Context, opts CreateOpts) (serverID, ipAddr string, err error)

CreateServer provisions a resource group (idempotent, never deleted), a shared per-region VNet/subnet (idempotent, never deleted), then a public IP, NIC and virtual machine unique to this server. No network security group is created: a Standard SKU public IP is closed to inbound traffic by default unless an NSG explicitly allows it, so this matches the "no inbound ports" default the other providers get from their own platform defaults.

func (*Azure) DeleteServer

func (a *Azure) DeleteServer(ctx context.Context, id string) error

DeleteServer deletes only the virtual machine. Its NIC, public IP and OS disk were all created with deleteOption "Delete" (createVM, createNIC, createPublicIP), which Azure documents as cascading their deletion from this one call; the shared VNet/subnet is left in place for other servers in the same region. This cascade was not verified against a real Azure subscription, only against fakes (see azure_test.go).

func (*Azure) GetServer

func (a *Azure) GetServer(ctx context.Context, id string) (ServerStatus, string, error)

GetServer calls GET .../virtualMachines/{id} plus a second call for the public IP's address, id being the VM name (resourceGroup and subscriptionID are fixed per Azure instance, not part of id).

func (*Azure) ListRegions

func (a *Azure) ListRegions(ctx context.Context) ([]Region, error)

ListRegions calls GET /subscriptions/{sub}/locations, keeping only physical regions (Azure also lists "Logical" entries like paired DR regions that aren't valid CreateServer targets).

func (*Azure) ListSizes

func (a *Azure) ListSizes(ctx context.Context, region string) ([]Size, error)

ListSizes calls GET .../locations/{region}/vmSizes. Azure's retail pricing isn't part of this API, so every returned Size has an empty PriceMonthly, the same "not returned" case DigitalOcean/Hetzner's own Size doc comment already covers.

type BillingReader

type BillingReader interface {
	ReadBilling(ctx context.Context) (SpendBalance, SpendInvoice)
}

BillingReader is optional on a provisioner: it reads the billed amounts the provider exposes. Each section carries its own state so a missing scope on one does not hide the other.

type Capability

type Capability struct {
	ID         string    `json:"id"`
	Group      string    `json:"group"`
	State      string    `json:"state"`
	Evidence   string    `json:"evidence"`
	Needs      string    `json:"needs"`
	UsedBy     []string  `json:"used_by"`
	ObservedAt time.Time `json:"observed_at"`
}

Capability is one provider permission as the control plane understands it.

type CapabilityMatrix

type CapabilityMatrix map[InstanceVerb]bool

CapabilityMatrix reports which verbs a driver supports.

func InstanceCapabilities

func InstanceCapabilities(m InstanceManager) CapabilityMatrix

InstanceCapabilities returns the manager's matrix. A manager that does not report gets the full set, so an old driver never loses actions by accident.

func NewCapabilityMatrix

func NewCapabilityMatrix(verbs ...InstanceVerb) CapabilityMatrix

NewCapabilityMatrix builds a matrix with exactly the listed verbs on.

func (CapabilityMatrix) Supports

func (c CapabilityMatrix) Supports(v InstanceVerb) bool

Supports reports whether the verb is on; unknown verbs are off.

func (CapabilityMatrix) SupportsAction

func (c CapabilityMatrix) SupportsAction(k InstanceActionKind) bool

SupportsAction reports whether the power action is on.

func (CapabilityMatrix) Verbs

func (c CapabilityMatrix) Verbs() []InstanceVerb

Verbs lists the supported verbs in a stable order.

type CapabilityProber

type CapabilityProber interface {
	ProbeCapabilities(ctx context.Context, concurrency int) ProviderCapabilities
}

CapabilityProber is optional on a provisioner: only providers with a safe read-only way to check a credential implement it.

type CloudInitParams

type CloudInitParams struct {
	ControlPlaneAddr string
	JoinToken        string
	CAFingerprint    string
	NodeName         string
	// AgentName is the brand-derived agent identifier (Brand.AgentName()), used for the unit, env file, data dir and default image.
	AgentName string
	// DisplayName is the product name shown in the unit description (Brand.Name).
	DisplayName string
	// AgentImage overrides the default repo:tag, for an operator who
	// mirrors the image elsewhere. Empty uses the default repo at
	// AgentVersion.
	AgentImage   string
	AgentVersion string
	// MeshEnabled gives the agent container the TUN device and NET_ADMIN
	// its WireGuard device needs.
	MeshEnabled bool
	// RegistryMirrorPrefix is put in front of the default image's registry host; it never rewrites an explicit AgentImage.
	RegistryMirrorPrefix string
	// DockerMirror picks the get.docker.com mirror (Aliyun or AzureChinaCloud); empty falls back to LEVELRAIL_DOCKER_MIRROR.
	DockerMirror string
}

CloudInitParams is everything RenderCloudInit needs to produce a first-boot script for a freshly created server.

type CreateOpts

type CreateOpts struct {
	Region string
	Size   string
	Name   string
	// UserData is the cloud-init script run on first boot.
	UserData string
	// ProvisionID is the provision row id; drivers that support it use it as
	// an idempotency token and a tag so a retried create cannot leak a server.
	ProvisionID string
	// AllowSSHInbound opts into an inbound rule for TCP 22, off by
	// default to match this platform's "no inbound ports needed" node
	// architecture (CLAUDE.md 4.3): the agent always dials out. Only AWS
	// currently acts on this; other providers ignore it, the same way
	// AWS.ListSizes ignores the region parameter other providers use.
	AllowSSHInbound bool
}

CreateOpts describes the server CreateServer should provision.

type DigitalOcean

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

DigitalOcean implements Provisioner against the DigitalOcean API v2 (https://docs.digitalocean.com/reference/api/), token auth, no SDK.

func NewDigitalOcean

func NewDigitalOcean(token string) *DigitalOcean

NewDigitalOcean returns a DigitalOcean provisioner authenticating with token.

func (*DigitalOcean) CreateServer

func (d *DigitalOcean) CreateServer(ctx context.Context, opts CreateOpts) (serverID, ipAddr string, err error)

CreateServer calls POST /v2/droplets.

func (*DigitalOcean) DeleteServer

func (d *DigitalOcean) DeleteServer(ctx context.Context, id string) error

DeleteServer calls DELETE /v2/droplets/{id}.

func (*DigitalOcean) DescribeInstance

func (d *DigitalOcean) DescribeInstance(ctx context.Context, id string) (InstanceDetail, error)

DescribeInstance reads one droplet.

func (*DigitalOcean) GetServer

func (d *DigitalOcean) GetServer(ctx context.Context, id string) (ServerStatus, string, error)

GetServer calls GET /v2/droplets/{id}.

func (*DigitalOcean) InstanceAction

func (d *DigitalOcean) InstanceAction(ctx context.Context, id string, kind InstanceActionKind) error

InstanceAction runs one power action on a managed droplet.

func (*DigitalOcean) InstanceCapabilities

func (d *DigitalOcean) InstanceCapabilities() CapabilityMatrix

InstanceCapabilities lists what droplets support. Boot volume retention is off: a droplet disk cannot outlive the droplet.

func (*DigitalOcean) InstanceEvents

func (d *DigitalOcean) InstanceEvents(ctx context.Context, id string, since time.Time) ([]InstanceEvent, error)

InstanceEvents reads the droplet action history newer than since.

func (*DigitalOcean) ListInstances

func (d *DigitalOcean) ListInstances(ctx context.Context, scope InstanceScope) ([]Instance, error)

ListInstances lists droplets across every page, optionally of one region.

func (*DigitalOcean) ListRegions

func (d *DigitalOcean) ListRegions(ctx context.Context) ([]Region, error)

ListRegions calls GET /v2/regions, following every page.

func (*DigitalOcean) ListResources

func (d *DigitalOcean) ListResources(ctx context.Context) ([]ProviderResource, error)

ListResources calls GET /v2/droplets across every page and prices each droplet from the sizes list. A sizes failure only drops prices, a droplets failure is returned so the caller can map a 403 to the missing scope.

func (*DigitalOcean) ListSizes

func (d *DigitalOcean) ListSizes(ctx context.Context, region string) ([]Size, error)

ListSizes calls GET /v2/sizes, following every page. When region is non-empty, only sizes DigitalOcean lists as available in that region are returned.

func (*DigitalOcean) ProbeCapabilities

func (d *DigitalOcean) ProbeCapabilities(ctx context.Context, concurrency int) ProviderCapabilities

ProbeCapabilities runs one read-only GET per read capability, at most concurrency at once. A 401 or 403 is missing, a 2xx is granted, anything else (404, 5xx, network) stays unknown and never reads as missing.

func (*DigitalOcean) ReadBilling

func (d *DigitalOcean) ReadBilling(ctx context.Context) (SpendBalance, SpendInvoice)

ReadBilling calls GET /v2/customers/my/balance and /v2/customers/my/billing_history. Both are read-only and independent.

func (*DigitalOcean) ResizeInstance

func (d *DigitalOcean) ResizeInstance(ctx context.Context, id string, spec ResizeSpec) error

ResizeInstance changes the droplet size slug without growing the disk.

func (*DigitalOcean) SetInstanceTags

func (d *DigitalOcean) SetInstanceTags(ctx context.Context, id string, tags map[string]string) error

SetInstanceTags upserts tags as DO tag names and detaches the removed ones. A tag that belongs to no other resource is left in the account, never deleted.

func (*DigitalOcean) TerminateInstance

func (d *DigitalOcean) TerminateInstance(ctx context.Context, id string, keepBootVolume bool) error

TerminateInstance deletes the droplet. Keeping the disk is not possible.

type EC2CreateGuard

type EC2CreateGuard func(ctx context.Context, req EC2CreateRequest) (map[string]string, error)

EC2CreateGuard decides one EC2 create and returns the full tag set to apply. It returns a *GuardRefusal to refuse.

type EC2CreateRequest

type EC2CreateRequest struct {
	Region, InstanceType, Name, ProvisionID string
}

EC2CreateRequest is what the create guard sees before any AWS call.

type EnrolledNodeRef

type EnrolledNodeRef struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

EnrolledNodeRef points at the Levelrail node a discovered machine maps to.

type GCP

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

GCP implements Provisioner against the Compute Engine REST API (https://cloud.google.com/compute/docs/reference/rest/v1), a service account JSON key exchanged for an OAuth2 access token via JWT bearer auth, no SDK (golang.org/x/oauth2/google, not google.golang.org/api).

func NewGCP

func NewGCP(credentialJSON string) (*GCP, error)

NewGCP returns a GCP provisioner authenticating with credentialJSON, a service account key's raw JSON content. The project ID is read from the key itself, not a separate field.

func (*GCP) CreateServer

func (g *GCP) CreateServer(ctx context.Context, opts CreateOpts) (serverID, ipAddr string, err error)

CreateServer calls POST .../zones/{zone}/instances with an ephemeral external IP (no reserved address to clean up later) and an auto-deleting boot disk, so DeleteServer needs only the one instance delete call. The insert call is asynchronous at the operation level, but the instance resource itself exists as soon as this call returns, in PROVISIONING state; its IP isn't assigned yet, so ipAddr is always empty here, matching CreateOpts' own doc comment for a provider that assigns one later. serverID is "{zone}/{name}": unlike Azure's fixed per-account resource group, GCP's zone varies per server and every later call needs it, so it has to travel in the id.

func (*GCP) DeleteServer

func (g *GCP) DeleteServer(ctx context.Context, id string) error

DeleteServer calls DELETE .../zones/{zone}/instances/{name}. The boot disk (autoDelete: true) and the ephemeral external IP go with it; no separate cleanup call is needed.

func (*GCP) GetServer

func (g *GCP) GetServer(ctx context.Context, id string) (ServerStatus, string, error)

GetServer calls GET .../zones/{zone}/instances/{name}, id being the "{zone}/{name}" CreateServer returned.

func (*GCP) ListRegions

func (g *GCP) ListRegions(ctx context.Context) ([]Region, error)

ListRegions returns GCP zones (e.g. us-central1-a), not regions: Compute Engine places an instance in a zone, and CreateServer/ GetServer/DeleteServer all need that zone, so this interface's "region" maps to a GCE zone for this provider.

func (*GCP) ListSizes

func (g *GCP) ListSizes(ctx context.Context, zone string) ([]Size, error)

ListSizes calls GET .../zones/{zone}/machineTypes. Disk size is a separate resource in GCE, not part of a machine type, so every returned Size has Disk 0; CreateServer picks gcpBootDiskGB itself. GCP's own billing catalog is a separate API this package doesn't call, so PriceMonthly is always empty here too.

type GuardRefusal

type GuardRefusal struct{ Code, Message string }

GuardRefusal is a guard decision that stops a create before any cloud call.

func (*GuardRefusal) Error

func (e *GuardRefusal) Error() string

type Hetzner

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

Hetzner implements Provisioner against the Hetzner Cloud API (https://docs.hetzner.cloud), token auth, no SDK.

func NewHetzner

func NewHetzner(token string) *Hetzner

NewHetzner returns a Hetzner provisioner authenticating with token.

func (*Hetzner) CreateServer

func (h *Hetzner) CreateServer(ctx context.Context, opts CreateOpts) (serverID, ipAddr string, err error)

CreateServer calls POST /v1/servers.

func (*Hetzner) DeleteServer

func (h *Hetzner) DeleteServer(ctx context.Context, id string) error

DeleteServer calls DELETE /v1/servers/{id}.

func (*Hetzner) DescribeInstance

func (h *Hetzner) DescribeInstance(ctx context.Context, id string) (InstanceDetail, error)

DescribeInstance reads one server.

func (*Hetzner) GetServer

func (h *Hetzner) GetServer(ctx context.Context, id string) (ServerStatus, string, error)

GetServer calls GET /v1/servers/{id}.

func (*Hetzner) InstanceAction

func (h *Hetzner) InstanceAction(ctx context.Context, id string, kind InstanceActionKind) error

InstanceAction runs one power action on a managed server.

func (*Hetzner) InstanceCapabilities

func (h *Hetzner) InstanceCapabilities() CapabilityMatrix

InstanceCapabilities lists what Hetzner servers support. Boot volume retention is off: the root disk is part of the server.

func (*Hetzner) InstanceEvents

func (h *Hetzner) InstanceEvents(ctx context.Context, id string, since time.Time) ([]InstanceEvent, error)

InstanceEvents reads the server action history newer than since.

func (*Hetzner) ListInstances

func (h *Hetzner) ListInstances(ctx context.Context, scope InstanceScope) ([]Instance, error)

ListInstances lists servers across every page, optionally of one location.

func (*Hetzner) ListRegions

func (h *Hetzner) ListRegions(ctx context.Context) ([]Region, error)

ListRegions calls GET /v1/locations, following every page.

func (*Hetzner) ListSizes

func (h *Hetzner) ListSizes(ctx context.Context, region string) ([]Size, error)

ListSizes calls GET /v1/server_types, following every page. When region is non-empty, only server types priced in that location are returned (Hetzner's own signal for "available there"), with that location's own monthly price attached.

func (*Hetzner) ResizeInstance

func (h *Hetzner) ResizeInstance(ctx context.Context, id string, spec ResizeSpec) error

ResizeInstance changes the server type without upgrading the disk.

func (*Hetzner) SetInstanceTags

func (h *Hetzner) SetInstanceTags(ctx context.Context, id string, tags map[string]string) error

SetInstanceTags merges labels into the server; an empty value removes the key.

func (*Hetzner) TerminateInstance

func (h *Hetzner) TerminateInstance(ctx context.Context, id string, keepBootVolume bool) error

TerminateInstance deletes the server. Keeping the disk is not possible.

type Instance

type Instance struct {
	ID         string
	Name       string
	Region     string
	State      InstanceState
	RawState   string
	Shape      string
	OCPUs      float64
	MemoryGB   float64
	PublicIPv4 string
	// PrivateIPv4 is set on list rows by drivers that resolve it; detail has its own copy.
	PrivateIPv4 string
	// IPNote says why the addresses are empty when the caller may not read them.
	IPNote    string
	CreatedAt time.Time
	Tags      map[string]string
	// Managed is true when the instance carries this product's ownership tags.
	Managed bool
	// ReadOnly marks an instance the driver lists but refuses to change.
	ReadOnly bool
}

Instance is the neutral list row.

type InstanceActionKind

type InstanceActionKind string

InstanceActionKind is a power action every driver maps to its own verb.

const (
	InstanceActionStart      InstanceActionKind = "start"
	InstanceActionStop       InstanceActionKind = "stop"
	InstanceActionSoftStop   InstanceActionKind = "soft_stop"
	InstanceActionReboot     InstanceActionKind = "reboot"
	InstanceActionSoftReboot InstanceActionKind = "soft_reboot"
)

The power actions an InstanceManager may support. A driver lists the ones it can do in its CapabilityMatrix, the rest are hidden, never errors.

type InstanceCapabilityReporter

type InstanceCapabilityReporter interface {
	InstanceCapabilities() CapabilityMatrix
}

InstanceCapabilityReporter is implemented by managers that can say what they support.

type InstanceDetail

type InstanceDetail struct {
	Instance
	PrivateIPv4    string
	Zone           string
	ImageID        string
	BootVolumeGB   float64
	Project        string
	Environment    string
	ResizeAdvisory string
	// CompartmentID is set by drivers with compartments so callers can enforce scope.
	CompartmentID string
}

InstanceDetail adds what only the detail page needs.

type InstanceEvent

type InstanceEvent struct {
	Time    time.Time
	Kind    string
	Status  string
	Message string
}

InstanceEvent is one provider-side event or operation on an instance.

type InstanceManager

type InstanceManager interface {
	ListInstances(ctx context.Context, scope InstanceScope) ([]Instance, error)
	DescribeInstance(ctx context.Context, id string) (InstanceDetail, error)
	InstanceAction(ctx context.Context, id string, kind InstanceActionKind) error
	ResizeInstance(ctx context.Context, id string, spec ResizeSpec) error
	// SetInstanceTags upserts the given tags; an empty value removes the key.
	SetInstanceTags(ctx context.Context, id string, tags map[string]string) error
	TerminateInstance(ctx context.Context, id string, keepBootVolume bool) error
	InstanceEvents(ctx context.Context, id string, since time.Time) ([]InstanceEvent, error)
}

InstanceManager is optional: a driver that implements it gets the instance detail actions. It is deliberately separate from Provisioner so the other drivers stay untouched.

type InstanceScope

type InstanceScope struct {
	Region string
	// Compartment is only read by drivers that have compartments.
	Compartment string
}

InstanceScope narrows a listing. Empty fields mean the account default.

type InstanceState

type InstanceState string

InstanceState is the provider state folded into a small shared vocabulary.

const (
	InstanceStatePending     InstanceState = "pending"
	InstanceStateRunning     InstanceState = "running"
	InstanceStateStopping    InstanceState = "stopping"
	InstanceStateStopped     InstanceState = "stopped"
	InstanceStateTerminating InstanceState = "terminating"
	InstanceStateTerminated  InstanceState = "terminated"
	InstanceStateUnknown     InstanceState = "unknown"
)

Shared instance states. The raw provider value stays on Instance.RawState.

type InstanceVerb

type InstanceVerb string

InstanceVerb names one thing a driver may or may not do.

const (
	VerbList          InstanceVerb = "list"
	VerbDescribe      InstanceVerb = "describe"
	VerbStart         InstanceVerb = "start"
	VerbStop          InstanceVerb = "stop"
	VerbSoftStop      InstanceVerb = "soft_stop"
	VerbReboot        InstanceVerb = "reboot"
	VerbSoftReboot    InstanceVerb = "soft_reboot"
	VerbResize        InstanceVerb = "resize"
	VerbTags          InstanceVerb = "tags"
	VerbTerminate     InstanceVerb = "terminate"
	VerbKeepBootVol   InstanceVerb = "keep_boot_volume"
	VerbEvents        InstanceVerb = "events"
	VerbResizeByShape InstanceVerb = "resize_by_type"
)

Every verb the UI gates on. Adding a capability is one entry here plus the driver listing it.

type Oracle

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

Oracle provisions OCI Core instances over signed REST calls, no SDK.

func NewOracle

func NewOracle(cred OracleCredential, settings OracleSettings) (*Oracle, error)

NewOracle validates the credential and builds a driver for it.

func NewOracleWithEndpoints

func NewOracleWithEndpoints(cred OracleCredential, settings OracleSettings, iaasBase, identityBase string) (*Oracle, error)

NewOracleWithEndpoints points the driver at explicit plain HTTP base URLs. Only Go callers can reach it, so tests can use a local fake without a config switch that could redirect signed requests.

func (*Oracle) CreateServer

func (o *Oracle) CreateServer(ctx context.Context, opts CreateOpts) (string, string, error)

CreateServer launches one instance, trying each allowed availability domain once when OCI reports no host capacity. Any other error stops at once.

func (*Oracle) DeleteServer

func (o *Oracle) DeleteServer(ctx context.Context, id string) error

DeleteServer terminates the instance and its boot volume in the instance's own region. A 404 counts as deleted only when the OCID names that region or every subscribed region answered 404.

func (*Oracle) DescribeInstance

func (o *Oracle) DescribeInstance(ctx context.Context, id string) (InstanceDetail, error)

DescribeInstance reads state, shape, addresses, image and tags.

func (*Oracle) EffectiveRegion

func (o *Oracle) EffectiveRegion(region string) string

EffectiveRegion is the region a request with this region value acts in.

func (*Oracle) FindServerByTag

func (o *Oracle) FindServerByTag(ctx context.Context, region, tag string) (string, error)

FindServerByTag returns a live instance carrying the provision row id tag, so a create that failed without an id cannot leak a server.

func (*Oracle) GetServer

func (o *Oracle) GetServer(ctx context.Context, id string) (ServerStatus, string, error)

GetServer maps the instance state and, once it exists, looks up the public IP through its primary VNIC. It reads the instance's own region.

func (*Oracle) HomeRegion

func (o *Oracle) HomeRegion(ctx context.Context) (string, error)

HomeRegion returns the tenancy home region, where the free allowance lives.

func (*Oracle) InstanceAction

func (o *Oracle) InstanceAction(ctx context.Context, id string, kind InstanceActionKind) error

InstanceAction runs one power action through POST /instances/{id}?action=.

func (*Oracle) InstanceCapabilities

func (o *Oracle) InstanceCapabilities() CapabilityMatrix

InstanceCapabilities reports every verb: OCI has all five power actions.

func (*Oracle) InstanceEvents

func (o *Oracle) InstanceEvents(ctx context.Context, id string, since time.Time) ([]InstanceEvent, error)

InstanceEvents reads the compartment's Audit events and keeps the ones for this instance, since Core has no work request listing by resource. A 404 is an empty list.

func (*Oracle) ListInstances

func (o *Oracle) ListInstances(ctx context.Context, scope InstanceScope) ([]Instance, error)

ListInstances lists the non-terminated instances of one compartment and region.

func (*Oracle) ListRegions

func (o *Oracle) ListRegions(ctx context.Context) ([]Region, error)

ListRegions returns the regions the tenancy is subscribed to.

func (*Oracle) ListSizes

func (o *Oracle) ListSizes(ctx context.Context, region string) ([]Size, error)

ListSizes returns fixed shapes as listed and Flex shapes expanded into the configured presets, with the preset encoded in the size id. No price is returned because the compute API has none.

func (*Oracle) OracleUsage

func (o *Oracle) OracleUsage(ctx context.Context, region string) (OracleUsage, error)

OracleUsage counts A1 and micro instances across the tenancy when the key may read every compartment. The compartment-only fallback needs the AllowCompartmentScope setting and only follows a 403 or 404.

func (*Oracle) ResizeInstance

func (o *Oracle) ResizeInstance(ctx context.Context, id string, spec ResizeSpec) error

ResizeInstance changes OCPU and memory of a flexible shape through PUT /instances/{id}. Fixed shapes are refused before any change is sent.

func (*Oracle) SessionAuth

func (o *Oracle) SessionAuth() bool

SessionAuth reports a browser session login, which cannot create nodes.

func (*Oracle) SetInstanceTags

func (o *Oracle) SetInstanceTags(ctx context.Context, id string, tags map[string]string) error

SetInstanceTags merges into the freeform tags, since OCI replaces the whole map on update. The ownership label is never changed here.

func (*Oracle) TerminateInstance

func (o *Oracle) TerminateInstance(ctx context.Context, id string, keepBootVolume bool) error

TerminateInstance deletes the instance; preserveBootVolume follows keepBootVolume.

type OracleCredential

type OracleCredential struct {
	TenancyOCID     string
	UserOCID        string
	Fingerprint     string
	PrivateKeyPEM   string
	CompartmentOCID string
	// SubnetOCID is required until the network slice can create one.
	SubnetOCID string
	Region     string
	// SessionToken switches signing to the browser session scheme; UserOCID and Fingerprint are then unused.
	SessionToken string
}

OracleCredential is the API key material plus scope the driver needs.

type OracleSettings

type OracleSettings struct {
	FlexPresets         string // ocpus:memoryGB pairs, comma separated
	BootVolumeGB        int
	AvailabilityDomains []string // AD name suffixes, empty means all
	ImageOS             string
	ImageOSVersion      string
	// LabelKey prefixes the freeform tag that marks instances we launched.
	LabelKey string
	// AllowCompartmentScope lets the usage count fall back to the configured
	// compartment when the key cannot read the whole tenancy tree.
	AllowCompartmentScope bool
	// MaxBootVolumeGB refuses a create whose boot volume is larger; 0 is no cap.
	MaxBootVolumeGB int
}

OracleSettings are the tunables the later settings slice will feed live. Zero values fall back to the documented defaults.

type OracleUsage

type OracleUsage struct {
	A1OCPU     float64
	A1MemoryGB float64
	E2Micro    int
	// Scope says how wide the count was, so a refusal can state it.
	Scope string
}

OracleUsage is what existing non-terminated instances already hold, whether or not Levelrail created them.

type ProviderCapabilities

type ProviderCapabilities struct {
	Provider       string       `json:"provider"`
	AccountID      string       `json:"account_id"`
	Method         string       `json:"method"`
	CheckedAt      time.Time    `json:"checked_at"`
	Cached         bool         `json:"cached"`
	NextCheckAt    *time.Time   `json:"next_check_at,omitempty"`
	LiveCheckError string       `json:"live_check_error,omitempty"`
	Capabilities   []Capability `json:"capabilities"`
}

ProviderCapabilities is the provider-neutral result of a capability check.

type ProviderError

type ProviderError struct {
	Status int
	Body   string
	// contains filtered or unexported fields
}

ProviderError is a non-2xx response from a provider's API, carrying the HTTP status so callers (and tests) can distinguish "not found" from a generic failure without parsing each provider's own error body shape.

func (*ProviderError) Error

func (e *ProviderError) Error() string

type ProviderResource

type ProviderResource struct {
	ID                    string           `json:"id"`
	Name                  string           `json:"name"`
	Region                string           `json:"region"`
	Size                  string           `json:"size"`
	Status                string           `json:"status"`
	PublicIPv4            string           `json:"public_ipv4"`
	CreatedAt             time.Time        `json:"created_at"`
	Tags                  []string         `json:"tags"`
	EstimatedMonthlyPrice *float64         `json:"estimated_monthly_price"`
	Currency              string           `json:"currency"`
	ManagedByLevelrail    bool             `json:"managed_by_levelrail"`
	EnrolledNode          *EnrolledNodeRef `json:"enrolled_node"`
}

ProviderResource is one machine in a provider account, provider-neutral. ManagedByLevelrail and EnrolledNode are filled by the API layer, never by the provider adapter.

type Provisioner

type Provisioner interface {
	ListRegions(ctx context.Context) ([]Region, error)
	ListSizes(ctx context.Context, region string) ([]Size, error)
	// CreateServer returns the provider's own server id and, when the
	// provider assigns one immediately, its public IPv4 address (empty
	// until GetServer reports one, for providers that assign it later).
	CreateServer(ctx context.Context, opts CreateOpts) (serverID, ipAddr string, err error)
	GetServer(ctx context.Context, id string) (status ServerStatus, ipAddr string, err error)
	DeleteServer(ctx context.Context, id string) error
}

Provisioner creates and manages servers at a cloud provider. hetzner.go, digitalocean.go, azure.go and gcp.go are the real implementations; all four talk to their provider's REST API directly over net/http, no SDK.

type Region

type Region struct {
	ID   string
	Name string
}

Region is one region/location a provider can create a server in.

type RegionResourceLister

type RegionResourceLister interface {
	ListServers(ctx context.Context, region string) ([]ProviderResource, error)
}

RegionResourceLister is optional: providers whose machine list is scoped to a region can list any one region on request.

type ResizeSpec

type ResizeSpec struct {
	OCPUs        float64
	MemoryGB     float64
	InstanceType string
}

ResizeSpec carries what a driver needs to resize. Flexible-shape drivers read OCPUs and MemoryGB, drivers with fixed types read InstanceType.

type ResourceLister

type ResourceLister interface {
	ListResources(ctx context.Context) ([]ProviderResource, error)
}

ResourceLister is optional on a provisioner: only providers that can list the machines in an account implement it. Read-only, never mutates.

type ScopeMissingError

type ScopeMissingError struct {
	Provider   string
	Capability string
	Needs      string
}

ScopeMissingError reports a provider 401 or 403 mapped to the scope the operation needs. It carries fixed text only, never the provider body.

func ScopeFromError

func ScopeFromError(provider, capabilityID string, err error) (*ScopeMissingError, bool)

ScopeFromError returns a ScopeMissingError when err is a provider 401 or 403 for a known capability of provider, so callers can say which scope to add instead of a bare 403.

func (*ScopeMissingError) Error

func (e *ScopeMissingError) Error() string

type ServerStatus

type ServerStatus string

ServerStatus is a provider-reported server lifecycle state, normalized across providers into a small common vocabulary.

const (
	ServerStatusPending ServerStatus = "pending"
	ServerStatusRunning ServerStatus = "running"
	ServerStatusError   ServerStatus = "error"
)

The three server states GetServer normalizes every provider's own status string into.

type Size

type Size struct {
	ID     string
	Name   string
	VCPUs  int
	Memory int // MB
	Disk   int // GB
	// PriceMonthly is the provider's own listed monthly price, in its
	// native currency string. Empty when the provider does not return a
	// price for this size.
	PriceMonthly string
	Currency     string
	// Regions lists where the provider offers this size. Empty means the
	// provider does not say, so no region check is possible.
	Regions []string
}

Size is one server size/plan a provider offers.

type SpendBalance

type SpendBalance struct {
	SpendSection
	AccountBalance     *SpendValue `json:"account_balance"`
	MonthToDateBalance *SpendValue `json:"month_to_date_balance"`
	MonthToDateUsage   *SpendValue `json:"month_to_date_usage"`
	GeneratedAt        *time.Time  `json:"generated_at"`
}

SpendBalance is the account balance block.

type SpendEstimate

type SpendEstimate struct {
	SpendSection
	MonthlyTotal  *SpendValue `json:"monthly_total"`
	ResourceCount int         `json:"resource_count"`
	PricedCount   int         `json:"priced_count"`
}

SpendEstimate is the monthly total of list prices for discovered machines.

type SpendInvoice

type SpendInvoice struct {
	SpendSection
	Amount      *SpendValue `json:"amount"`
	InvoiceID   string      `json:"invoice_id,omitempty"`
	InvoiceUUID string      `json:"invoice_uuid,omitempty"`
	Description string      `json:"description,omitempty"`
	Date        *time.Time  `json:"date"`
}

SpendInvoice summarises the most recent invoice.

type SpendReport

type SpendReport struct {
	Provider    string        `json:"provider"`
	AccountID   string        `json:"account_id"`
	Currency    string        `json:"currency"`
	GeneratedAt time.Time     `json:"generated_at"`
	Cached      bool          `json:"cached"`
	Balance     SpendBalance  `json:"balance"`
	LastInvoice SpendInvoice  `json:"last_invoice"`
	Estimate    SpendEstimate `json:"estimate"`
}

SpendReport is the provider-neutral spend answer.

type SpendSection

type SpendSection struct {
	State string `json:"state"`
	Needs string `json:"needs,omitempty"`
}

SpendSection is the state shared by every spend section.

type SpendValue

type SpendValue struct {
	Value    string     `json:"value"`
	Source   string     `json:"source"`
	DataAsOf *time.Time `json:"data_as_of"`
}

SpendValue is one number with where it came from and how old it is.

type Vultr

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

Vultr implements Provisioner against the Vultr API v2 (https://www.vultr.com/api/), bearer key auth, no SDK.

func NewVultr

func NewVultr(apiKey string) *Vultr

NewVultr returns a Vultr provisioner authenticating with the API key.

func (*Vultr) CreateServer

func (v *Vultr) CreateServer(ctx context.Context, opts CreateOpts) (serverID, ipAddr string, err error)

CreateServer calls POST /v2/instances with base64 user_data.

func (*Vultr) DeleteServer

func (v *Vultr) DeleteServer(ctx context.Context, id string) error

DeleteServer calls DELETE /v2/instances/{id} for the stored id only. A 404 means it is already gone, which is success for a retried destroy.

func (*Vultr) GetServer

func (v *Vultr) GetServer(ctx context.Context, id string) (ServerStatus, string, error)

GetServer calls GET /v2/instances/{id}.

func (*Vultr) ListRegions

func (v *Vultr) ListRegions(ctx context.Context) ([]Region, error)

ListRegions calls GET /v2/regions, following every page.

func (*Vultr) ListSizes

func (v *Vultr) ListSizes(ctx context.Context, region string) ([]Size, error)

ListSizes calls GET /v2/plans. Each plan carries its locations, so a non-empty region keeps only plans Vultr offers there, and Size.Regions feeds the size-region check.

func (*Vultr) ProbeCapabilities

func (v *Vultr) ProbeCapabilities(ctx context.Context, concurrency int) ProviderCapabilities

ProbeCapabilities runs one read-only GET per read capability, at most concurrency at once. A 401 or 403 is missing, a 2xx is granted, anything else stays unknown and never reads as missing.

Jump to

Keyboard shortcuts

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