Documentation
¶
Overview ¶
Package provider is the versioned host/VM provider contract (S472).
A provider package is either a declarative manifest (data only, run by the built-in engine) or an executable plugin (argv-invoked, JSON over stdin/stdout, diagnostics on stderr). Both speak the same Request/Result schema below. This file freezes the shared types so the contract, loader and dispatcher stories can proceed in parallel; behavior lives elsewhere.
Endpoint reservation (S522.2 rework 3).
A satellite's public endpoint has to be known BEFORE the host exists. The master renders the first-boot script with the endpoint baked into it, and a script that discovers its own address from cloud metadata works only on the one cloud whose metadata format it knows — which is exactly how the first zoo-aws create came up without ever enrolling.
So a provider that can hold a stable address reserves it FIRST, the reserved address becomes the enrollment bundle's endpoint hint, and the host is created afterwards and attached to the address it was already told about. Nothing then depends on metadata, and nothing races the attachment against first boot.
Reservation is an OPTIONAL capability, deliberately kept OFF the Adapter interface: a provider with no stable addresses stays exactly as it was and the provisioning sequence simply has no hint to send, rather than every adapter having to grow a method that answers "not me".
Index ¶
- Constants
- func DeadlineFromTags(tags []string) (time.Time, bool)
- func DeadlineTag(t time.Time) string
- func DefaultJournalDir() (string, error)
- func Expand(tmpl string, vars map[string]string) (string, error)
- func IdempotencyTag(key string) string
- func LeaseTags(owner, idempotencyKey string, temp *Authorization) []string
- func Owned(tags []string, owner string) bool
- func OwnerTag(owner string) string
- func Serve(ctx context.Context, a Adapter, r io.Reader, w io.Writer) error
- func SslipEndpoint(ip string) string
- func TemporaryKey(createKey string) string
- func ValidOwner(owner string) bool
- func ValidateDeclarative(m Manifest) error
- func ValidateManifest(m Manifest) error
- func WorkTag(ref string) string
- type Accelerator
- type Adapter
- type Allocation
- type AuthKind
- type Authorization
- type AvailState
- type Availability
- type BuiltinFactory
- type CPU
- type Capability
- type Charge
- type CostPlan
- type CostReport
- type CredentialFunc
- type CredentialSource
- type DeclarativeAuth
- type DeclarativeConfig
- type DeclarativeDoc
- type DeclarativeEndpoint
- type DeclarativeResource
- type DeviceComparison
- type DeviceMismatch
- type Dispatcher
- func (d *Dispatcher) Adapter() Adapter
- func (d *Dispatcher) CompleteWork(ctx context.Context, workRef string) ([]Result, error)
- func (d *Dispatcher) Do(ctx context.Context, req Request) (Result, error)
- func (d *Dispatcher) ExpireTemporary(ctx context.Context) ([]Result, error)
- func (d *Dispatcher) Manifest() Manifest
- func (d *Dispatcher) Redact(s string) string
- func (d *Dispatcher) Resume(ctx context.Context) (ResumeReport, error)
- func (d *Dispatcher) View(ctx context.Context) (JournalView, error)
- type EndpointReserver
- type Error
- type ErrorCode
- type ExecOptions
- type ExecPolicy
- type FileJournal
- type Form
- type JournalEntry
- type JournalStore
- type JournalView
- type JournaledResource
- type Lifecycle
- type LifecycleMode
- type Manifest
- type MemoryJournal
- type MismatchKind
- type ModelSpec
- type Network
- type Offer
- type OffersData
- type Op
- type Operation
- type Options
- type Phase
- type Placement
- type Plan
- type Price
- type PurchaseMode
- type Qualification
- type Quota
- type Redactor
- type Request
- type Reservation
- type Resource
- type Result
- type ResumeReport
- type Spec
- type State
- type StaticCredential
- type Storage
- type Workload
Constants ¶
const ( PhCredential = "credential" PhResourceID = "resource_id" PhIdempotencyKey = "idempotency_key" PhIdempotencyTag = "idempotency_tag" PhOwnerTag = "owner_tag" PhName = "name" PhTags = "tags" // JSON array in a body; comma-joined elsewhere PhSpecName = "spec.name" PhSpecRegion = "spec.region" PhSpecSize = "spec.size" PhSpecImage = "spec.image" PhSpecUserData = "spec.user_data" )
Placeholders accepted in templates. ${credential} is accepted only in Auth.Value, so a document cannot route the credential into a body, a path or a query parameter by another name.
const ( // TagLease marks a resource as created through this contract. TagLease = "bashy-lease" // TagTemporary marks a resource created with a temporary-lifecycle // authorization (A6); only such a resource may be destroyed under one. TagTemporary = "bashy-temp" )
The bashy-lease tag discipline: the tags on a provider resource are the durable record of who owns it, which request created it and whether it was created as temporary. They survive the controller (a fresh process, or a lost create response, can recover everything from the provider), so adapters must write them at create and read them back before acting.
Every tag fits the common provider tag charset [A-Za-z0-9_:-], max 255.
const GiB int64 = 1 << 30
GiB is one gibibyte in bytes.
const KindInfra = "infra"
KindInfra is the Manifest.Kind of every provider package (the fleet kind and bashy verb of record are both "infra", S472.0).
const ProtocolVersion = "provider/v1"
ProtocolVersion is the only protocol version this package speaks.
Variables ¶
This section is empty.
Functions ¶
func DeadlineFromTags ¶
DeadlineFromTags returns the latest recorded deadline, if any.
func DeadlineTag ¶
DeadlineTag records a TTL. When several are present the latest wins (DeadlineFromTags), which is how a lease is extended.
func DefaultJournalDir ¶
DefaultJournalDir is where the local journal lives: BASHY_HOME/provider/ journal, with BASHY_HOME defaulting to $HOME/.bashy.
func Expand ¶
Expand substitutes ${field} placeholders in tmpl from vars. An unknown placeholder is an error: templates are closed, nothing is evaluated.
func IdempotencyTag ¶
IdempotencyTag is the tag recording the idempotency key of the create that made a resource. Keys are hashed, so any key string is safe.
func LeaseTags ¶
func LeaseTags(owner, idempotencyKey string, temp *Authorization) []string
LeaseTags returns the tags a create must write: lease, owner, idempotency key and, for a temporary authorization, the temporary marker plus its deadline and/or work tag.
func OwnerTag ¶
OwnerTag is the ownership tag for an owner; an adapter acts on an existing resource only when it carries TagLease and its owner's tag. owner must satisfy ValidOwner.
func Serve ¶
Serve is the plugin side of the executable protocol: it reads one Request from r, runs it on a, and writes one Result to w. A plugin's main is typically `provider.Serve(ctx, adapter, os.Stdin, os.Stdout)` with diagnostics on os.Stderr. A normalized failure is a Result, not a Serve error; Serve fails only when it cannot read the request or write the result.
func SslipEndpoint ¶
SslipEndpoint is the https endpoint an IPv4 address answers on through sslip.io, the wildcard DNS service that resolves an address written into its own domain straight back to that address: 52.12.110.80 becomes https://52-12-110-80.sslip.io.
The DASHED spelling is the one used, not the dotted one: a dotted address is several DNS labels deep under sslip.io and a wildcard certificate covers exactly one label, so only the dashed form gets built-in TLS.
It returns "" for anything that is not an IPv4 address: an IPv6 address has no dashed form here, and a host name needs no hint.
func TemporaryKey ¶
TemporaryKey is the idempotency key of the automatic destroy of a temporary resource created under createKey: deterministic, so expiry sweeps and work completion destroy it exactly once.
func ValidOwner ¶
ValidOwner reports whether owner can be used verbatim in OwnerTag.
func ValidateDeclarative ¶
ValidateDeclarative validates a declarative manifest against the engine schema without evaluating anything or making any network call. It is the same function the master calls at registration.
func ValidateManifest ¶
ValidateManifest checks a manifest's identity, protocol version, form and capability set.
Types ¶
type Accelerator ¶
type Accelerator struct {
Vendor string `json:"vendor,omitempty"`
Model string `json:"model"`
MemoryBytes int64 `json:"memory_bytes"`
Fraction float64 `json:"fraction,omitempty"`
Unified bool `json:"unified,omitempty"`
}
Accelerator is one accelerator device. MemoryBytes is that device's own memory (for a fractional device, its slice). Fraction is the share of a physical device (1 = whole). Unified marks memory shared with the host.
type Adapter ¶
Adapter executes contract requests for one provider. Built-in adapters, the declarative engine and the executable-plugin runner all implement it.
func Guard ¶
Guard wraps an adapter so every request is checked by CheckRequest before the adapter runs. A refused request never reaches the adapter. Guard also refuses a result whose op differs from the request's, so an adapter cannot substitute one operation for another.
func NewDeclarativeAdapter ¶
func NewDeclarativeAdapter(m Manifest, cfg DeclarativeConfig) (Adapter, error)
NewDeclarativeAdapter returns the engine for a declarative manifest, wrapped in Guard. It makes no network call until Do.
func NewExecAdapter ¶
func NewExecAdapter(m Manifest, opts ExecOptions) (Adapter, error)
NewExecAdapter returns the runner for an executable provider plugin. Each Do execs m.Argv directly (never through a shell), writes the Request as one JSON document on stdin, and reads one Result from stdout; stderr carries diagnostics only. The runner is wrapped in Guard, so an undeclared operation, a missing idempotency key or an unauthorized destroy is refused without executing the plugin.
type Allocation ¶
type Allocation struct {
Accelerators []Accelerator `json:"accelerators,omitempty"`
ObservedAt time.Time `json:"observed_at,omitempty"`
}
Allocation is what is actually allocated/observed on a host, distinct from what the catalog advertises. Nil means nothing observed.
type AuthKind ¶
type AuthKind string
AuthKind is the kind of destroy authorization (S450.1 amendment A6).
const ( // AuthConfirmation is a single-use user confirmation bound to one // resource ID and one idempotency key. AuthConfirmation AuthKind = "confirmation" // AuthTemporary is a temporary-lifecycle authorization (TTL or // work-bound) recorded at create and tagged on the resource. AuthTemporary AuthKind = "temporary" )
type Authorization ¶
type Authorization struct {
Kind AuthKind `json:"kind"`
ResourceID string `json:"resource_id,omitempty"`
IdempotencyKey string `json:"idempotency_key,omitempty"`
ExpiresAt time.Time `json:"expires_at,omitempty"` // TTL form
WorkRef string `json:"work_ref,omitempty"` // work-bound form
}
Authorization accompanies destroy requests (and, for AuthTemporary, the create that recorded it).
type AvailState ¶
type AvailState string
AvailState is whether an offer can currently be bought.
const ( AvailAvailable AvailState = "available" AvailUnknown AvailState = "unknown" )
type Availability ¶
type Availability struct {
State AvailState `json:"state"`
Reason string `json:"reason,omitempty"`
ObservedAt time.Time `json:"observed_at,omitempty"`
}
Availability is the (advertised) availability in the offer's region.
type BuiltinFactory ¶
BuiltinFactory builds a built-in adapter for a manifest from the credential the dispatcher resolved. Hosts register one per built-in provider name (e.g. digitalocean.New behind "digitalocean").
type Capability ¶
type Capability string
Capability names an operation or optional feature a provider declares. Every Op is also a capability; "volumes" and "spot" are feature flags.
const ( CapVolumes Capability = "volumes" CapSpot Capability = "spot" )
type Charge ¶
type Charge struct {
Known bool `json:"known"`
USD float64 `json:"usd,omitempty"`
ObservedAt time.Time `json:"observed_at,omitempty"`
}
Charge is one projected cost line; Known=false is an explicit unknown.
type CostPlan ¶
type CostPlan struct {
Compute Charge `json:"compute"`
Storage Charge `json:"storage"`
Network Charge `json:"network"`
Measured *float64 `json:"measured_usd,omitempty"`
}
CostPlan separates quoted (projected) from measured (nil until observed).
type CostReport ¶
type CostReport struct {
Ongoing bool `json:"ongoing"`
Retained []string `json:"retained,omitempty"`
Note string `json:"note,omitempty"`
}
CostReport describes what keeps costing money after stop or a refused / partial destroy (retained disks, reserved IPs, the instance itself).
func RefusedDestroyCost ¶
func RefusedDestroyCost() *CostReport
RefusedDestroyCost is the cost report attached to a refused destroy: the resource was not touched, so whatever it cost before it still costs.
type CredentialFunc ¶
CredentialFunc adapts a function to CredentialSource.
func (CredentialFunc) Credential ¶
Credential implements CredentialSource.
type CredentialSource ¶
type CredentialSource interface {
Credential(ctx context.Context, provider string) (string, error)
}
CredentialSource resolves the provider credential. It is the one seam between this stdlib-only package and the host's credential store.
type DeclarativeAuth ¶
type DeclarativeAuth struct {
// In is "header" or "query".
In string `json:"in"`
// Name is the header or query parameter.
Name string `json:"name"`
// Value is a template that must use ${credential} (default:
// "${credential}"; e.g. "Bearer ${credential}").
Value string `json:"value,omitempty"`
}
DeclarativeAuth says where the credential goes on each request.
type DeclarativeConfig ¶
type DeclarativeConfig struct {
// Credential is held in memory only; it is placed as Auth declares
// and never written anywhere.
Credential string
// Owner scopes ownership (ValidOwner).
Owner string
// HTTPClient defaults to a client with a 60s timeout.
HTTPClient *http.Client
}
DeclarativeConfig configures the engine for one provider.
type DeclarativeDoc ¶
type DeclarativeDoc struct {
// BaseURL is the API root every operation path is joined to.
BaseURL string `json:"base_url"`
// Headers are sent on every request (templated; the credential is
// not allowed here — see Auth).
Headers map[string]string `json:"headers,omitempty"`
// Auth places the credential.
Auth DeclarativeAuth `json:"auth"`
// Resource maps a provider resource object onto the normalized
// Resource (JSON paths relative to the operation's Result).
Resource DeclarativeResource `json:"resource"`
// States maps the provider's raw status strings onto normalized
// states; anything unmapped is StateUnknown.
States map[string]State `json:"states"`
// Operations declares one endpoint per supported Op. The manifest's
// capability list must match its keys (plan needs no endpoint).
Operations map[Op]*DeclarativeEndpoint `json:"operations"`
}
DeclarativeDoc is the declarative document a Manifest.Declarative decodes into.
func ParseDeclarative ¶
func ParseDeclarative(m Manifest) (*DeclarativeDoc, error)
ParseDeclarative decodes and validates m.Declarative.
type DeclarativeEndpoint ¶
type DeclarativeEndpoint struct {
Method string `json:"method"`
// Path is a template joined to BaseURL.
Path string `json:"path"`
// Query holds templated query parameters.
Query map[string]string `json:"query,omitempty"`
// Body is a JSON template: every string value is expanded, and a
// string that is exactly "${tags}" becomes the JSON array of tags.
Body json.RawMessage `json:"body,omitempty"`
// Result is the JSON path of the resource object (or, for list, the
// array of them) in the response. Empty means the whole body; for
// operations whose response carries no resource (a 204 destroy, an
// action receipt) set NoResource.
Result string `json:"result,omitempty"`
// NoResource says the response does not describe the resource; the
// engine inspects it afterwards (or, for destroy, reports it deleted).
NoResource bool `json:"no_resource,omitempty"`
}
DeclarativeEndpoint is one operation's HTTP call.
type DeclarativeResource ¶
type DeclarativeResource struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
Status string `json:"status"`
Region string `json:"region,omitempty"`
Size string `json:"size,omitempty"`
Tags string `json:"tags"`
PublicIPs string `json:"public_ips,omitempty"`
CreatedAt string `json:"created_at,omitempty"`
// Retained lists what the provider keeps (and bills) after the
// resource is destroyed or stopped, e.g. attached volumes.
Retained string `json:"retained,omitempty"`
}
DeclarativeResource maps a resource object's JSON paths. ID, Status and Tags are required; the others are optional. Paths are dot-separated keys (array indexes are digits), no functions.
type DeviceComparison ¶
type DeviceComparison struct {
Known bool `json:"known"`
Advertised int `json:"advertised"`
Observed int `json:"observed"`
Mismatches []DeviceMismatch `json:"mismatches,omitempty"`
}
DeviceComparison is the result of CompareAccelerators.
func CompareAccelerators ¶
func CompareAccelerators(advertised, observed []Accelerator, tolerance float64) DeviceComparison
CompareAccelerators compares an observed per-device inventory (for example Outpost sysinfo GPUs mapped to Accelerator: model name plus per-device memory bytes) against advertised devices. Models compare case- and punctuation-insensitively; observed memory below advertised by more than tolerance (fraction, e.g. 0.05 for driver reserve) is a mismatch. Zero observed memory means unobserved and is not compared. Devices are compared one by one, never summed.
func (DeviceComparison) Match ¶
func (c DeviceComparison) Match() bool
Match reports no observed-versus-advertised difference.
type DeviceMismatch ¶
type DeviceMismatch struct {
Kind MismatchKind `json:"kind"`
Index int `json:"index"`
AdvertisedModel string `json:"advertised_model,omitempty"`
ObservedModel string `json:"observed_model,omitempty"`
AdvertisedBytes int64 `json:"advertised_bytes,omitempty"`
ObservedBytes int64 `json:"observed_bytes,omitempty"`
}
DeviceMismatch is one difference. Index is the position in the paired (model, memory-descending) ordering; it is -1 for a count mismatch.
type Dispatcher ¶
type Dispatcher struct {
// contains filtered or unexported fields
}
Dispatcher runs lifecycle operations for one provider through its adapter and the journal.
func Open ¶
Open resolves the credential, builds the adapter for m's form and returns the dispatcher. It makes no provider call. An executable manifest under ExecDisabled is refused with ErrExecDisabled before any process starts.
func (*Dispatcher) Adapter ¶
func (d *Dispatcher) Adapter() Adapter
Adapter returns the underlying adapter (guarded). Callers that need a raw read (inspect/list without the dispatcher) may use it.
func (*Dispatcher) CompleteWork ¶
CompleteWork destroys every journaled work-bound temporary resource created for workRef, with no confirmation input.
func (*Dispatcher) Do ¶
Do runs one operation. Read operations (validate, capacity, plan, inspect, list) go to the adapter under the common timeout and retries and are not journaled. A mutating operation is journaled before and after the call; a replay of a completed key answers from the journal without a provider call — except a create, whose resource is proven to still exist first (createReplay); a pending key is reconciled first; and a destroy is authorized per A6 before anything reaches the adapter.
func (*Dispatcher) ExpireTemporary ¶
func (d *Dispatcher) ExpireTemporary(ctx context.Context) ([]Result, error)
ExpireTemporary destroys every journaled resource whose TTL authorization has expired by the dispatcher's clock, with no confirmation input: the authorization was given at create. Each resource is destroyed exactly once (TemporaryKey). Failures are reported per resource and leave it journaled active with its cost.
func (*Dispatcher) Manifest ¶
func (d *Dispatcher) Manifest() Manifest
Manifest returns the provider's manifest.
func (*Dispatcher) Redact ¶
func (d *Dispatcher) Redact(s string) string
Redact scrubs s: the credential literal(s), then the caller's Redactor.
func (*Dispatcher) Resume ¶
func (d *Dispatcher) Resume(ctx context.Context) (ResumeReport, error)
Resume reconciles every pending operation in the journal — a create whose result was never recorded, an ambiguous destroy — from the provider, before anything is retried. It never creates or destroys: it only asks and records. Call it once at process start.
func (*Dispatcher) View ¶
func (d *Dispatcher) View(ctx context.Context) (JournalView, error)
View loads and folds the provider's journal.
type EndpointReserver ¶
type EndpointReserver interface {
ReserveEndpoint(ctx context.Context, spec Spec) (Reservation, error)
}
EndpointReserver is the optional capability of reserving a host's stable public address before the host is created. An adapter that implements it is asked once, ahead of enrollment.
type Error ¶
type Error struct {
Code ErrorCode `json:"code"`
Message string `json:"message"`
Retryable bool `json:"retryable,omitempty"`
}
Error is a structured, normalized error.
func AuthorizeDestroy ¶
AuthorizeDestroy is the full A6 check against the resource as the provider reports it: the static check, and for a temporary authorization the resource must have been created as temporary (TagTemporary) and, when the authorization names a work ref, carry that work tag.
func CheckDestroyAuthorization ¶
CheckDestroyAuthorization is the static half of A6, decidable before any provider call: a destroy must carry either a user confirmation bound to exactly this resource ID and this idempotency key, or a temporary authorization. A confirmation is single use by construction — it names one idempotency key, and a replay under that key is the same operation. A temporary authorization still has to match the resource's recorded tags; see AuthorizeDestroy.
func CheckRequest ¶
CheckRequest validates req against manifest m without calling any provider: protocol version, a declared capability for req.Op (an undeclared op is unsupported_capability and is never substituted), an idempotency key on mutating ops, a resource ID where one is needed, and the static half of the destroy authorization (see CheckDestroyAuthorization).
type ErrorCode ¶
type ErrorCode string
ErrorCode is a normalized error code.
const ( ErrUnsupportedCapability ErrorCode = "unsupported_capability" ErrConfirmationRequired ErrorCode = "confirmation_required" ErrNotOwned ErrorCode = "not_owned" // untagged or foreign resource ErrNotFound ErrorCode = "not_found" ErrInvalidRequest ErrorCode = "invalid_request" ErrBudgetExceeded ErrorCode = "budget_exceeded" ErrQuotaExceeded ErrorCode = "quota_exceeded" ErrInvalidCredentials ErrorCode = "invalid_credentials" ErrProtocolMismatch ErrorCode = "protocol_mismatch" ErrRateLimited ErrorCode = "rate_limited" ErrTimeout ErrorCode = "timeout" ErrProvider ErrorCode = "provider_error" ErrNeedsManualReconcile ErrorCode = "needs_manual_reconcile" ErrExecDisabled ErrorCode = "exec_disabled" // executable plugin in a no-exec context )
type ExecOptions ¶
type ExecOptions struct {
// Stderr receives the plugin's diagnostics; nil discards them.
Stderr io.Writer
// Env is the plugin's environment; nil inherits the caller's.
Env []string
// Dir is the plugin's working directory; empty inherits the caller's.
Dir string
}
ExecOptions configures the executable-plugin runner.
type ExecPolicy ¶
type ExecPolicy int
ExecPolicy says whether executable plugins may run in this process.
const ( // ExecDisabled refuses every executable plugin (the master). ExecDisabled ExecPolicy = iota // ExecAllowed runs executable plugins (user-owned compute only). ExecAllowed )
type FileJournal ¶
type FileJournal struct {
// contains filtered or unexported fields
}
FileJournal is the local JournalStore: one JSON-lines file per provider under dir, appended with O_APPEND so concurrent writers on one host interleave whole records. Files are 0600, the directory 0700.
func NewFileJournal ¶
func NewFileJournal(dir string) (*FileJournal, error)
NewFileJournal returns a file store rooted at dir, creating it.
func (*FileJournal) Append ¶
func (f *FileJournal) Append(_ context.Context, e JournalEntry) error
Append implements JournalStore.
func (*FileJournal) Load ¶
func (f *FileJournal) Load(_ context.Context, provider string) ([]JournalEntry, error)
Load implements JournalStore. A truncated last line (a crash mid-write) is ignored; any other malformed line is an error.
type JournalEntry ¶
type JournalEntry struct {
Seq int64 `json:"seq,omitempty"`
At time.Time `json:"at"`
Provider string `json:"provider"`
Form Form `json:"form,omitempty"`
Op Op `json:"op"`
IdempotencyKey string `json:"idempotency_key,omitempty"`
Phase Phase `json:"phase"`
Attempt int `json:"attempt,omitempty"`
ResourceID string `json:"resource_id,omitempty"` // before the call
ResultID string `json:"result_resource_id,omitempty"` // after the call
State State `json:"state,omitempty"`
Tags []string `json:"tags,omitempty"`
Spec *Spec `json:"spec,omitempty"`
Authorization *Authorization `json:"authorization,omitempty"`
Error *Error `json:"error,omitempty"`
Cost *CostReport `json:"cost,omitempty"`
Note string `json:"note,omitempty"`
}
JournalEntry is one journal record.
type JournalStore ¶
type JournalStore interface {
Append(ctx context.Context, e JournalEntry) error
Load(ctx context.Context, provider string) ([]JournalEntry, error)
}
JournalStore persists journal records for one host. Append must be durable before it returns; Load returns every record of provider in append order. Implementations must be safe for concurrent use.
type JournalView ¶
type JournalView struct {
Operations []Operation
Resources []JournaledResource
}
JournalView folds a provider's records into operations and resources.
func Replay ¶
func Replay(entries []JournalEntry) JournalView
Replay folds entries (append order) into a view. It is deterministic and pure: the same records always give the same view.
func (JournalView) Find ¶
func (v JournalView) Find(op Op, key string) (Operation, bool)
Find returns the operation for (op, key).
func (JournalView) ManualReconcile ¶
func (v JournalView) ManualReconcile() []Operation
ManualReconcile returns the operations a human has to look at.
func (JournalView) Pending ¶
func (v JournalView) Pending() []Operation
Pending returns the operations whose outcome is unknown.
func (JournalView) Resource ¶
func (v JournalView) Resource(id string) (JournaledResource, bool)
Resource returns the journaled resource with id.
type JournaledResource ¶
type JournaledResource struct {
ID string
CreateKey string
Tags []string
State State
// Temporary is the temporary-lifecycle authorization recorded at
// create, if any.
Temporary *Authorization
// Destroyed is true once a destroy result or reconciliation reported
// StateDeleted. A refused or failed destroy leaves it false.
Destroyed bool
// Cost is the latest cost report (stop, refused destroy, destroy).
Cost *CostReport
Last time.Time
}
JournaledResource is the journal's view of one provider resource.
type Lifecycle ¶
type Lifecycle struct {
StopKeepsBilling bool `json:"stop_keeps_billing"`
StopKeepsDisk bool `json:"stop_keeps_disk"`
ReleaseDeletes bool `json:"release_deletes"`
Note string `json:"note,omitempty"`
}
Lifecycle states what stop and release mean for cost and data.
type LifecycleMode ¶
type LifecycleMode string
const ( LifecyclePersistent LifecycleMode = "persistent" LifecycleEphemeral LifecycleMode = "ephemeral" )
type Manifest ¶
type Manifest struct {
Name string `json:"name" yaml:"name"`
Kind string `json:"kind" yaml:"kind"` // KindInfra ("infra")
Form Form `json:"form" yaml:"form"`
Version string `json:"version,omitempty" yaml:"version,omitempty"`
ProtocolVersion string `json:"protocol_version" yaml:"protocol_version"`
Summary string `json:"summary,omitempty" yaml:"summary,omitempty"`
Capabilities []Capability `json:"capabilities" yaml:"capabilities"`
// Argv is the executable plugin's command line (FormExecutable only).
// It is exec'd directly, never through a shell.
Argv []string `json:"argv,omitempty" yaml:"argv,omitempty"`
// Declarative holds the endpoint/template/lifecycle-mapping document
// (FormDeclarative only). Its schema is owned by the declarative engine.
Declarative json.RawMessage `json:"declarative,omitempty" yaml:"-"`
}
Manifest identifies a provider package. Credentials are never manifest fields; they are references resolved by the caller.
type MemoryJournal ¶
type MemoryJournal struct {
// contains filtered or unexported fields
}
MemoryJournal is an in-memory JournalStore (tests, the master's cache).
func NewMemoryJournal ¶
func NewMemoryJournal() *MemoryJournal
NewMemoryJournal returns an empty in-memory store.
func (*MemoryJournal) Append ¶
func (m *MemoryJournal) Append(_ context.Context, e JournalEntry) error
Append implements JournalStore.
func (*MemoryJournal) Load ¶
func (m *MemoryJournal) Load(_ context.Context, provider string) ([]JournalEntry, error)
Load implements JournalStore.
type MismatchKind ¶
type MismatchKind string
MismatchKind classifies an observed-versus-advertised accelerator difference.
const ( MismatchCount MismatchKind = "count" MismatchModel MismatchKind = "model" MismatchMemory MismatchKind = "memory" )
type ModelSpec ¶
type ModelSpec struct {
Digest string `json:"digest,omitempty"`
Quantization string `json:"quantization,omitempty"`
ContextLength int `json:"context_length,omitempty"`
Params int64 `json:"params,omitempty"`
WeightBytes int64 `json:"weight_bytes,omitempty"`
KVBytesPerToken int64 `json:"kv_bytes_per_token,omitempty"`
}
ModelSpec carries the registry fields (Digest, Quantization, ContextLength) plus the weight/KV metadata the estimate needs. Zero means unknown.
type Network ¶
type Network struct {
Known bool `json:"known"`
BandwidthMbps int64 `json:"bandwidth_mbps,omitempty"`
TransferBytes int64 `json:"transfer_bytes,omitempty"` // monthly allowance
}
Network holds network characteristics; Known is false when the provider does not say.
type Offer ¶
type Offer struct {
Account string `json:"account,omitempty"`
Region string `json:"region"`
SKU string `json:"sku"`
Purchase PurchaseMode `json:"purchase"`
CPU CPU `json:"cpu"`
MemoryBytes int64 `json:"memory_bytes"`
Accelerators []Accelerator `json:"accelerators,omitempty"`
Storage []Storage `json:"storage,omitempty"`
Network Network `json:"network"`
Price Price `json:"price"`
Availability Availability `json:"availability"`
Quota Quota `json:"quota"`
Allocation *Allocation `json:"allocation,omitempty"`
Lifecycle Lifecycle `json:"lifecycle"`
Qualification Qualification `json:"qualification"`
}
Offer is one normalized purchasable shape: advertised catalog data plus optional account quota and observed allocation.
func DiscoverOffers ¶
DiscoverOffers runs OpCapacity on a and returns its normalized offers. An adapter that does not emit offers yields none.
func (Offer) CompareObserved ¶
func (o Offer) CompareObserved() DeviceComparison
CompareObserved compares the offer's advertised accelerators with its observed Allocation. A nil allocation means no observation was made.
func (Offer) FitsSingleDevice ¶
FitsSingleDevice reports whether need bytes fit on one device.
func (Offer) PerDeviceMemoryBytes ¶
PerDeviceMemoryBytes returns each accelerator's own memory, in order.
func (Offer) Placeable ¶
Placeable reports whether the offer can be bought now under v1 policy and why not. Unknown availability or quota does not block; it is surfaced by the caller from the Unknown states.
func (Offer) SingleDeviceFitBytes ¶
SingleDeviceFitBytes is the largest model/working set one device can hold: the per-device maximum, never a sum across devices.
type OffersData ¶
type OffersData struct {
Offers []Offer `json:"offers"`
}
OffersData is the "offers" payload of an OpCapacity result's Data.
type Op ¶
type Op string
Op is one lifecycle operation.
const ( OpValidate Op = "validate" // validate credentials OpCapacity Op = "capacity" // discover regions/sizes OpPlan Op = "plan" OpCreate Op = "create" OpInspect Op = "inspect" OpList Op = "list" OpStart Op = "start" OpStop Op = "stop" OpDestroy Op = "destroy" // Optional capabilities. OpReboot Op = "reboot" OpResize Op = "resize" )
type Operation ¶
type Operation struct {
Op Op
IdempotencyKey string
ResourceID string // the resource the op addressed or produced
Attempts int
// Pending is true when the latest record is an intent or an ambiguous
// result: the provider may have acted and nothing proves it either way.
Pending bool
// Done is true when a successful result or a reconciled outcome closed
// the op. Result is that record.
Done bool
Result *JournalEntry
// NeedsManualReconcile is true when reconciliation could not prove
// the outcome; a human has to look at the provider.
NeedsManualReconcile bool
// Retired is true when the resource a completed operation produced is
// gone, so Result no longer describes anything: the key may act
// again. A new attempt (an intent record) clears it.
Retired bool
// Refused counts refusals before any provider call.
Refused int
First time.Time
Last time.Time
}
Operation is the journal's view of one (op, idempotency key) pair: the records that describe it, folded into its current standing.
type Options ¶
type Options struct {
// Owner scopes ownership tags (ValidOwner). Required.
Owner string
// Exec is the executable-plugin policy; the zero value is disabled.
Exec ExecPolicy
// Journal is the durable store; nil opens the file store under
// DefaultJournalDir (BASHY_HOME/provider/journal).
Journal JournalStore
// Timeout bounds each provider call (default 60s).
Timeout time.Duration
// MutatingTimeout bounds a mutating call (create, destroy, power,
// resize) when it is larger than Timeout; zero means Timeout.
//
// It exists because those two budgets are not the same size. A read
// answers in a second or it is broken, but an adapter that brings a
// host all the way to its serving shape before answering — AWS
// Lightsail waits for "running" and then applies the firewall and
// the static IP — legitimately runs for minutes. Bounding it at the
// read timeout cancels the adapter mid-sequence and the dispatcher
// then reconciles the create as "the resource exists", reporting
// success for a host whose remaining steps never ran.
MutatingTimeout time.Duration
// Retries is how many more attempts a retryable failure gets after
// the first (default 0: one attempt). A create is never retried
// before its outcome has been reconciled by idempotency tag.
Retries int
// Backoff is the wait before a retry, multiplied by the attempt
// number (default 0).
Backoff time.Duration
// Now is the clock (TTL expiry); nil means time.Now.
Now func() time.Time
// Redact is applied to every journaled and logged string after the
// credential literal has been scrubbed.
Redact Redactor
// Credentials resolves the credential at Open. Required for the
// built-in and declarative forms.
Credentials CredentialSource
// Builtins maps a built-in manifest name to its factory.
Builtins map[string]BuiltinFactory
// HTTPClient is used by the declarative engine (default 60s client).
HTTPClient *http.Client
// ExecStderr, ExecEnv and ExecDir configure the executable runner.
// The dispatcher never puts the credential in ExecEnv.
ExecStderr io.Writer
ExecEnv []string
ExecDir string
// ExecFactory builds the executable runner (default NewExecAdapter).
// Tests install a hook that fails when called.
ExecFactory func(m Manifest, opts ExecOptions) (Adapter, error)
// Log receives one redacted line per noteworthy event; nil is silent.
Log func(line string)
}
Options configures a Dispatcher.
type Phase ¶
type Phase string
Phase is the stage a journal record describes.
const ( // PhaseIntent is written before the provider call. PhaseIntent Phase = "intent" // PhaseResult is written after the provider answered (success or a // normalized failure that proves nothing happened). PhaseResult Phase = "result" // PhaseRefused is a request the dispatcher refused before any // provider call (no confirmation, exec disabled, unsupported op). PhaseRefused Phase = "refused" // PhaseAmbiguous is a call whose outcome is unknown (timeout, lost // response, 5xx): the provider may or may not have acted. PhaseAmbiguous Phase = "ambiguous" // PhaseReconciled closes an intent or ambiguous record from what the // provider reports (list by idempotency tag, inspect by ID). PhaseReconciled Phase = "reconciled" // PhaseNeedsManualReconcile closes nothing: the outcome could not be // proven and a human has to look. PhaseNeedsManualReconcile Phase = "needs_manual_reconcile" // PhaseRetired says a completed operation no longer answers its key: // the resource it produced is gone (destroyed here, swept, or deleted // in the provider's own console), so replaying its result would // report a resource that does not exist. It closes nothing and // rewrites nothing — the record is the fact that the old answer is // dead, and the key is free to act again. PhaseRetired Phase = "retired" )
type Plan ¶
type Plan struct {
Offer Offer `json:"offer"`
Fits bool `json:"fits"`
Reason string `json:"reason,omitempty"`
Placement Placement `json:"placement,omitempty"`
NeedBytes int64 `json:"need_bytes,omitempty"`
Uncertain []string `json:"uncertain,omitempty"`
Cost CostPlan `json:"cost"`
LifecycleMode LifecycleMode `json:"lifecycle_mode"`
Purchase PurchaseMode `json:"purchase"`
MaxLifetime time.Duration `json:"max_lifetime,omitempty"`
CleanupTrigger string `json:"cleanup_trigger,omitempty"`
Notes []string `json:"notes,omitempty"`
}
Plan explains one offer's fit and cost.
type Price ¶
type Price struct {
Known bool `json:"known"`
USDPerHour float64 `json:"usd_per_hour,omitempty"`
USDPerMonth float64 `json:"usd_per_month,omitempty"`
ObservedAt time.Time `json:"observed_at,omitempty"`
}
Price is a unit price that may be unknown.
type PurchaseMode ¶
type PurchaseMode string
PurchaseMode is how an offer is bought.
const ( PurchaseOnDemand PurchaseMode = "on_demand" PurchaseSpot PurchaseMode = "spot" )
type Qualification ¶
type Qualification struct {
Qualified bool `json:"qualified"`
Reason string `json:"reason,omitempty"`
}
Qualification says whether the offer is usable under v1 policy.
type Quota ¶
type Quota struct {
Known bool `json:"known"`
Limit int `json:"limit,omitempty"`
Used int `json:"used,omitempty"`
ObservedAt time.Time `json:"observed_at,omitempty"`
}
Quota is account-level headroom for the offer's resource class; it is distinct from the advertised catalog. Known is false when not observed.
type Redactor ¶
Redactor scrubs a string before it is journaled or logged. The caller wires pkg/redact's Scrubber.String here; the dispatcher always scrubs the credential literal itself, with or without a Redactor.
type Request ¶
type Request struct {
ProtocolVersion string `json:"protocol_version"`
Op Op `json:"op"`
IdempotencyKey string `json:"idempotency_key,omitempty"` // required for mutating ops
ResourceID string `json:"resource_id,omitempty"`
Spec *Spec `json:"spec,omitempty"`
Authorization *Authorization `json:"authorization,omitempty"`
}
Request is one operation call.
type Reservation ¶
type Reservation struct {
// Name is the provider's own name for the reservation (e.g. a
// Lightsail static IP name), so a later destroy can find it.
Name string `json:"name,omitempty"`
// Address is the reserved IP.
Address string `json:"address,omitempty"`
// Endpoint is the public endpoint hint that address answers on, or
// "" when the provider has no hint to offer for it.
Endpoint string `json:"endpoint,omitempty"`
// Reused is true when the reservation already existed and was taken
// over rather than allocated. A replayed provision must not allocate
// a second address.
Reused bool `json:"reused,omitempty"`
}
Reservation is a stable public address held for a host that does not exist yet. The zero value means nothing was reserved.
func ReserveEndpoint ¶
ReserveEndpoint reserves a stable address for spec through a, or returns the zero Reservation when a reserves nothing — an adapter without the capability is not an error, it just has no hint.
type Resource ¶
type Resource struct {
ID string `json:"id"` // provider resource ID, preserved verbatim
Name string `json:"name,omitempty"`
State State `json:"state"`
RawStatus string `json:"raw_status,omitempty"`
Region string `json:"region,omitempty"`
Size string `json:"size,omitempty"`
Tags []string `json:"tags,omitempty"`
PublicIPs []string `json:"public_ips,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
}
Resource is a provider resource as reported by the provider.
type Result ¶
type Result struct {
ProtocolVersion string `json:"protocol_version"`
Op Op `json:"op"`
Resource *Resource `json:"resource,omitempty"`
Resources []Resource `json:"resources,omitempty"`
Cost *CostReport `json:"cost,omitempty"`
Data json.RawMessage `json:"data,omitempty"` // validate/capacity/plan payloads
Error *Error `json:"error,omitempty"`
}
Result is one operation's outcome. Exactly one of the payload fields or Error is meaningful.
type ResumeReport ¶
type ResumeReport struct {
Pending int // operations found pending
Reconciled int // proven done, result journaled
NotApplied int // proven not done; a replay may retry
NeedsManualReconcile int
}
ResumeReport summarizes Resume.
type Spec ¶
type Spec struct {
Name string `json:"name,omitempty"`
Region string `json:"region,omitempty"`
Size string `json:"size,omitempty"`
Image string `json:"image,omitempty"`
Tags []string `json:"tags,omitempty"`
// SSHKeys are provider key IDs or fingerprints installed at first boot.
SSHKeys []string `json:"ssh_keys,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
// UserData is opaque (e.g. an enrollment bundle) and passed through unread.
UserData []byte `json:"user_data,omitempty"`
}
Spec is the create/plan input.
type State ¶
type State string
State is the normalized lifecycle state of a provider resource. It says nothing about satellite installation or readiness.
type StaticCredential ¶
type StaticCredential string
StaticCredential is a CredentialSource holding one value in memory (a use-once token the caller already resolved).
func (StaticCredential) Credential ¶
Credential implements CredentialSource.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package aws is the AWS Lightsail provider adapter (S522.2): a FormBuiltin provider.Adapter over the Lightsail JSON API, reached through `bashy infra provision aws` (or `--provider aws`).
|
Package aws is the AWS Lightsail provider adapter (S522.2): a FormBuiltin provider.Adapter over the Lightsail JSON API, reached through `bashy infra provision aws` (or `--provider aws`). |
|
fakeec2
Package fakeec2 is a deterministic in-process stand-in for the AWS EC2 query API, the Service Quotas JSON API and the S3 object API, for testing the EC2 GPU worker adapter (pkg/provider/aws NewEC2).
|
Package fakeec2 is a deterministic in-process stand-in for the AWS EC2 query API, the Service Quotas JSON API and the S3 object API, for testing the EC2 GPU worker adapter (pkg/provider/aws NewEC2). |
|
fakelightsail
Package fakelightsail is a deterministic in-process stand-in for the AWS Lightsail and Cost Explorer JSON APIs, for testing pkg/provider/aws.
|
Package fakelightsail is a deterministic in-process stand-in for the AWS Lightsail and Cost Explorer JSON APIs, for testing pkg/provider/aws. |
|
Package conformance is the reusable provider conformance suite (S472.14): one func over states and transitions, idempotency and reconciliation, normalized errors, unsupported operations, stop-versus-destroy billing and data semantics, and A6 destroy confirmation.
|
Package conformance is the reusable provider conformance suite (S472.14): one func over states and transitions, idempotency and reconciliation, normalized errors, unsupported operations, stop-versus-destroy billing and data semantics, and A6 destroy confirmation. |
|
Package digitalocean is the reference provider adapter (S472.4a): a FormBuiltin provider.Adapter over the DigitalOcean v2 API.
|
Package digitalocean is the reference provider adapter (S472.4a): a FormBuiltin provider.Adapter over the DigitalOcean v2 API. |
|
fakedo
Package fakedo is an in-process fake of the DigitalOcean v2 API subset the provider adapter uses, for tests only (httptest; it never reaches the network).
|
Package fakedo is an in-process fake of the DigitalOcean v2 API subset the provider adapter uses, for tests only (httptest; it never reaches the network). |
|
Package enroll is the OSS client for the public dhnt.io satellite enrollment API (S472.13b item 1, executable path).
|
Package enroll is the OSS client for the public dhnt.io satellite enrollment API (S472.13b item 1, executable path). |