provision

package
v1.5.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: 33 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.

Variables

This section is empty.

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.

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"`
}

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 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 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) GetServer

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

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

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.

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 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) GetServer

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

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

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.

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) 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) 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.

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
}

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 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