Documentation
¶
Overview ¶
Package exec defines the Backend interface and per-backend implementations roksbnkctl uses to run external tools (ibmcloud, kubectl, terraform, iperf3, etc.). Backends differ along network locality (where the tool runs) and toolchain freshness (host install vs. pinned image); see PRD 03 (docs/prd/03-EXECUTION-BACKENDS.md) for the full rationale.
Sprint 3 ships `local` and `docker` backends. Sprint 4 adds `k8s` and `ssh`. Every backend translates the shared `Credentials` struct into its native shape (env vars for local, --env+--mount for docker, etc.) per the rules in PRD 04 (docs/prd/04-CREDENTIALS.md).
Index ¶
- Constants
- func K8sInstallYAML() string
- func NewRedactor(w io.Writer, secrets []string) io.Writer
- func Register(name string, b Backend)
- func SetK8sInit(fn func() (kubernetes.Interface, *rest.Config, error))
- func SetSSHClientFactory(fn func(ctx context.Context, target *remote.Target) (remoteClient, error))
- func SetSSHOpts(opts SSHBackendOpts)
- func SetSSHTargetResolver(...)
- func SetToolImageTag(fn func() string)
- func SpecTarget(spec string) string
- type Backend
- type Credentials
- type DockerBackend
- type HostMount
- type K8sBackend
- type LocalBackend
- type RunOpts
- type SSHBackend
- type SSHBackendOpts
Constants ¶
const ( K8sOpsNamespace = "roksbnkctl-ops" K8sTestNamespace = "roksbnkctl-test" K8sOpsPodName = "roksbnkctl-ops" K8sOpsSecretName = "roksbnkctl-ibm-creds" )
Namespaces and well-known names used by the k8s backend. Mirror the values baked into k8s_install.yaml — the backend assumes ops install has already provisioned these.
Variables ¶
This section is empty.
Functions ¶
func K8sInstallYAML ¶
func K8sInstallYAML() string
K8sInstallYAML returns the embedded install manifest template. The CLI layer (internal/cli/ops.go) substitutes ${IBMCLOUD_API_KEY_B64}, ${ROTATED_AT}, and ${OPS_IMAGE} before applying.
Exported as a function (not a var) so callers can't accidentally mutate the embedded copy at runtime — the substitution happens on a strings.NewReplacer.Replace return value, which is a fresh string.
func NewRedactor ¶
NewRedactor wraps w; any byte sequence matching one of the non-empty secrets is replaced with [REDACTED] before reaching the underlying writer. Buffering across writes catches secrets split across chunk boundaries. Empty / zero-length secrets are ignored (passing nil or the zero slice yields a transparent passthrough).
Each secret is registered in its raw form AND in its base64 forms (see base64Variants), because that is how credentials actually move through this system — *_b64 config fields, Kubernetes Secret values, anything a tool dumps from a rendered config. Registering only the raw form would mask half the shapes the same credential takes.
The returned io.Writer also implements io.Closer; callers MUST call Close() at end-of-stream so the held-back tail bytes drain to w. Backends call Close() in their cleanup defer; tests use the test- helper that detects the io.Closer and calls it.
func Register ¶
Register installs a backend under name. Called from each backend's init() so concrete implementations register themselves; the registration order is irrelevant.
Re-registering the same name overwrites silently — useful for tests that swap in stubs. If you want fail-on-collision behaviour, wrap this with a check at the call site.
func SetK8sInit ¶
func SetK8sInit(fn func() (kubernetes.Interface, *rest.Config, error))
SetK8sInit lets the CLI layer wire its kubeconfig-loading logic into the backend without forcing a circular import. internal/cli/k_root.go (or wherever feels natural) calls this in init().
func SetSSHClientFactory ¶
SetSSHClientFactory wires a custom remote.Client constructor for tests. Production callers leave the factory unset; the SSHBackend falls through to remote.Connect.
Test usage:
exec.SetSSHClientFactory(func(_ context.Context, _ *remote.Target) (remoteClient, error) {
return &fakeRemoteClient{...}, nil
})
defer exec.SetSSHClientFactory(nil)
// ... exercise the backend; assert against the fake's captures ...
func SetSSHOpts ¶
func SetSSHOpts(opts SSHBackendOpts)
SetSSHOpts is the seam the CLI layer uses to push --bootstrap and related flags into the backend without an import cycle. Safe to call repeatedly; the latest call wins.
func SetSSHTargetResolver ¶
func SetSSHTargetResolver(fn func(ctx context.Context, workspace, name string) (*remote.Target, map[string][]byte, error))
SetSSHTargetResolver overrides the default (workspace-config-backed) target resolver. Called from internal/cli (and tests).
func SetToolImageTag ¶
func SetToolImageTag(fn func() string)
SetToolImageTag wires the CLI's Version through to the image-tag resolver. Called from internal/cli/root.go's init().
func SpecTarget ¶
SpecTarget extracts the "<target>" component from a spec like "ssh:<target>". Returns "" for specs without a colon. Sprint 4 SSH backend uses this to look up the target by name.
Types ¶
type Backend ¶
type Backend interface {
// Run executes argv with stdin/stdout/stderr wired to the streams
// in opts. Returns the wrapped process's exit code.
//
// 126 + 127 are reserved per PRD 03 §"Backend interface" for
// backend-side failures (e.g., docker daemon unreachable, SSH
// connect refused). Codes 0-125 + 128-255 mirror the wrapped
// process exit code unchanged.
//
// ctx cancellation must terminate the wrapped process within a
// few seconds — backends signal/kill the container/process and
// return ctx.Err() (or the equivalent killed-by-signal exit
// code).
Run(ctx context.Context, argv []string, opts RunOpts) (exitCode int, err error)
// Name returns the registry key used to resolve this backend
// ("local" | "docker" | "k8s" | "ssh"). Used by logging + doctor.
Name() string
}
Backend is the common interface every external-tool runner implements. Implementations differ along (a) where the tool actually runs (host process vs docker container vs in-cluster pod vs SSH host) and (b) how credentials and files are propagated (env vs bind-mount vs projected Secret vs SSH wrapper).
PRD 03 §"Backend interface" is the authoritative spec. Implementations in this package: local.go, docker.go (Sprint 3); k8s.go, ssh.go are Sprint 4.
func ResolveBackend ¶
ResolveBackend looks up a backend by spec. Spec forms:
"local" — local execution "docker" — docker daemon on caller host "ssh:<target>" — SSH backend with named target (Sprint 4) "k8s" — in-cluster pod (Sprint 4)
Sprint 3 only registers "local" + "docker". The "ssh:<target>" spec parser is in place so the integrator's CLI flag parsing has a stable hook; resolving an unregistered spec (k8s, ssh:foo) returns a clear "backend not implemented yet" error pointing at PRD 03.
Empty spec defaults to "local" — matches the per-tool default for ibmcloud and terraform per PLAN.md Sprint 3.
type Credentials ¶
type Credentials struct {
// KubeconfigBytes is the raw YAML content of the kubeconfig that
// should be available to the wrapped tool. nil means "no kubeconfig"
// — backends that bind-mount or materialise it skip the step.
//
// Why bytes (not a path)? Because the docker / k8s / ssh backends
// need to materialise it inside the container / pod / remote host.
// Even the local backend takes bytes for symmetry; if a path is
// already on disk, callers read it once and pass the bytes through.
KubeconfigBytes []byte
// IBMCloudAPIKey is the resolved IBM Cloud API key. Empty means "no
// key" — backends skip the env-var / mount work.
//
// PRD 04 §"Cross-backend principles" #1: this value MUST NEVER end
// up in argv, log lines, or `docker inspect` output. Per-backend
// serialisers below ensure that; redact.go's NewRedactor wraps
// stdout/stderr as a defense-in-depth backstop.
IBMCloudAPIKey string
}
Credentials is the single shape every backend consumes. Per-backend serialisers (EnvVars, DockerArgs, …) translate it into env vars, bind-mounts, Secret references, or wrapper scripts — whatever the concrete backend needs.
PRD 04 reserves slots in this struct for AWS / GCP credentials in future. For Sprint 3 only IBMCloudAPIKey + KubeconfigBytes are wired.
func (*Credentials) DockerArgs ¶
func (c *Credentials) DockerArgs(tempDir string) (envArgs, mountArgs []string, cleanup func(), err error)
DockerArgs returns the docker-run argv fragments needed to propagate these credentials into a container, plus a cleanup function that removes any tempfiles materialised in tempDir.
The split into envArgs + mountArgs lets the caller assemble them in the order their docker-run shape requires (envs and mounts are independent; the convention is mounts first, then envs, then image, then command — but the assembly is the caller's job).
PRD 04 §Docker container constraints, encoded as code:
envArgs uses the bare-name `--env IBMCLOUD_API_KEY` form (no `=value`) so the value inherits from the caller env at runtime and never lands in `docker inspect`. Callers MUST set the env in the docker client's environment (or the daemon's, for remote daemons) before invoking docker.
mountArgs binds the SINGLE kubeconfig file (not its parent dir) read-only at /root/.kube/config. We materialise it under tempDir as kubeconfig with mode 0600.
cleanup unlinks any materialised tempfiles. Safe to call multiple times; nil means "nothing to clean" (no kubeconfig was materialised).
func (*Credentials) EnvVars ¶
func (c *Credentials) EnvVars() []string
EnvVars returns KEY=VALUE strings the local backend should append to the child process's environment. Empty fields produce no entries — callers can append() unconditionally.
Local backend semantics (PRD 04 §Local exec): cred values flow through env vars on a single-user assumption. KUBECONFIG points at a file path the caller has already written; we don't materialise it here because the local backend executes in the same FS namespace as roksbnkctl itself.
IBMCLOUD_API_KEY is also exported as IC_API_KEY because the IBM CLI older versions accept both names — matches the historical workspaceEnv behaviour in cli/cluster.go.
type DockerBackend ¶
type DockerBackend struct {
// contains filtered or unexported fields
}
DockerBackend executes argv inside a per-tool docker image. The image is selected by argv[0] from toolImages — tools without an entry fall back to argv[0] interpreted as a literal image reference (so callers can pass "busybox:latest" directly for tests).
PRD 03 §"Docker (internal/exec/docker.go)" + PRD 04 §"Docker container" jointly drive the implementation:
Per-tool image lookup (toolImages); the GH Actions workflow publishes :dev tags on tag releases.
Cred propagation: --env IBMCLOUD_API_KEY (no =value) so `docker inspect` can never leak the value; bind-mount the SINGLE kubeconfig file (not parent dir) read-only at /root/.kube/config.
Stream redaction: stdout/stderr passed through NewRedactor (defense-in-depth) before reaching the caller.
Cleanup: AutoRemove + ctx-cancel triggers ContainerKill so the container doesn't outlive its parent.
func (*DockerBackend) Run ¶
Run implements Backend.
argv[0] selects the image (via toolImages or literal); argv[1:] is passed as the container's command. The entrypoint baked into the image (e.g., `ibmcloud` for the ibmcloud-cli image) handles the argv[1:] by default — callers don't need to repeat the binary name.
type HostMount ¶
type HostMount struct {
HostPath string // absolute path on the host
ContainerPath string // absolute path inside the container
ReadOnly bool // true → read-only mount
}
HostMount is one host → container bind-mount. Used by the docker backend's terraform path; future backends may grow analogous shapes (k8s projected-volume, ssh staged-file).
type K8sBackend ¶
type K8sBackend struct {
// contains filtered or unexported fields
}
K8sBackend executes argv either by exec'ing into a long-lived ops pod (for ibmcloud + ad-hoc shells) or by spawning a one-shot Job (for iperf3 client + terraform).
PRD 03 §"K8s" is the design spec. The two paths share a single Run entrypoint and dispatch on RunOpts.LongLivedExec — true for the ops-pod exec path, false (default) for the Job path.
`roksbnkctl ops install` provisions the namespaces, ServiceAccount, Secret, ClusterRole, and ops Pod this backend assumes exist. The backend doesn't try to bootstrap on first call (would race; would surprise users). Callers see a clear "ops not installed" error (rc=127) and the install command in the message.
type LocalBackend ¶
type LocalBackend struct{}
LocalBackend executes argv in a child process on the host running roksbnkctl. Wraps `os/exec` with the credential-propagation + stream-redaction behaviour the Backend interface requires.
Behaviour matches the original passthrough callsites in internal/cli/cluster.go (runWithEnv): host env is inherited; Env entries from RunOpts.Env are appended (later wins for duplicates, per os/exec's documented semantics); cred env vars come from Credentials.EnvVars().
The local backend never materialises Files into the parent host's filesystem at arbitrary paths — that would surprise users. Instead, when Files is non-empty, the backend writes them inside RunOpts.WorkDir (or a tempdir if WorkDir is empty, returning that as cwd). Sprint 3 ibmcloud passthrough doesn't need Files for local; the path exists for symmetry with docker / k8s / ssh backends.
func (LocalBackend) Run ¶
Run implements Backend.
Exit-code semantics (PRD 03 §"Backend interface", 126/127 split):
argv[0] not on PATH → returns (127, error). Matches POSIX shell "command not found" convention; PRD 03 reserves 127 for backend-side failed-to-start, and "binary not on PATH" is the local-backend analog (no daemon to be unreachable, no SSH to fail to connect). The 126 ("started then failed") case doesn't apply to the local backend — there's no backend-startup phase distinct from process-spawn, so we never split that direction.
Child runs and exits non-zero → returns (childExit, *exec.ExitError). Caller can ignore the error (rc is the source of truth) or surface the wrap.
Child runs and exits 0 → returns (0, nil).
ctx cancelled mid-run → SIGKILL the child, return (137, ctx.Err()) (137 = 128 + SIGKILL, the Linux convention).
type RunOpts ¶
type RunOpts struct {
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
// Env is a list of "KEY=VALUE" strings to append to the wrapped
// process's environment. Backends merge with their own defaults
// (e.g., the local backend appends to os.Environ()).
Env []string
// WorkDir is the wrapped process's working directory. Best-effort
// — some backends ignore (k8s pod's WorkingDir is set on the
// container spec; can't change per-exec).
WorkDir string
// TTY requests a PTY where the backend supports it (local, ssh).
// Backends that don't support TTY (docker without -t flag plumbed,
// k8s without remotecommand TTY) silently degrade to non-TTY.
TTY bool
// Files is a name → content map that materialises at exec time.
// Local backend uses these as files in WorkDir; docker bind-mounts;
// k8s / ssh stage to a tempdir on the remote.
Files map[string][]byte
// Credentials carries cred values for the wrapped tool. Backends
// translate via the per-backend serialisers in creds.go (EnvVars,
// DockerArgs, etc.) and wrap stdout/stderr through NewRedactor as
// defense-in-depth.
Credentials *Credentials
// HostMounts lists additional bind-mounts the docker backend
// projects from the host filesystem into the container. Sprint 5
// terraform integration uses this to mount the workspace state
// directory at `/state` so the in-container `terraform init/plan/
// apply/destroy` operates on the same .tfstate file the local
// backend writes. Other backends ignore HostMounts (the local
// backend has no need; ssh / k8s would need scp / projected-volume
// shapes that aren't worth the v1 complexity).
//
// PRD 03 §"terraform" + chapter 17 §"terraform docker subsection".
HostMounts []HostMount
// RunAsUser pins the container's UID:GID. Set for the terraform
// docker path so the state file is written with the host user's
// ownership (otherwise terraform-in-container runs as root and
// produces root-owned state files the host user can't edit).
//
// Format: "uid:gid" or just "uid". Empty defers to the image's
// default user. Backends that don't honor a runtime UID (k8s,
// ssh, local) ignore the field.
RunAsUser string
}
RunOpts is the options bundle for one Backend.Run invocation.
PRD 03 §"Backend interface" defines the shape; this package adds two implementation conveniences:
- Stdin/Stdout/Stderr default to nil-ignored / nil-discarded (backends use io.Discard as a fallback, so callers don't have to).
- Files materialise at exec time — the local backend ignores them (FS is shared); the docker backend bind-mounts a tempdir; ssh / k8s backends scp / kubectl-cp them in.
type SSHBackend ¶
type SSHBackend struct{}
SSHBackend wraps internal/remote.Client with the surface PRD 03 specifies: pre-flight tool check + apt bootstrap, file materialization in a per-run tempdir on the remote, env propagation via SetEnv with a wrapper-script-with-trap fallback, TTY pass-through, and trap-on-EXIT cleanup.
One SSHBackend instance handles all targets — the per-Run target name comes from the spec ("ssh:<target>") parsed by ResolveBackend.
PRD 03 §"SSH" + PRD 04 §"SSH" jointly drive the design.
type SSHBackendOpts ¶
type SSHBackendOpts struct {
// Bootstrap toggles the "auto-install missing tools via apt" path.
// Default false (PRD 03 §"open questions" recommendation: opt-in).
// CLI plumbs `--bootstrap` here.
Bootstrap bool
// Workspace + Target plumbing — backend resolves target via
// remote.LoadTarget(workspace, name). Set by the CLI dispatcher
// before invoking Run; left blank for tests that wire a synthetic
// target via SetSSHTargetResolver.
Workspace string
// InsecureHostKey mirrors the persistent --insecure-host-key flag.
InsecureHostKey bool
}
SSHBackendOpts are runtime knobs the SSH backend reads via package- level setters (analogous to k8s.go's SetK8sInit). Keeps the cobra layer out of the exec package.