Documentation
¶
Overview ¶
Package setup implements the steps of `provr init`.
The Step pattern (Name, Check, Apply) is internal to provr and is not an extension point: steps are compiled in, never loaded or registered by users.
Index ¶
- Constants
- Variables
- func BudgetCreateCommand(billingAccountID, project, projectNumber string, usd int) string
- func BudgetName(project string) string
- func Failed(outcomes []Outcome) bool
- func HostEmail(project string) string
- func Member(account string) string
- func OperatorEmail(project string) string
- func PolicySnippet() string
- func QuotaMetric(machineType string) string
- func Region(zone string) (string, error)
- func RenderStarter(p StarterParams) ([]byte, error)
- func SanitizeProjectName(s string) string
- func WriteJSON(w io.Writer, outcomes []Outcome) error
- func WriteTable(w io.Writer, outcomes []Outcome) error
- type Deps
- type Gcloud
- type GcloudError
- type Options
- type Outcome
- type StarterParams
- type State
- type Status
- type Step
Constants ¶
const ( NetworkName = "provr-net" SubnetName = "provr-subnet" RouterName = "provr-router" NATName = "provr-nat" SubnetRange = "10.42.0.0/20" )
Network resource names and addressing.
const ( OperatorAccountID = "provr-operator" OperatorRoleID = "provrOperator" )
Operator identity names.
const ( TailscaleTag = "tag:provr" TailscaleSSHUser = "provr" )
Tailscale constants shared with the expose layer.
const HostAccountID = "provr-host"
HostAccountID is the account id of the role-less host service account.
Variables ¶
var ( ErrPermission = errors.New("permission denied") ErrAPIDisabled = errors.New("API not enabled") ErrNotFound = errors.New("not found") ErrNotAuthenticated = errors.New("not authenticated") )
Sentinel errors classifying gcloud failures; use errors.Is.
var BudgetThresholds = []float64{0.5, 0.9, 1.0}
BudgetThresholds are the alert thresholds (fractions of the budget).
var OperatorPermissions = []string{
"compute.disks.create",
"compute.disks.delete",
"compute.disks.get",
"compute.disks.list",
"compute.images.get",
"compute.images.getFromFamily",
"compute.images.list",
"compute.images.useReadOnly",
"compute.instances.create",
"compute.instances.delete",
"compute.instances.get",
"compute.instances.getSerialPortOutput",
"compute.instances.list",
"compute.instances.setLabels",
"compute.instances.setMetadata",
"compute.instances.start",
"compute.instances.stop",
"compute.machineTypes.get",
"compute.subnetworks.use",
"compute.zoneOperations.get",
}
OperatorPermissions is the custom role's permission set (sorted). It includes compute.zoneOperations.get (gcloud waits on create/start/stop operations), compute.images.getFromFamily (create uses --image-family) and compute.disks.list/get (gc lists detached disks, and re-checks one with `disks describe` before deleting it). Apply updates the role when the permissions differ.
var RequiredAPIs = []string{
"compute.googleapis.com",
"iam.googleapis.com",
"iamcredentials.googleapis.com",
"billingbudgets.googleapis.com",
}
RequiredAPIs are the GCP APIs provr needs enabled.
Functions ¶
func BudgetCreateCommand ¶
BudgetCreateCommand is the full gcloud command that creates the budget. It is used both for the real call and for the message to a billing admin.
func BudgetName ¶
BudgetName returns the display name of the project's budget.
func OperatorEmail ¶
OperatorEmail returns the operator service account email for a project.
func PolicySnippet ¶
func PolicySnippet() string
PolicySnippet returns the HuJSON fragment the user must merge into the tailnet policy. provr never edits the policy itself.
func QuotaMetric ¶
QuotaMetric returns the regional CPU quota metric for a machine type.
func RenderStarter ¶
func RenderStarter(p StarterParams) ([]byte, error)
RenderStarter renders the starter provr.yaml. It does not use a YAML library: the file is a text template with commented defaults.
func SanitizeProjectName ¶
SanitizeProjectName turns a directory name into a valid provr project name (^[a-z][a-z0-9-]{1,19}$).
Types ¶
type Deps ¶
type Deps struct {
// Gcloud runs the gcloud CLI.
Gcloud Gcloud
// Runner runs non-gcloud commands (e.g. docker compose config).
Runner execx.Runner
// HTTP is used for the Tailscale API; nil means http.DefaultClient with
// a 10s timeout.
HTTP *http.Client
// TailscaleBase is the Tailscale API base URL; empty means
// https://api.tailscale.com.
TailscaleBase string
// Getenv reads environment variables; nil means os.Getenv.
Getenv func(string) string
// Options are the user inputs.
Options Options
// State is shared mutable state between steps.
State *State
// Stdout receives user-facing instructions; never write secrets to it.
Stdout io.Writer
}
Deps bundles everything a step needs; tests substitute fakes.
type Gcloud ¶
type Gcloud struct {
Runner execx.Runner
Project string
Impersonate string
// Binary defaults to "gcloud" when empty.
Binary string
}
Gcloud runs the gcloud CLI through a Runner.
Every call adds --project=<Project>, --format=json, --quiet, and --impersonate-service-account=<Impersonate> when set. These flags are appended AFTER the caller's args.
type GcloudError ¶
type GcloudError struct {
// Args are the caller's args, without the appended common flags.
Args []string
ExitCode int
Stderr string
// Kind is one of the Err* sentinels, or nil when unclassified.
Kind error
// Permission is the missing permission name, when identified.
Permission string
// API is the disabled API name, when identified.
API string
}
GcloudError is a non-zero gcloud exit.
func (*GcloudError) Unwrap ¶
func (e *GcloudError) Unwrap() error
Unwrap returns the classification sentinel.
type Options ¶
type Options struct {
// GCPProject is the GCP project id (--gcp-project).
GCPProject string
// Zone is the compute zone, e.g. us-central1-a (--zone).
Zone string
// BudgetUSD is the monthly budget in USD (--budget-usd, default 150).
BudgetUSD int
// SkipBudget disables budget creation (--skip-budget).
SkipBudget bool
// ProjectName is the provr.yaml `project` value (--project-name).
ProjectName string
// RepoRoot is the directory where provr.yaml is written.
RepoRoot string
// MachineType comes from an existing provr.yaml or the config default;
// it is used only for the quota warning.
MachineType string
}
Options are the user-facing inputs of provr init.
type Outcome ¶
type Outcome struct {
Name string `json:"name"`
Status Status `json:"status"`
Detail string `json:"detail,omitempty"`
Duration time.Duration `json:"-"`
Millis int64 `json:"ms"`
}
Outcome is the recorded result of running one Step.
func Run ¶
Run executes steps in order and never stops early: a later step that depends on a failed one reports its own failure. One progress line is written to progress as each step finishes. Once ctx is canceled the remaining steps are recorded as failed with detail "canceled" without being called.
type StarterParams ¶
type StarterParams struct {
Project string
GCPProject string
Zone string
ComposeFile string // empty: no compose file detected
Expose map[string]int // service name -> container port
}
StarterParams are the inputs of the starter provr.yaml template.
type State ¶
type State struct {
// Account is the active gcloud account (the user: or serviceAccount:
// member form is derived by callers).
Account string
// BillingAccount is the linked billing account, "billingAccounts/XXXX-...".
BillingAccount string
// Region is derived from Options.Zone.
Region string
// ProjectNumber is the numeric project id; the Budget API filters by it.
ProjectNumber string
}
State is filled by earlier steps for later ones.
type Step ¶
type Step struct {
Name string
Check func(ctx context.Context) (Status, string, error)
Apply func(ctx context.Context) (string, error)
}
Step is one idempotent unit of `provr init`.
Check inspects the current state and returns:
- StatusExists: nothing to do (Apply is not called);
- StatusSkipped: deliberately not done, with the reason as detail;
- the empty status "": the thing is missing, so Apply is called.
Apply creates the thing and returns a human detail string; on success the step is recorded as StatusCreated. Any error from Check or Apply records StatusFailed with the error text as detail.
Detail strings are printed verbatim: they must never contain secret values.
func BudgetStep ¶
BudgetStep ensures a monthly budget with alerts exists on the project's billing account. Without billing permissions it fails with the exact command for a billing admin.
func NetworkStep ¶
NetworkStep ensures the provr VPC, subnet, Cloud Router and Cloud NAT exist and that the VPC has no ingress firewall rules.
Cloud NAT is outbound-only (image pulls, Tailscale); hosts get no external IP and provr never creates a firewall rule, so there is no public ingress. Cloud NAT costs roughly 1 USD/day while it exists.
func OperatorStep ¶
OperatorStep creates the operator service account, its custom role, the project binding and the caller's token-creator grant. It only VERIFIES impersonation; init itself runs with the caller's identity.
func PreflightStep ¶
PreflightStep verifies gcloud auth, project, billing, quota and Tailscale reachability. It never creates anything.
func StarterStep ¶
StarterStep writes a starter provr.yaml when none exists. An existing file is never modified.
func Steps ¶
Steps returns the init steps in execution order: preflight (auth, project, billing, quota, Tailscale reachability; fills State for later steps), apis, operator identity, host identity, network, budget, tailscale policy check, and the starter provr.yaml. The runner never stops early, so the starter config is written even when GCP setup failed.
func TailscaleStep ¶
TailscaleStep verifies the Tailscale OAuth credentials can mint keys for tag:provr and that the tailnet policy allows the tag and SSH access. It never changes the tailnet, so Check never returns "".