setup

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package 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

View Source
const (
	NetworkName = "provr-net"
	SubnetName  = "provr-subnet"
	RouterName  = "provr-router"
	NATName     = "provr-nat"
	SubnetRange = "10.42.0.0/20"
)

Network resource names and addressing.

View Source
const (
	OperatorAccountID = "provr-operator"
	OperatorRoleID    = "provrOperator"
)

Operator identity names.

View Source
const (
	TailscaleTag     = "tag:provr"
	TailscaleSSHUser = "provr"
)

Tailscale constants shared with the expose layer.

View Source
const HostAccountID = "provr-host"

HostAccountID is the account id of the role-less host service account.

Variables

View Source
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.

View Source
var BudgetThresholds = []float64{0.5, 0.9, 1.0}

BudgetThresholds are the alert thresholds (fractions of the budget).

View Source
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.

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

func BudgetCreateCommand(billingAccountID, project, projectNumber string, usd int) string

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

func BudgetName(project string) string

BudgetName returns the display name of the project's budget.

func Failed

func Failed(outcomes []Outcome) bool

Failed reports whether any outcome has StatusFailed.

func HostEmail

func HostEmail(project string) string

HostEmail returns the host service account email for a project.

func Member

func Member(account string) string

Member returns the IAM member string for a gcloud account.

func OperatorEmail

func OperatorEmail(project string) string

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

func QuotaMetric(machineType string) string

QuotaMetric returns the regional CPU quota metric for a machine type.

func Region

func Region(zone string) (string, error)

Region derives the region from a zone: us-central1-a -> us-central1.

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

func SanitizeProjectName(s string) string

SanitizeProjectName turns a directory name into a valid provr project name (^[a-z][a-z0-9-]{1,19}$).

func WriteJSON

func WriteJSON(w io.Writer, outcomes []Outcome) error

WriteJSON writes {"steps":[...],"ok":bool} indented by two spaces. Details are verbatim; callers must not put secret values in Outcome.Detail.

func WriteTable

func WriteTable(w io.Writer, outcomes []Outcome) error

WriteTable writes the summary table. Details are printed verbatim, so callers must not put secret values in Outcome.Detail.

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.

func (Gcloud) JSON

func (g Gcloud) JSON(ctx context.Context, out any, args ...string) error

JSON runs gcloud and decodes stdout into out. Empty stdout leaves out untouched.

func (Gcloud) Run

func (g Gcloud) Run(ctx context.Context, args ...string) ([]byte, error)

Run executes gcloud and returns stdout on exit 0, else a *GcloudError.

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

func (e *GcloudError) Error() string

Error implements error.

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

func Run(ctx context.Context, steps []Step, progress io.Writer) []Outcome

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 Status

type Status string

Status is the result of one init step.

const (
	StatusCreated Status = "created"
	StatusExists  Status = "exists"
	StatusSkipped Status = "skipped"
	StatusFailed  Status = "failed"
)

Step statuses.

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 APIsStep

func APIsStep(d Deps) Step

APIsStep enables the required GCP APIs.

func BudgetStep

func BudgetStep(d Deps) Step

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 HostStep

func HostStep(d Deps) Step

HostStep ensures the provr-host service account exists with no roles.

func NetworkStep

func NetworkStep(d Deps) Step

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

func OperatorStep(d Deps) Step

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

func PreflightStep(d Deps) Step

PreflightStep verifies gcloud auth, project, billing, quota and Tailscale reachability. It never creates anything.

func StarterStep

func StarterStep(d Deps) Step

StarterStep writes a starter provr.yaml when none exists. An existing file is never modified.

func Steps

func Steps(d Deps) []Step

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

func TailscaleStep(d Deps) Step

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

Jump to

Keyboard shortcuts

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