plugin

package
v0.0.0-...-8fc1da8 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 33 Imported by: 0

README

pkg/plugin/ — SC plugin runtime

The SC-core-side plugin runtime plus the shared plugin-side runtime library (runtime/) every SC plugin builds on: proto definitions, go-plugin lifecycle wrappers, MonitorProxy, pluginSession, SCCore callback server, PeerInvoke plumbing, and the handler scaffolding (runtime.NewContext, runtime.Settle, runtime.HarvestExports, runtime.ResourceInputForComputeProcess, runtime.DecodeInputs). Together with the dispatch wiring in pkg/clouds/pulumi/plugin_dispatch.go + plugin_preengine.go + plugin_sidecars.go, this is the base layer of the sc-plugin-architecture design.

Read the design doc first — this README assumes you have the architecture context, especially §3 "The two gRPC conversations" and Addendum C "state-storage and secrets-provider as plugins". For the trap catalogue collected across the five-plugin extraction wave, read forge/docs/design/2026-11-01/plugin-extraction-playbook/ before you start extracting a new one.

Package shape

pkg/plugin/
  proto/v1/plugin.proto         # SC plugin bus service definition (SCCloudPlugin + SCCore)
  proto/v1/plugin.pb.go         # generated — do not edit; regen with `make proto`
  proto/v1/plugin_grpc.pb.go    # ditto
  proto/README.md               # proto scope, buf config, regen command
  goplugin.go                   # hashicorp/go-plugin HandshakeConfig + Plugin impl
  client.go                     # SC-core-side: plugin.NewClient
  server.go                     # plugin-side: plugin.Serve
  monitor_proxy.go              # loopback gRPC ResourceMonitor forwarding to the real engine
  callback_server.go            # SC-core-side SCCore server (ResolveSecret, PeerInvoke)
  peer.go                       # plugin-side PeerInvoke client helper
  compute.go                    # ComputeResult builder (env vars, tpl extensions)
  vmhosts.go                    # VmHost builder
  publisher.go                  # progress Publisher routed to LogStream
  runtime/                      # plugin-side handler scaffolding (new in 2026-11-01)
    context.go                  #   NewContext + Settle generic
    wait.go                     #   go:linkname (*Context).wait — the drain
    engine.go                   #   LocalEngineAddress for background ctx.Log calls
    harvest.go                  #   HarvestExports — Secret-preserving output harvest
    compute.go                  #   ResourceInputForComputeProcess parent-env swap
    decode.go                   #   DecodeInputs[T] via scPlugin.InputsToPlain
  roundtrip_test.go             # unit test: handshake + Schema roundtrip
  provision_smoke_test.go       # unit test: plugin dials MonitorAddress + RegisterResource
  integration_test.go           # (build tag `integration`) real Pulumi engine Stage A
  vps_integration_test.go       # (build tag `integration`) real VPS Stage B
  testdata/
    echo-plugin/                # minimal Schema-only fixture plugin
    provision-plugin/           # plugin that registers a resource via monitor
    vps-marker-plugin/          # plugin that SSHes to a VPS via command:remote:Command
    state-store-plugin/         # plugin that provides a state-storage type (Step 4b)

What SC core registers on your plugin's behalf

Plugin advertises in SchemaResponse SC core wires it where
resource_types Dispatch table in pApi.PluginResourcesByType. In-engine, plugin.Provision called from configureResource's fall-through. Plugin dials MonitorProxy and calls RegisterResource.
state_store_types Pre-engine sidecar in pApi.InitStateStoreFuncByType. Plugin.InitStateStore called from pkg/clouds/pulumi/login.go to resolve backend_url + env vars.
secrets_provider_types Proto reserved; wiring pending (see Addendum C / Step 4b follow-up).
provider_types Proto reserved; wiring pending (plugin-owned pulumi:providers:<pkg> resources).
compute_processor_types Proto reserved; wiring pending.
registrar_types Proto reserved; wiring pending.
pulumi_plugins SC core's auto-pin reads this for the explicit-provider mechanism (04 §3).

Types with : are routed to plugins; bare names stay in-tree. The config-tier fall-through in pkg/api/read.go triggers on any type: string containing : and wraps the config in api.PluginFieldConfig.

Writing a plugin

The template at simple-container-com/sc-plugin-echo is the fastest start — clone it, swap in your cloud's config structs, keep the runtime wiring. The author guide at docs/docs/guides/plugin-authoring.md walks the full path.

The minimum viable binary — using the runtime library every production plugin builds on:

package main

import (
    "context"
    "os"

    hclog "github.com/hashicorp/go-hclog"

    plugin "github.com/simple-container-com/api/pkg/plugin"
    scpluginv1 "github.com/simple-container-com/api/pkg/plugin/proto/v1"
    "github.com/simple-container-com/api/pkg/plugin/runtime"
)

type myPlugin struct {
    scpluginv1.UnimplementedSCCloudPluginServer
    progress *plugin.Publisher
}

func (p *myPlugin) Schema(_ context.Context, _ *scpluginv1.SchemaRequest) (*scpluginv1.SchemaResponse, error) {
    return &scpluginv1.SchemaResponse{
        PluginVersion: "my-plugin-0.1.0",
        ResourceTypes: []string{"mycloud:storage:Bucket"},  // MUST contain `:` for routing
    }, nil
}

func (p *myPlugin) Provision(stdctx context.Context, req *scpluginv1.ProvisionRequest) (resp *scpluginv1.ProvisionResponse, err error) {
    // runtime.NewContext opens one sdk.Context against req.Header.MonitorAddress
    // and defers a drain-then-close via runtime.Settle. WithLocalEngineFallback
    // keeps background ctx.Log calls from panicking when the header has no
    // engine address.
    rctx, err := runtime.NewContext(stdctx, req.GetHeader(), runtime.WithLocalEngineFallback(p.progress))
    if err != nil {
        return nil, err
    }
    defer runtime.Settle(rctx, &resp, &err)

    // ... register cloud resources against rctx.Pulumi ...
    // ... rctx.Pulumi.Export(key, out) for every value the parent should see ...

    outputs, err := runtime.HarvestExports(stdctx, rctx.Pulumi)
    if err != nil {
        return nil, err
    }
    return &scpluginv1.ProvisionResponse{Urn: "...", Outputs: outputs}, nil
}

func main() {
    publisher := plugin.NewPublisher()
    plugin.Serve(plugin.ServerConfig{
        Impl:   &myPlugin{progress: publisher},
        Logger: hclog.New(&hclog.LoggerOptions{
            Name:   "my-plugin",
            Level:  hclog.Warn,
            Output: os.Stderr,
        }),
    })
}

Three invariants runtime.* enforces for you — each has caused a live regression at least once (see the extraction playbook):

  • Drain before you return. runtime.Settle runs (*Context).wait via go:linkname before closing the SDK context. Returning without draining drops every pending RegisterResource and SC core plans a destroy of each state entry on the next apply. (Playbook trap 7, 2026-10-27.)
  • Preserve the Secret flag on exports. runtime.HarvestExports calls internals.UnsafeAwaitOutput and copies .Secret into InputValue.Secret. Dropping it lands the value plaintext in the parent stack root. (Playbook trap 11, 2026-10-31.)
  • Export cross-plugin bridge Outputs. If your plugin wraps a PeerInvoke call in an ApplyT, you MUST rctx.Pulumi.Export(unique-key, urnOut) the resulting Output. Callers that discard the ResourceOutput let Pulumi dead-strip the orphan chain — the PeerInvoke never fires and the DNS record silently never registers. (Playbook trap 15, 2026-11-01.)

Build:

go build -o my-plugin ./cmd/my-plugin

Operator configuration (server.yaml):

plugins:
  my-plugin:
    path: /opt/sc-plugins/my-plugin
    sha256: abc123...  # optional; verified at every spawn

resources:
  resources:
    staging:
      resources:
        my-bucket:
          type: mycloud:storage:Bucket

Extracting a driver from pkg/clouds/pulumi/<cloud>/ — checklist

The point of all of this is to let a driver live in its own repo. Five drivers have come out this way so far (cloudflare, yandex, cloudru, mongodb, aws); the next milestone is gcp. The playbook at forge/docs/design/2026-11-01/plugin-extraction-playbook/ is the canonical trap-by-trap guide — read it alongside this checklist.

Steps:

  • Decide the plugin's advertised type names. Add : in each (required by the config-tier fall-through). Keep the type strings byte-identical to what the current in-tree driver passes to Pulumi RegisterResource — see 04-no-destroy-invariant.md §1.2. For existing drivers (migration path), use the explicit-provider mechanism from 04 §3 to keep provider URNs byte-identical.
  • Create a new repo named simple-container-com/sc-plugin-<cloud>. Nested-module layout: /api (config structs, no Pulumi SDK) + /plugin (the binary — may vendor whatever typed Pulumi SDKs the driver needs). Pattern per 03 §2.2.
  • Author the plugin. Implement Schema + whatever RPCs match your advertised types. For resource plugins, Provision dials MonitorAddress and calls RegisterResource with the exact type token Pulumi expects (e.g. cloudflare:index/record:Record — NOT sc-cloudflare:record:Record).
  • Use pkg/plugin/runtime for the handler scaffolding — do NOT re-copy the per-plugin drain.go / pulumiContextFromHeader / harvest triad from an older plugin. Every handler starts with rctx, err := runtime.NewContext(stdctx, req.GetHeader(), runtime.WithLocalEngineFallback(p.progress)) + defer runtime.Settle(rctx, &resp, &err). Returning outputs? runtime.HarvestExports. ComputeProcess? runtime.ParentInfoFromRequest + runtime.ResourceInputForComputeProcess. Decoding typed inputs? runtime.DecodeInputs[T]. These helpers encode the invariants in playbook traps 7, 11, 12, 14 — rolling your own re-earns the bugs.
  • Lift the current in-tree driver code from pkg/clouds/pulumi/<cloud>/ into the plugin's /plugin/internal/. Rewrite the entry points from the pApi.Register*() init() pattern to SCCloudPluginServer method implementations. Preserve resource names and parent chains byte-identically.
  • Preserve the config-tier schema. Lift pkg/clouds/<cloud>/ structs into the plugin repo's /api module. SC core imports those for cmd/schema-gen per D3.
  • Add a URN-contract test in the plugin's own repo, mirroring pkg/clouds/pulumi/cloudflare/urn_contract_test.go (PR #479's seed) — asserts resource/provider names match a documented pattern. One failed byte-match blocks the plugin's release.
  • Add fixture-based migration test — a scratch stack deployed by pre-split sc, then pulumi preview --expect-no-changes with the plugin-era sc. Required gate per 04 §4.
  • Cut v1.0.0 — GitHub release with signed binary + sha256sums.txt.
  • Update SC core — remove _ "github.com/simple-container-com/api/pkg/clouds/pulumi/<cloud>" blank import from pkg/clouds/pulumi/init.go; delete the subtree; update go.mod; measure new make build link RSS to verify shrinkage.

For composite drivers (kubernetes, k3s, mongodb that compose other clouds), add:

  • PeerInvoke RPC (proto wiring pending — composite plugin asks SC core to invoke on another plugin, per D8).

Shipped surfaces (what the shipped plugins actually use)

As of 2026-11-13: sc-plugin-{aws,cloudflare,cloudru,gcp,mongodb,mws,yandex} plus sc-plugin-echo as the template.

Surface Plugin RPC Shipped example
State-store InitStateStore aws s3-bucket, yandex yc-object-storage, gcp gcp-bucket
Secrets-provider InitSecretsProvider aws aws-kms, yandex yc-kms, gcp gcp-kms + gcp-secrets-manager
Provider Provider aws, yandex, cloudru, gcp, mws providers; mongodb Atlas provider
Resource / Template Provision every resource/template token in supported-resources.md tagged "plugin"
Compute processor ComputeProcess mongodb uses: fan-out (MONGO_URI/USER/PASSWORD), aws s3-bucket consumer env, gcp gcp-bucket/gcp-redis/gcp-pubsub consumer env
Registrar ProvisionRegistrar, NewDnsRecord, NewOverrideHeaderRule, ProvisionDomainForEndpoint cloudflare; aws + gcp delegate DNS to the operator-configured registrar via PeerInvoke
PreDestroy PreDestroy mongodb drops databases named in -service-user outputs before Pulumi destroys the cluster
VM driver VmHosts yandex yandex-vm, cloudru cloudru-evolution-vm
LogStream LogStream (server-stream) every plugin's scPlugin.Publisher routed to the engine's progress channel
Peer invoke SCCore.PeerInvoke (plugin → core → peer plugin) aws delegates NewDnsRecord, NewOverrideHeaderRule, ProvisionDomainForEndpoint to cloudflare without a Go-module import (D8)

Not yet wired

What Current state Blocker
Fingerprint streamed health Not yet in proto Server-streaming RPC per Nomad pattern. Health inference today still happens inside SC core via pkg/clouds/pulumi/healthcheck.go.

The two-phase plugin lifecycle (pre-engine + in-engine) + the SCCore callback server (ResolveSecret / ResolveCredential / PeerInvoke) cover everything the five extracted plugins needed.

Testing

# Unit tests — fast, no external deps.
go test ./pkg/plugin/...

# Stage A — real Pulumi engine, local-fs backend. Requires `pulumi` CLI on PATH.
go test -tags integration -run TestIntegration_PluginRegistersAgainstRealEngine ./pkg/plugin/...

# Stage B — real VPS deploy via command:remote:Command. Requires SC_PLUGIN_VPS_* env vars.
SC_PLUGIN_VPS_HOST=... SC_PLUGIN_VPS_USER=... SC_PLUGIN_VPS_PASSWORD=... \
  go test -tags integration -run TestIntegration_PluginTouchesVPS ./pkg/plugin/...

The integration tests are build-tagged so plain make check + go test ./... stay fast; CI's dedicated integration job (which already has pulumi installed per commit 20a04303) picks them up with -tags integration.

Documentation

Overview

Package plugin wires hashicorp/go-plugin's lifecycle to the sc_plugin.proto service, providing both the SC-core-side client wrapper and the plugin-side server registration helper.

See forge/docs/design/2026-10-24/sc-plugin-architecture/03-architecture.md §6 for lifecycle details, §6.3 for credential passing, §6.4 for the health channel, and 06-decisions.md D2 for why hashicorp/go-plugin is the transport.

Index

Constants

View Source
const DefaultCacheRoot = "~/.sc/plugins"

DefaultCacheRoot is where SC caches fetched plugin binaries. Can be overridden per-call to ResolveBinaryPath; the default follows the Terraform-ish convention most operators already have in muscle memory.

View Source
const PluginName = "sc_cloud_plugin"

PluginName is the single plugin.Plugin entry every SC cloud plugin advertises. Plugins that eventually need to serve multiple distinct interfaces over the same binary will register additional entries alongside this one.

Variables

View Source
var Handshake = hplugin.HandshakeConfig{
	ProtocolVersion:  1,
	MagicCookieKey:   "SC_PLUGIN_MAGIC_COOKIE",
	MagicCookieValue: "sc-plugin-v1-c2ltcGxlLWNvbnRhaW5lcgo",
}

Handshake is the magic-cookie guard every sc-plugin-<cloud> binary must declare. It is NOT a security mechanism — go-plugin's own README is explicit on that point — it is a UX guard that makes a plugin binary print a friendly error instead of serving when run by hand without SC core setting the env var. Mutual TLS (AutoMTLS) provides the real transport integrity.

Functions

func AwaitAll

func AwaitAll(ctx context.Context, outputs ...sdk.Output) error

AwaitAll blocks until every passed output has resolved, and is the generic form of the "do not return before your outputs resolve" rule for a handler that has no URN it needs the value of — it just needs the registrations to have landed.

An output that resolves UNKNOWN (a preview, or a value derived from something not yet created) satisfies this: unknown is a resolution, and refusing it would make every plugin fail `sc preview`.

func AwaitURN

func AwaitURN(ctx context.Context, res sdk.Resource) (string, error)

AwaitURN blocks until the engine has assigned res its URN, and returns it.

This is the call that makes a resource real before the handler returns, and the one that makes a ResourcePropertyRef answerable: core resolves a ref by asking the engine for that URN's state, which it can only answer once the resource's step has completed. Awaiting the URN is exactly what waits for that.

A URN is known even during a preview — the engine assigns it at RegisterResource, before anything is created — so an unknown URN means the resource was never registered, and that is reported as an error rather than an empty string.

func AwaitURNs

func AwaitURNs(ctx context.Context, resources ...sdk.Resource) ([]string, error)

AwaitURNs is AwaitURN over several resources, in order, and is what a handler wanting the dependency list for a VmHostFacts calls.

func BuildVmHosts

func BuildVmHosts(hosts ...*VmHostBuilder) (*scpluginv1.VmHostsResponse, error)

BuildVmHosts builds every host and assembles the response.

It refuses an empty set for the same reason core does: a VmHosts call that returns no hosts has reported success for a `type: vm` resource that produced no machines, and the deploy would then fail much later on something that looks unrelated.

func CachedSchema

func CachedSchema(spec api.PluginSpec, cacheRoot string) (*scpluginv1.SchemaResponse, bool)

CachedSchema returns the schema recorded for (repository, version) by a previous WriteCachedSchema call, or (nil, false) if the cache has no entry (fresh install, path: spec, cache cleared, cache file corrupt). A hit means the pre-parse can skip the plugin spawn entirely.

func Gibibytes

func Gibibytes(quantity, field string) (int, error)

Gibibytes parses one of SC's DSL size quantities ("4Gi", "60Gi") into a whole number of GiB. Every VM-plugin needs this: cloud APIs that take disk / memory arguments in integer GiB are the common case, and SC's own schema spells the value as a human quantity string.

Refuses a fractional value rather than rounding. Rounding a flavour-filter down matches nothing — reads to an operator as "the region has no such machine". Rounding a disk size silently gives the operator a disk they did not ask for. Neither is a useful failure mode.

`field` is the server.yaml field name to name in the error ("size.disk", "size.memory").

func InputValueToPlain

func InputValueToPlain(v *scpluginv1.InputValue) (any, bool)

InputValueToPlain is InputsToPlain for one value. The bool is false for an InputValue with no value set, which the caller should treat as absent (inside a list it decodes as nil, keeping the element's position).

func InputsToPlain

func InputsToPlain(inputs map[string]*scpluginv1.InputValue) map[string]any

InputsToPlain turns a request's InputValue map back into plain Go values — strings, bools, float64, int64, []byte, map[string]any and []any — ready for a YAML or JSON round-trip into the plugin's own config struct. It is the inverse of what core does when it serialises a resource's config onto the bus, nested objects and lists included.

Output and secret references are passed through as their reference strings; a plugin that accepts them resolves them itself (ResolveStringOutput / ResolveSecret).

func MarshalPeerPayload

func MarshalPeerPayload(resp proto.Message) ([]byte, error)

MarshalPeerPayload is a convenience for a PeerDispatcher implementation: marshal a response message into the bytes PeerInvokeResponse expects.

func OutputLiteral

func OutputLiteral(value string) *scpluginv1.OutputValue

OutputLiteral is a fact the plugin already knows: a byo host's address, an empty key password, a host key pinned in the operator's config.

func OutputRefTo

func OutputRefTo(ctx context.Context, res sdk.Resource, property string) (*scpluginv1.OutputValue, error)

OutputRefTo names a property of a resource the plugin registered, for core to resolve against the engine once it exists.

`property` is the PROVIDER's output property name as the Pulumi package spells it (`externalIpv4Address`, `privateKeyOpenssh`, `accessIpV4`) — not an SC-level name, and not the Terraform snake_case spelling. Getting it wrong surfaces core-side as a resolution error naming the properties the resource does have, which is the fastest way to find the right one.

Blocks until the resource's URN is known; see AwaitURN for why that is required rather than merely tidy.

func PlainToInputValue

func PlainToInputValue(v any) *scpluginv1.InputValue

PlainToInputValue maps one decoded value onto the bus's InputValue. Returns nil for a nil / null input — the caller then omits the key, which a plugin reads back as the zero value (same semantics as the null meant). Used recursively for nested maps and lists.

func PlainToInputs

func PlainToInputs(cfg any) map[string]*scpluginv1.InputValue

PlainToInputs is the inverse of InputsToPlain: it serialises a Go value (typed struct or map[string]any) into the plugin bus's InputValue map via a JSON round-trip. Nested objects and lists travel as InputMap / InputList. SC core uses this to marshal both plain-resource configs (serializeConfigToInputs in plugin_sidecars.go — a thin wrapper) and template-conversion stack configs (pkg/stackread's ConvertStackConfig dialler).

The output is deterministic for a given input: JSON numbers return as doubles; a plugin decoding into an int field receives the integral value through yaml.v3's number coercion.

func PluginSet

PluginSet is the plugin-side PluginSet (Impl set, no Peer). Kept for Serve() callers in plugin binaries.

func PulumiContext

func PulumiContext(ctx context.Context, h *scpluginv1.RequestHeader) (*sdk.Context, func(), error)

PulumiContext opens a pulumi.Context against the monitor address core put in the request header, and returns a close function the handler must defer.

Call it once per RPC and let it close at the end of that RPC. A *sdk.Context is not reusable across calls and neither is anything built inside one: an sdk.ProviderResource cannot cross context boundaries, so a plugin that needs a provider must build it inside the same handler that registers resources against it. Re-registering the provider per call is correct and cheap — the URN stays byte-identical (same name, same version), so the engine sees the same resource and the no-destroy invariant holds.

Await everything you care about BEFORE the deferred close runs; see AwaitURN.

func RehydrateResource

func RehydrateResource(ctx *sdk.Context, urnStr string) (sdk.Resource, error)

RehydrateResource returns a live sdk.Resource handle for a resource a plugin registered, so core can put it in DependsOn.

The type token and name come out of the URN itself rather than from the plugin, so core never has to know what resource types a plugin's cloud has. The handle is deliberately a CustomResourceState and nothing more: core wants the ordering edge, not the properties (those travel as OutputRefs, which this call cannot serve — see the Property comment above).

func ResolveBinaryPath

func ResolveBinaryPath(spec api.PluginSpec, cacheRoot string) (string, error)

ResolveBinaryPath resolves a PluginSpec to a concrete executable binary path on disk. Supported modes:

  • spec.Path set → return it verbatim (dev / air-gapped operator path).
  • spec.Source set with type "github-release" → download from github.com/<repo>/releases/download/<version>/<binary>, verify sha256, cache under cacheRoot/<repo>/<version>/, chmod +x, return.

If spec.SHA256 is set, it is enforced. If not, the fetcher looks for a sha256sums.txt asset in the release and uses the matching entry.

cacheRoot may begin with "~" and is expanded to the user's home dir.

func ResolveStringOutput

func ResolveStringOutput(ctx *sdk.Context, ref OutputRef, deps []sdk.Resource) (sdk.StringOutput, error)

ResolveStringOutput turns a plugin's OutputRef into a real sdk.StringOutput that core can hand to remote.Connection, ready.go or any other resource it builds.

`deps` is attached to the output when the value is still unknown, so that a preview keeps the dependency edge it would otherwise lose.

Three properties of the result, all of which matter:

  • An unknown property stays UNKNOWN. In preview a machine's address does not exist yet; resolving it to "" would have core preview a remote.Command against the empty string and report a diff that is not the one that will happen.
  • A secret property stays SECRET. The engine marshals every invoke return with KeepSecrets hardcoded on (source_eval.go), so the flag does survive the round trip — but callers holding key material should still wrap with sdk.ToSecret unconditionally rather than trust that, because it is one marshalling option in a module we do not control and the failure mode is a private key printed in a preview and archived in a CI log.
  • A missing property is an ERROR naming what the resource does have. A typo in a plugin's property name would otherwise present as an empty string that silently configures SSH with no key.

func SecretLiteral

func SecretLiteral(value string) *scpluginv1.OutputValue

SecretLiteral is OutputLiteral for a value that must not reach a log or the state file in plain text. Core wraps it with pulumi.ToSecret.

func SecretRefTo

func SecretRefTo(ctx context.Context, res sdk.Resource, property string) (*scpluginv1.OutputValue, error)

SecretRefTo is OutputRefTo for a property that must stay secret once resolved.

func Serve

func Serve(cfg ServerConfig)

Serve is the entry point every sc-plugin-<cloud> binary's main() calls. It blocks until the host disconnects.

Example (plugin side):

func main() {
    plugin.Serve(plugin.ServerConfig{
        Impl:   &awsPlugin{},
        Logger: hclog.New(&hclog.LoggerOptions{Name: "sc-plugin-aws"}),
    })
}

The host side (SC core) calls plugin.NewClient to spawn and dial this.

func UnmarshalPeerPayload

func UnmarshalPeerPayload(payload []byte, into proto.Message) error

UnmarshalPeerPayload is the matching convenience for a PeerDispatcher: unmarshal the request payload into a typed message chosen by rpc_name.

func VerifySHA256

func VerifySHA256(spec api.PluginSpec) error

VerifySHA256 validates spec.SHA256 against the binary at spec.Path when a hash is configured. An empty hash is a warn-and-proceed (D10) — the smoke accepts this; production should treat it as an error. ResolveBinaryPath already checks the hash for github-release fetches on cache miss; this helper covers the path: mode where the operator points at a local binary.

func WriteCachedSchema

func WriteCachedSchema(spec api.PluginSpec, cacheRoot string, schema *scpluginv1.SchemaResponse) error

WriteCachedSchema persists schema for (repository, version). Best-effort — a write failure logs and returns nil, so the next parse just re-fetches instead of failing the deploy.

Types

type BrokerAware

type BrokerAware interface {
	SetBroker(*hplugin.GRPCBroker)
}

BrokerAware is the opt-in interface a plugin's Impl can implement to capture SC's go-plugin broker at GRPCServer time, so handlers can later call pkg/plugin/peer.go NewPeerClient to dial SC core's SCCore endpoint. Terraform-provider pattern — see the sc-plugin-aws composite demo.

Non-composite plugins (cloudflare, yandex, cloudru) leave this unimplemented and are unaffected: GRPCServer below type-asserts and skips the SetBroker call when the Impl does not satisfy it.

(Re-added here after PR #510 accidentally removed the BrokerAware shipped in #509. Without it NewPeerClient on the plugin side errors with "nil broker" — the broker never reached the handler, and the registrar-via-PeerInvoke bridge (D8) cannot work.)

type CallbackServer

type CallbackServer struct {
	scpluginv1.UnimplementedSCCoreServer

	// Peer dispatches a PeerInvoke to another plugin via SC core's
	// loaded-plugins registry. Nil → PeerInvoke returns Unimplemented.
	Peer PeerDispatcher

	// Secret and Credential are the Vault-pattern callbacks. Nil in
	// Phase 1e; the proto fields and this server slot are reserved so a
	// future Addendum can wire them without reshaping the server.
	Secret     SecretResolver
	Credential CredentialResolver
}

CallbackServer implements SCCoreServer. SC core registers one of these per spawned plugin, exposed over the hashicorp/go-plugin broker at the stream id passed in RequestHeader.sccore_broker_stream.

Fields are set per-plugin by NewCallbackServer so lookups into the plugin registry route to the right loader context. Nil fields answer Unimplemented — which is correct for ResolveSecret/ResolveCredential in Phase 1e and lets us ship PeerInvoke without the Vault pattern's callback plumbing.

func NewCallbackServer

func NewCallbackServer(peer PeerDispatcher) *CallbackServer

NewCallbackServer builds the SCCore impl SC core serves per-plugin. Pass only Peer today; Secret/Credential are reserved and ignored.

func (*CallbackServer) PeerInvoke

PeerInvoke is the composite-plugin broker. Looks the target plugin up by name and dispatches rpc_name against its client stub.

func (*CallbackServer) ResolveSecret

ResolveSecret / ResolveCredential — kept at Unimplemented until the Vault pattern is wired (Addendum R follow-up). The proto field + this server slot are reserved so adding them later is a behaviour change, not a wire change.

type Client

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

Client is a connected handle to a running cloud plugin. The caller SHOULD defer Close() on it; Close is idempotent.

func NewClient

func NewClient(cfg ClientConfig) (*Client, error)

NewClient spawns a plugin binary and dials its gRPC server. It validates the handshake (magic cookie + protocol version) and returns a Client that speaks the SCCloudPlugin service. The caller is expected to Close() when done.

func NewClientWithStub

func NewClientWithStub(stub scpluginv1.SCCloudPluginClient) *Client

NewClientWithStub wraps an already-connected (or fake) gRPC stub, without spawning a plugin binary. It exists so callers outside this package can exercise the SC-core-side dispatch wrappers — the pluginRegistrar sidecars in particular — against a stub, which is otherwise impossible because `stub` is unexported. Close() on such a Client is a no-op: there is no subprocess.

func ResolveAndSchema

func ResolveAndSchema(
	ctx context.Context,
	name string,
	spec api.PluginSpec,
	cacheRoot string,
	logger hclog.Logger,
	peer PeerDispatcher,
) (cli *Client, schema *scpluginv1.SchemaResponse, err error)

func (*Client) Close

func (c *Client) Close()

Close terminates the plugin subprocess. Safe to call more than once.

func (*Client) ComputeProcess

ComputeProcess calls through to the plugin's ComputeProcess RPC.

func (*Client) ConvertStackConfig

ConvertStackConfig asks the plugin to turn a merged StackConfig* into its typed Input. SC core dials this when api.IsPluginOwnedType(templateType) returns a binding whose PluginName matches this Client's plugin — see pkg/api/client.go's Prepare*ForDeploy branches.

func (*Client) InitSecretsProvider

InitSecretsProvider calls through to the plugin's InitSecretsProvider RPC.

func (*Client) InitStateStore

InitStateStore calls through to the plugin's InitStateStore RPC.

func (*Client) LogStream

LogStream opens the plugin's progress-event stream. SC core calls this once per plugin after Schema() returns, then forwards each event to its logger. The stream naturally ends when the plugin exits OR when the caller cancels ctx. Caller is responsible for draining in a goroutine.

func (*Client) NewDnsRecord

NewDnsRecord calls through to the plugin's NewDnsRecord RPC (Phase 1b).

func (*Client) NewOverrideHeaderRule

NewOverrideHeaderRule calls through to the plugin's NewOverrideHeaderRule RPC (Phase 1b).

func (*Client) PluginInvoke

PluginInvoke calls through to the plugin's PluginInvoke RPC — the capability dispatcher (sc-components-plugin-peer-invoke slice). SC core's peer broker invokes this when forwarding a cross-plugin capability call; the broker enforces capability advertisement before the call is made, so a plugin receiving this RPC can trust that its SchemaResponse.peer_capabilities list the capability.

func (*Client) PreDestroy

PreDestroy calls through to the plugin's PreDestroy RPC.

func (*Client) Provider

Provider calls through to the plugin's Provider RPC — registers the explicit pulumi:providers:<pkg> resource against the shared Pulumi monitor.

func (*Client) Provision

Provision calls through to the plugin's Provision RPC — the main workhorse.

func (*Client) ProvisionDomainForEndpoint

ProvisionDomainForEndpoint calls through to the plugin's ProvisionDomainForEndpoint RPC (Phase 1b).

func (*Client) ProvisionRegistrar

ProvisionRegistrar calls through to the plugin's ProvisionRegistrar RPC.

func (*Client) SccoreBrokerStream

func (c *Client) SccoreBrokerStream() uint32

SccoreBrokerStream is the go-plugin broker stream id SC core serves its SCCore endpoint on for this plugin. Zero if the Client was built from a stub (test harnesses) rather than from a real plugin spawn. Sidecars include this in RequestHeader.sccore_broker_stream so the plugin knows what to dial for PeerInvoke / ResolveSecret / ResolveCredential.

func (*Client) Schema

Schema returns the plugin's advertised schema. Called once at SC core startup after a plugin is spawned, before any dispatch to that plugin.

func (*Client) VmHosts

VmHosts calls through to the plugin's VmHosts RPC (Phase 1d) — the plugin creates the machines of one `type: vm` resource and returns reachable hosts.

The returned facts carry URN references rather than values for anything the plugin does not know yet; pkg/clouds/pulumi/vm turns them back into Outputs with pkg/plugin/outputref.go.

type ClientConfig

type ClientConfig struct {
	// Path to the plugin binary on disk. The caller is responsible for
	// having verified its SHA256 (see 06-decisions.md D10) and for having
	// made it executable.
	Path string

	// Managed makes the hashicorp/go-plugin runtime track the client so
	// plugin.CleanupClients() tears it down on SC core exit — important to
	// avoid zombie child processes if SC core itself is killed with SIGKILL.
	// Default: true. Only set to false in tests that want to retain a
	// crash-dump of the plugin's output.
	Managed bool

	// Logger passed to the plugin via stdout/stderr capture (hashicorp/go-plugin
	// prefixes every captured line with the plugin's binary path). Required.
	Logger hclog.Logger

	// Peer, if set, is the dispatcher SC core's SCCore endpoint uses to
	// route this plugin's PeerInvoke calls to another loaded plugin's
	// SCCloudPlugin RPC. Nil means PeerInvoke answers Unimplemented —
	// safe for every non-composite plugin and for test harnesses.
	Peer PeerDispatcher
}

ClientConfig describes how SC core spawns a cloud plugin and makes RPCs against it. Discovery (lock file, user cache, auto-fetch) lives in a separate file; this type assumes the Path on disk is already resolved.

type ComputeResultBuilder

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

ComputeResultBuilder accumulates the env + tpl-extension mutations a ComputeProcess handler wants SC core to apply back into the live `pApi.ComputeContextCollector`. Build validates and returns the proto response, which the sidecar unpacks and dispatches.

func NewComputeResult

func NewComputeResult() *ComputeResultBuilder

NewComputeResult starts a response. Pass the URN of the resource the handler registered (if any) via Urn below; otherwise the response's `urn` field stays empty, same as a v1 compute processor.

func (*ComputeResultBuilder) Build

Build returns the response, or the first error the chain hit.

func (*ComputeResultBuilder) DependencyTplExtension

func (b *ComputeResultBuilder) DependencyTplExtension(depName, resName string, values map[string]string) *ComputeResultBuilder

DependencyTplExtension queues values the consuming stack can interpolate via `${dependency:<depName>.<resName>.<key>}`. Mirrors pApi.ComputeContextCollector.AddDependencyTplExtension.

func (*ComputeResultBuilder) EnvVar

func (b *ComputeResultBuilder) EnvVar(name, value, resType, resName, stackName string) *ComputeResultBuilder

EnvVar queues an env var to inject into downstream compute.

resType/resName/stackName are the metadata pApi.ComputeEnvVariable records: the consuming compose service / lambda / cloud-run reads the var only when it is scoped to the stack it is deploying into. Getting one of these wrong silently sends the var to the wrong consumer.

func (*ComputeResultBuilder) ResourceTplExtension

func (b *ComputeResultBuilder) ResourceTplExtension(resName string, values map[string]string) *ComputeResultBuilder

ResourceTplExtension queues values the consuming stack can interpolate via `${resource:<resName>.<key>}`. Mirrors pApi.ComputeContextCollector.AddResourceTplExtension.

func (*ComputeResultBuilder) SecretEnvVar

func (b *ComputeResultBuilder) SecretEnvVar(name, value, resType, resName, stackName string) *ComputeResultBuilder

SecretEnvVar is EnvVar for a value that must not reach a log or state file in plain text. Core wraps it in pulumi.ToSecret before injection.

func (*ComputeResultBuilder) Urn

Urn names the resource the compute processor is reporting against, if any. The sidecar echoes this back in the ResourceOutput ref so downstream config interpolation can key against the right URN.

type CredentialResolver

type CredentialResolver interface {
	ResolveCredential(ctx context.Context, req *scpluginv1.ResolveCredentialRequest) (*scpluginv1.ResolveCredentialResponse, error)
}

type EngineProxy

type EngineProxy struct {
	pulumirpc.UnimplementedEngineServer
	// contains filtered or unexported fields
}

EngineProxy is a loopback gRPC Engine server SC core stands up alongside its MonitorProxy so a plugin-side pulumi.NewContext(RunInfo{EngineAddr:…}) gets a real engine conn. Without it, logState.engine is nil, and any pulumi-aws driver that calls ctx.Log.Warn in a background goroutine (resolveDeployImageRef, provider conflict paths) panics with `invalid memory address or nil pointer dereference` and exits the plugin process — which SC core's gRPC client sees as `error reading from server: EOF`.

The engine addr is NOT in os.Environ for an inline-RunFunc program, so `os.Getenv("PULUMI_ENGINE")` returns empty inside SC core. The engine client is held in pctx.state.engine; this proxy extracts it via the same reflect+unsafe path monitor_proxy.go uses and republishes it as loopback TCP for the plugin's own gRPC dial.

func NewEngineProxy

func NewEngineProxy(ctx *pulumi.Context, logger hclog.Logger) (*EngineProxy, error)

NewEngineProxy extracts the live EngineClient from a running pulumi.Context and wraps it in a proxy server dialable over gRPC. The returned Addr() is what SC core puts in RequestHeader.EngineAddress on each plugin.Provision call.

func (*EngineProxy) GetRootResource

GetRootResource forwards — some SDK paths probe it.

func (*EngineProxy) Log

Log forwards to the real Pulumi engine — the hot path plugins reach via ctx.Log.{Debug,Info,Warn,Error}.

func (*EngineProxy) Serve

func (p *EngineProxy) Serve() (string, func(), error)

Serve binds a loopback TCP listener, starts the gRPC server, and returns its address. Caller MUST call Stop() when done. Same transport/threat model as monitor_proxy.go — plaintext on 127.0.0.1 by Pulumi SDK's requirement.

func (*EngineProxy) SetRootResource

SetRootResource forwards — not currently used by plugins, kept for completeness.

type MonitorProxy

type MonitorProxy struct {
	pulumirpc.UnimplementedResourceMonitorServer
	// contains filtered or unexported fields
}

MonitorProxy is a loopback gRPC ResourceMonitor server that SC core stands up inside its Pulumi inline RunFunc. Each incoming RegisterResource from a plugin is forwarded verbatim to the REAL Pulumi monitor the engine handed SC core. This solves the gap between SC core's pulumi.Context (which holds the live monitor client as an unexported field) and the plugin subprocess (which can only reach the engine over gRPC).

Why a proxy and not a public API: pulumi/sdk/v3 v3.245.0 does not expose Context.MonitorAddr — NewContext dials with info.MonitorAddr and discards it. Until Pulumi exposes an accessor, SC core either (a) runs this proxy, or (b) switches to the "plugin returns resource descriptions; SC core registers" model (option (d) in D1a). The proxy keeps the plugin side architecture clean — plugins talk real Pulumi gRPC — and keeps the hack localised to one file in pkg/plugin.

The reflect+unsafe path to the monitor client is confined to monitorFromContext below. If a future Pulumi SDK version renames contextState.monitor, this will panic at startup, which is caught by the roundtrip test — not a prod hazard.

func NewMonitorProxy

func NewMonitorProxy(ctx *pulumi.Context, logger hclog.Logger) (*MonitorProxy, error)

NewMonitorProxy extracts the live ResourceMonitorClient from a running pulumi.Context and wraps it in a proxy server that can be dialed over gRPC. The returned Addr() is what SC core puts in RequestHeader.MonitorAddress on each plugin.Provision call.

IMPORTANT: the proxy's lifetime must match the inline RunFunc's lifetime. Serve() runs in a goroutine until Stop() is called; call Stop() in the RunFunc's defer.

func (*MonitorProxy) Call

Call forwards — resource-method invocations.

func (*MonitorProxy) Invoke

Invoke forwards — data-source lookups (e.g. LookupZone) use this.

func (*MonitorProxy) ReadResource

ReadResource forwards — resource imports / reads.

func (*MonitorProxy) RegisterResource

RegisterResource forwards to the real Pulumi monitor. This is the one method plugins currently exercise.

func (*MonitorProxy) RegisterResourceOutputs

func (p *MonitorProxy) RegisterResourceOutputs(ctx context.Context, req *pulumirpc.RegisterResourceOutputsRequest) (*emptypb.Empty, error)

RegisterResourceOutputs forwards for completeness — components use it.

func (*MonitorProxy) Serve

func (p *MonitorProxy) Serve() (string, func(), error)

Serve binds a loopback TCP listener, starts the gRPC server, and returns its address. Caller MUST call Stop() when done.

The listener is plaintext, and has to be: it exists so a plugin subprocess can reach the Pulumi resource monitor via pulumi.NewContext(RunInfo{ MonitorAddr: ...}), and the Pulumi Go SDK dials a monitor address with insecure credentials — there is no hook to hand it a CA or a client cert. That is Pulumi's own transport for this socket: the engine passes its real monitor to every language host and provider plugin exactly the same way, plaintext on loopback.

So the exposure is a loopback-only, ephemeral, unauthenticated port that can register resources into the running stack, for the duration of one `sc deploy`. It grants a local process nothing it did not already have — during that same window Pulumi's own monitor is listening on loopback under the same terms, and this proxy only forwards to it. Binding 127.0.0.1 (never 0.0.0.0) and tearing the server down in the caller's defer are what keep it to that.

A bearer token in the metadata would be the obvious hardening and is not available: the plugin side dials through the Pulumi SDK, which sends no custom metadata, so requiring one would mean every plugin hand-rolling a monitor client instead of using pulumi.NewContext.

func (*MonitorProxy) SupportsFeature

SupportsFeature forwards too — plugins often probe this before calling RegisterResource with options the engine may or may not understand.

type OutputRef

type OutputRef struct {
	// URN the plugin has ALREADY awaited. Not optional, and not merely good
	// manners: core can only read a resource the engine has finished the step for,
	// and the engine stores it during step completion — which is also what
	// RegisterResource waits for before replying. So "the plugin received this URN"
	// is exactly the condition that makes this call safe, and a plugin that returns
	// a URN it never awaited has reintroduced the waitForRef bug.
	URN string
	// Property is the PROVIDER's output property name (e.g. "privateKeyOpenssh"),
	// not an SC-level name. Which is why core cannot unmarshal it into a
	// `pulumi:"…"`-tagged struct and let the SDK do this: the name is not known
	// until runtime, and reflect.StructOf cannot build a type that satisfies
	// sdk.Resource (it does not promote embedded methods).
	Property string
}

OutputRef names one property of a resource that lives in SC core's Pulumi graph but was registered by a PLUGIN, against the shared monitor, from a pulumi.Context that no longer exists.

This is the only way a plugin can hand core a value it does not know yet. A plugin cannot return an sdk.Output over gRPC — but its resources are in core's graph (that is what MonitorProxy buys), so core can project the property itself. See forge/docs/design/2026-10-24/sc-plugin-architecture/07-plugin-first-for-new-clouds.md §3.5 for the full derivation, including the two alternatives that do not work.

func (OutputRef) String

func (r OutputRef) String() string

type PeerClient

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

PeerClient is a connected handle to SC core's SCCore callback endpoint, scoped to one SC-core-spawned plugin. Open per RPC that needs to invoke a peer; Close when done to release the broker stream.

func NewPeerClient

func NewPeerClient(ctx context.Context, broker *hplugin.GRPCBroker, header *scpluginv1.RequestHeader) (*PeerClient, error)

NewPeerClient dials SC core's SCCore endpoint. Preferred path is RequestHeader.sccore_address (loopback TCP) — deterministic, no race with the broker's ConnInfo delivery. Legacy path is RequestHeader.sccore_broker_stream over the hashicorp/go-plugin broker; kept so an older plugin stays wire-compatible.

The broker argument is only consulted on the legacy path. A plugin can pass nil when it is OK to require the TCP endpoint.

func (*PeerClient) Close

func (c *PeerClient) Close() error

Close releases the broker stream connection. Safe to call more than once.

func (*PeerClient) NewDnsRecord

NewDnsRecord calls the NewDnsRecord RPC on another plugin.

func (*PeerClient) NewOverrideHeaderRule

NewOverrideHeaderRule calls the NewOverrideHeaderRule RPC on another plugin.

func (*PeerClient) PluginInvoke

func (c *PeerClient) PluginInvoke(ctx context.Context, pluginName, capability string, payloadJSON []byte) ([]byte, error)

PluginInvoke dispatches a capability-based call to another plugin via SC core's broker. The target plugin's `SchemaResponse.peer_capabilities` must advertise `capability`; SC core refuses the call otherwise. The payload + reply schemas are capability-specific — see each plugin's README for the typed shapes.

First consumer (sc-components-plugin-peer-invoke): sc-component-backup → sc-plugin-mongodb for `mint-scoped-user`:

payloadBytes, _ := json.Marshal(map[string]any{
    "database":      "forge_app",
    "roleName":      "readWrite",
    "consumerStack": "forge-conductor--staging",
})
reply, err := peer.PluginInvoke(ctx, "mongodb", "mint-scoped-user", payloadBytes)
// reply bytes: {"username": "...", "password": "...", "uri": "..."}

SC core sets `calling_plugin` on the forwarded request; the target plugin can inspect it for per-caller policy. Today it's best-effort (empty when the broker cannot identify the caller) — see TODO in callback_server.go PeerInvoke about run_token validation.

func (*PeerClient) Provider

Provider calls the Provider RPC on another plugin.

func (*PeerClient) Provision

Provision calls the Provision RPC on another plugin.

func (*PeerClient) ProvisionDomainForEndpoint

ProvisionDomainForEndpoint calls the ProvisionDomainForEndpoint RPC on another plugin.

func (*PeerClient) ProvisionRegistrar

ProvisionRegistrar calls the ProvisionRegistrar RPC on another plugin.

func (*PeerClient) VmHosts

VmHosts calls the VmHosts RPC on another plugin.

type PeerDispatcher

type PeerDispatcher interface {
	DispatchPeer(ctx context.Context, pluginName, rpcName string, payload []byte) ([]byte, error)
}

PeerDispatcher is the host-side route from one plugin's PeerInvoke call to another plugin's regular SCCloudPlugin RPC. SC core implements this against its loaded-plugins registry (`preEnginePluginBundle.clients` in pkg/clouds/pulumi/plugin_preengine.go).

`pluginName` is the plugin's advertised name — the key SC core stores in its registry on load. `rpcName` is the SCCloudPlugin method name, case-sensitive (e.g. "Provision", "NewDnsRecord"). The payload is proto wire bytes; the dispatcher unmarshals into the right request type, calls the stub, and marshals the response.

D8 of 06-decisions.md: a direct plugin-to-plugin connection was rejected in favour of this broker pattern. SC core is the only entity that knows every plugin's identity and credentials.

type Publisher

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

Publisher is a thread-safe, non-blocking sink for plugin-side progress events. The plugin's SCCloudPluginServer impl calls Push from any RPC handler; SC core's LogStream RPC drains events into its logger. Backs a bounded ring buffer so Push never blocks even if SC core isn't draining yet (startup race) or has gone away (shutdown). Dropped events are counted so a plugin's own health probe can surface the loss.

Lifetime: one per plugin process. The plugin's main() constructs one and passes it to the server impl; the impl exposes it on the LogStream RPC. It survives across RPCs. Drain blocks until Close is called OR the stream context cancels.

func NewPublisher

func NewPublisher(capacity int) *Publisher

NewPublisher creates a Publisher with the given ring-buffer capacity. A capacity of 0 defaults to 1024, which is enough for even a chatty multi-record provision without back-pressure.

func (*Publisher) Close

func (p *Publisher) Close()

Close wakes every blocked Drain so the gRPC stream handler can return. Idempotent.

func (*Publisher) Debug

func (p *Publisher) Debug(phase, msg string)

func (*Publisher) Drain

func (p *Publisher) Drain() ([]*scpluginv1.PluginLogEvent, bool)

Drain blocks until an event is available (or the publisher is closed) and returns the next batch. Caller is expected to loop: drain → send over the gRPC stream → drain again. Returns an empty slice + false after Close.

func (*Publisher) Dropped

func (p *Publisher) Dropped() uint64

Dropped returns the number of events dropped since start due to ring overflow. Observational only; a plugin can expose it on a healthz endpoint if it has one.

func (*Publisher) Error

func (p *Publisher) Error(phase, msg string)

func (*Publisher) Info

func (p *Publisher) Info(phase, msg string)

Info / Debug / Warn / Error are tiny convenience wrappers.

func (*Publisher) Push

func (p *Publisher) Push(sev scpluginv1.LogSeverity, phase, message string)

Push enqueues one event. Non-blocking. When the buffer is full, the OLDEST event is dropped (ring semantics) — the newest progress is almost always what the operator wants to see.

func (*Publisher) Warn

func (p *Publisher) Warn(phase, msg string)

type SecretResolver

type SecretResolver interface {
	ResolveSecret(ctx context.Context, req *scpluginv1.ResolveSecretRequest) (*scpluginv1.ResolveSecretResponse, error)
}

SecretResolver and CredentialResolver are placeholders for the two other SCCore RPCs. Neither has a core-side implementation today — the bus declares them but no plugin can usefully call them yet (noted in Addendum R and this PR's design). The server below returns Unimplemented until they land, which is observable but harmless.

type ServerConfig

type ServerConfig struct {
	Impl   scpluginv1.SCCloudPluginServer
	Logger hclog.Logger
}

ServerConfig describes the plugin-side registration: who implements SCCloudPluginServer and what logger to use.

type VmHostBuilder

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

VmHostBuilder accumulates one host's facts, and the first error that occurred while doing so. Every setter returns the builder, so a whole host reads as one expression and the error is checked once, by Build.

func NewVmHost

func NewVmHost(ctx context.Context, name string) *VmHostBuilder

NewVmHost starts a host. `name` is how the operator will see this machine and how core names the resources it hangs off it, so it must be stable across deploys — derive it from the resource name in the request, not from anything the cloud generated.

ctx is the one to await URNs on: pass pctx.Context() from the PulumiContext opened for this RPC.

func (*VmHostBuilder) Address

func (b *VmHostBuilder) Address(value string) *VmHostBuilder

Address is the address core connects to, when the plugin already knows it.

func (*VmHostBuilder) AddressOf

func (b *VmHostBuilder) AddressOf(res sdk.Resource, property string) *VmHostBuilder

AddressOf is Address as a property of a resource — the usual case, since the address is a floating IP or an instance field that does not exist yet.

func (*VmHostBuilder) AddressOutput

func (b *VmHostBuilder) AddressOutput(out sdk.StringOutput) *VmHostBuilder

AddressOutput sets the address from an sdk.StringOutput — the pattern a plugin that shells out to a CLI needs, since the address is parsed out of a local.Command's stdout at apply time, not a property on a provider resource.

Awaits the value. On apply the await blocks until the upstream command has run and the parsed address is known. On preview the value is unknown — the in-tree drivers' sdk.StringOutput was treated as a known empty string in the same case (see cloudru_evolution.go's parseEvolutionResult preview branch, which returns ""), and this mirrors that: emit OutputLiteral("") so Build() still has a non-nil address and core-side readers see the same shape they used to. Everything that would actually dial SSH in preview has unknown resource dependencies and never runs, so a known-empty address is correct.

Prefer AddressOf when the address IS a property of a Pulumi provider resource; this one is for the no-provider / CLI-driven case.

func (*VmHostBuilder) Build

func (b *VmHostBuilder) Build() (*scpluginv1.VmHostFacts, error)

Build returns the host, or the first error the chain hit.

The two structural refusals are core's, raised here instead: core rejects a host with no name (it has nothing to call the resources it creates) and a host with no address (it has nowhere to connect). Catching them in the plugin turns a gRPC round-trip into a local error that names the host.

func (*VmHostBuilder) DependsOn

func (b *VmHostBuilder) DependsOn(resources ...sdk.Resource) *VmHostBuilder

DependsOn names resources everything core hangs off this host must wait for — the instance itself, the floating-IP association, a firewall rule that has to exist before the SSH connection is attempted.

Core rehydrates these URNs into resource handles and passes them as pulumi.DependsOn, so the ordering is enforced by the engine rather than by luck.

func (*VmHostBuilder) HostKey

func (b *VmHostBuilder) HostKey(key string) *VmHostBuilder

HostKey pins the machine's SSH host key, so core verifies the host it reaches is the host it created instead of trusting the first answer.

Only a cloud whose first boot SC controls can do this — the key has to be seeded into the machine before it comes up. A driver that cannot (Cloud.ru Evolution refuses user-data outright) calls TrustOnFirstUse instead.

func (*VmHostBuilder) HostKeyOf

func (b *VmHostBuilder) HostKeyOf(res sdk.Resource, property string) *VmHostBuilder

HostKeyOf is HostKey as a property of a resource — the public half of a host key the plugin generated and seeded via user-data.

func (*VmHostBuilder) Port

func (b *VmHostBuilder) Port(port int) *VmHostBuilder

Port is the SSH port. Leave it unset for 22 — core defaults it.

func (*VmHostBuilder) PrivateKey

func (b *VmHostBuilder) PrivateKey(pem string) *VmHostBuilder

PrivateKey is the SSH private key core authenticates with.

Marked secret on the wire regardless: core applies pulumi.ToSecret to this field unconditionally, and a plugin cannot opt out of that by omission. Setting it here too means the value is also marked for anything that reads the wire message.

func (*VmHostBuilder) PrivateKeyOf

func (b *VmHostBuilder) PrivateKeyOf(res sdk.Resource, property string) *VmHostBuilder

PrivateKeyOf is PrivateKey as a property of a resource — a key pair the plugin generated in this same deploy, typically `privateKeyOpenssh` on a tls.PrivateKey.

func (*VmHostBuilder) PrivateKeyPassword

func (b *VmHostBuilder) PrivateKeyPassword(password string) *VmHostBuilder

PrivateKeyPassword is the passphrase protecting the private key. Leave it unset for a key the plugin generated itself — core reads an absent value as the empty passphrase, which is what every self-keying driver means.

func (*VmHostBuilder) PrivateKeyPasswordOf

func (b *VmHostBuilder) PrivateKeyPasswordOf(res sdk.Resource, property string) *VmHostBuilder

PrivateKeyPasswordOf is PrivateKeyPassword as a property of a resource.

func (*VmHostBuilder) Role

func (b *VmHostBuilder) Role(role string) *VmHostBuilder

Role is what the machine is being prepared for: the values of pkg/clouds/vm.HostRole ("compose", "k3s-server", "k3s-agent").

func (*VmHostBuilder) TrustOnFirstUse

func (b *VmHostBuilder) TrustOnFirstUse() *VmHostBuilder

TrustOnFirstUse says this driver cannot pin a host key, and that core should accept whatever the machine presents on the first connection.

It is a separate call rather than the default so that it is a decision in the plugin's source, reviewable as such: it is a real weakening of the connection's guarantees, and the operator's `hostKey:` escape hatch exists because of it.

func (*VmHostBuilder) User

func (b *VmHostBuilder) User(user string) *VmHostBuilder

User is the SSH user core connects as.

Directories

Path Synopsis
proto
v1
Package runtime is the shared RPC-handler scaffolding every SC plugin uses: context construction with a local-engine fallback, deferred drain-then-settle of the Pulumi SDK context, harvest of pctx exports into ProvisionResponse.Outputs, and the compute-process parent-env swap.
Package runtime is the shared RPC-handler scaffolding every SC plugin uses: context construction with a local-engine fallback, deferred drain-then-settle of the Pulumi SDK context, harvest of pctx exports into ProvisionResponse.Outputs, and the compute-process parent-env swap.

Jump to

Keyboard shortcuts

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