deploycontrol

package module
v0.0.0-...-c545229 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 30 Imported by: 4 modules, 4 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

cutversion.go implements the "cut a version" flow (#1877, epic #1871). With deployments now persisted (#1872), the current version is known, so MemQL can propose the next semver and let an owner cut it.

SuggestNextVersion (read) reads the latest succeeded deployment's version and proposes the next major / minor / patch. CutVersion (write) creates a new pending v1:cluster:deployment record at the chosen version with the resolved image digest -- ready for the deploy driver (#1878) to ship. Both are developer-or-above gated (#1876): cutting a version is a forward-deploy action, so developer/admin/owner may do it (SuggestNextVersion is its read companion and shares the gate so a developer can size the cut). The DSL mirror is the bare conjunct requiresDeveloperOrAbove in dsl/deployment/specs.memql.

deploy.go implements the two target-agnostic deploy actions (#1878, epic #1871) on top of the persisted deployment records (#1872):

  • Deploy(deploymentId): take a cut `pending` deployment record (created by CutVersion, #1877), validate its provider, and transition the record pending -> in_progress. The in_progress CDC edge triggers the deploy pack's driveDeploymentInProgress automation (E2.3), which observes ArgoCD's reconciled state and owns the succeeded|failed terminal transition.

  • RollbackDeployment(toDeploymentId): redeploy a prior SUCCEEDED deployment's stored image digest. This is NOT a blue-green color flip -- the previous color only survives the scale-down window, so a rollback must re-pin (re-ship) the historical digest. It creates a NEW deployment record at in_progress pointing at the historical digest (previousDeploymentId -> the target); that create-at-in_progress edge triggers the same automation, which observes the reconciliation and lands the record in `rolled_back` (it branches on previousDeploymentId, #2168).

Both actions are ASYNC kick-offs (#2115 step 6 retired the synchronous Go apply): the RPC validates + kicks off the lifecycle and returns an ack; the deploy pack automations (examples/deploypack), anchored on the identity binary, own the terminal transition through the same Executor effects. Callers poll GetDeploymentStatus / the deployment concept for resolution.

Deploy is developer-or-above gated (#1876): developer/admin/owner may ship a cut version forward. RollbackDeployment is gated more strictly -- owner-only (#1876) -- so developer and admin can deploy forward but not roll back. Both emit exactly one audit event via finishWrite.

deployment_store.go persists deployments as first-class v1:cluster:deployment records (#1872, foundation of epic #1871).

Before this, a deploy left no trace in the data layer -- image digests lived only in releases/*.yaml on disk, and there was no deployment entity, status, or history to query. The console write RPCs now write a record at deploy start (status in_progress) and transition it as the rollout resolves (succeeded on a clean run, failed on error). Each write appends a new payload version under the SAME concept id (the deploymentId), so the lifecycle is reconstructable asOf any time, and the CDC path emits graph.node.created/updated.<partition>.v1:cluster:deployment -- the same event stream the cockpit Deployments view subscribes to.

Persistence is best-effort: a bookkeeping write must never block or fail a deploy. When no engine is wired (e.g. unit tests) every method is a no-op. Errors are logged at warn, never returned to the RPC.

dispatch.go bridges the DeployControlService RPC set onto a single envelope so a WebSocket client can reach it (memql#3311).

DeployControlService is a separate UNARY gRPC service on the same listener. The Go SDK dials it natively; a browser cannot dial gRPC at all, and neither can any other WebSocket client -- so the entire deploy surface was unreachable from the VS Code extension (which speaks /memql/ws) and from the portal. Bridging it onto MemqlService.Stream fixes that, and this file is the fan-out that makes the bridge safe.

THE INVARIANT THIS FILE EXISTS TO HOLD. Dispatch takes the memqlv1.DeployControlServiceServer interface and calls its methods directly. It contains no role check, no audit write, and no argument validation of its own -- every one of those lives inside the Service methods, which is what the unary path invokes too. The gate therefore cannot drift between the two surfaces: there is one implementation, and a bridged call is the unary call with a different envelope around it. A bridge that re-implemented the checks would be a privilege-escalation hole the first time the two copies disagreed, which is precisely the failure the #3311 parity test (deploycontrol/stream_parity_test.go) exists to make impossible.

The caller's identity travels the ordinary way: the stream handler stamps the session's auth.AccessContext onto the context it passes here, and resolveActor (service.go) reads it exactly as it reads the interceptor-stamped context on a unary call.

Package deploycontrol is the deploy CAPABILITY BACKEND for the MemQL DevOps deployment bundle -- NOT the orchestrator. (I11 #2225, epic #2212.)

Role after I11

The single orchestrator for an engine deploy is the `deployEngineCluster` automation in the centralized `deployment` pack (dsl/deployment/, I10 #2224): it sequences clone -> build -> place -> gate -> finish, calling the pure decision logics, the persistence mutations, and the world-touching actions. This package is demoted to what those constructs RESOLVE TO -- the deploy capability implementations:

  • Executor (executor.go) -- THE single side-effect boundary (git / kubectl argo rollouts / kubectl JSON reads). The deploy pack drives these exact effects through the IntegrationProvider layer via the exported NewExecutor, so the DSL automation layer is ADDITIVE, never a drifting parallel copy.
  • driver.go / lockfile.go / semver.go (cutversion.go) / overlay.go -- mechanical deploy primitives (provider selection, release lockfile, version arithmetic, overlay pinning) the actions/builtins resolve to.
  • role_gate.go / status.go -- the Go auth gates + status reads the deploy RPCs and the deploy pack share.
  • repair.go -- the Repair verb (memql#4209): an owner-only, observed re-sync of the installation's ArgoCD Application through the Executor, recorded on the deployment timeline. Its file comment says what a cluster-side repair is and is not, and why its watcher lives here rather than in the deploy pack's automations.

The orchestration entrypoints are DEMOTED, not orchestrating

The synchronous Go deploy LIFECYCLE that deploy.go's Deploy / RollbackDeployment once ran (select driver -> apply -> terminal transition) was retired in #2115 step 6 and stays retired under I11. Those RPCs are now thin ASYNC KICK-OFF shims: they validate, write a single in_progress edge (Deploy transitions an existing pending record; RollbackDeployment creates a new in_progress record carrying the historical digest + previousDeploymentId), and return an ack. The in_progress CDC edge is what a deploy-pack automation consumes to observe the reconciliation + own the terminal transition -- the orchestration lives in the DSL, not here. So an entrypoint NEVER writes a terminal status; the only synchronous write is the kick-off edge. This invariant is guarded by TestDeployKicksOffWithoutApply + TestRollbackDeploymentKicksOffWithoutApply (deploy_test.go): a regression that re-added a synchronous deploy lifecycle to this package fails those tests.

The legacy Deployment Console actions (Rollback / RolloutAction / GetDeploymentStatus, service.go, #728) still call the Executor effects synchronously; retiring those gRPC surfaces in favor of the automation is owner-gated follow-on work (tracked off #2229), not part of I11, because they are consumed cross-repo by the cockpit Deploy Console + the SDK.

driver.go holds the provider allow-list the deploy-control actions (deploy.go) share.

The synchronous Go apply -- the deployDriver/azureDriver abstraction that ran the promote script inline and transitioned the record to its terminal status -- was RETIRED in #2115 step 6. The deploy-as-a-pack automations (examples/deploypack: driveDeploymentInProgress / recordReconciledState) now own promote + the terminal transition off the deployment-record CDC edge, through the SAME Executor effects. So Deploy / RollbackDeployment only validate the record and kick off the lifecycle (transition to in_progress); they never apply here.

What remains is the provider allow-list (validateDeploymentProvider): the kick-off validates the provider before transitioning. The Executor effect boundary (executor.go) + the proto/gRPC surface are preserved.

repair.go implements Repair, the cluster-side repair verb on DeployControlService (memql#4209).

What a repair IS here, and what it is not

The vision names update / repair / restore. Update and restore were covered (Deploy / Rollback / RollbackDeployment / RolloutAction); repair existed only as the VS Code extension's capability-script flow -- `cli.js repair`, which re-runs the INSTALL graph with the parameters the install receipt recorded (editors/vscode/src/install, scripts/install/graph/install.json). Read that graph and most of it is the OPERATOR'S MACHINE: place the pinned k3d / kubectl / mkcert binaries, edit the hosts file under sudo, install the local CA into the browser trust store, clone the stack into the pinned source directory, `k3d cluster create` against the host's Docker daemon, seed the bootstrap secrets from a key FILE on the operator's disk. None of that is reachable from a pod -- the identity node has no Docker socket, no sudo, no hosts file, no receipt, and the cluster it would recreate is the one it runs in. So the install graph is NOT what this verb runs, and it could not be.

What the graph's cluster half does, once the cluster exists, is "apply the ArgoCD Application and wait for the workloads to become ready" (scripts/k3d/up.sh: apply_argocd_app + wait_for_workloads). THAT half has a cluster-side form, and it is the same form on both providers because the local cluster and the cloud reconcile through one Application on one ArgoCD (environment parity): ask ArgoCD to hard-refresh the manifests and run a sync with prune, then watch the Application until it reports synced AND healthy. It is the command deploy/argocd/README.md documents for an operator-triggered sync (`kubectl -n argocd patch app memql --type merge -p '{"operation":{"sync":{}}}'`), issued through the Executor from the identity node rather than by a person at a terminal. On the cloud the Application is on MANUAL sync, so this is the only thing that re-applies drift at all; on the local cluster it is the immediate form of the selfHeal the Application already carries. Nothing here changes version -- a repair that installs a different version is an upgrade wearing a repair's name (memql#3605).

Provider

The provider is read off the concepts -- the v1:cluster:cluster row first (the installation's own statement of where it runs), then the newest v1:cluster:deployment record -- never off an environment branch (epic memql#3943). Both known providers, docker-local and azure, reconcile through the Application, so both have the repair above; an empty provider is the package's "nobody said" and takes the same default (azure) every other record here takes. Anything else has NO defined repair: the engine cannot claim the Application is that topology's reconciliation path, so the call is refused inside the ActionResult with the locked message "repair is not defined for this provider" (RepairUndefinedError) -- audited as a failure, with the audit id on the result on both transports -- rather than half-run.

Honest progress

ok=true means accepted AND kicked off, not "repaired". The RPC writes a v1:cluster:deployment record at in_progress BEFORE the kick-off (notes prefixed repairNotePrefix, carrying the version in force), so the timeline the portal already renders carries the repair from its first instant; a kick-off that fails transitions that record to failed in the same call. After a successful kick-off a bounded watcher on this node observes the Application through the Executor until the operation it stamped (repairOperationInfoName = the record's id) has run and the Application is synced AND healthy -- succeeded -- or the operation failed, the Application went Degraded, the reads kept failing, or the ceiling passed -- failed. The terminal status is therefore always an OBSERVATION; nothing here asserts success from an exit code.

The watcher lives here rather than in the deploy pack's automations because those observe a single instant on the in_progress edge and only for the azure provider (examples/deploypack/dsl/logic.memql); a repair on a local cluster would strand at in_progress forever, which is exactly the invented progress this verb must not produce. The record is created by an insert, which emits graph.node.created and not the graph.node.updated edge the pack triggers on, so the pack and this watcher never contend for one record.

semver.go is the version-arithmetic helper behind the "cut a version" flow (#1877). It parses a version, bumps a chosen part, and compares two versions to find the highest succeeded deployment.

MemQL release tags are a three-part numeric version. Two schemes are in use and BOTH fit one parser: classic semver (0.9.9, 1.2.3) and the date-ish CalVer the concept doc mentions (2026.6.21) -- each is three dot-separated non-negative integers. That is exactly what the release tooling validates: scripts/release/release.sh enforces `^[0-9]+\.[0-9]+\.[0-9]+$` for the immutable image tag. We follow the same contract here -- no pre-release / build suffix -- so a cut version is always a clean X.Y.Z that release.sh will accept downstream.

Package deploycontrol implements the gRPC DeployControlService behind the MemQL Deployment Console (znasllc-io/memql#725 + #728).

The service exposes the deployment-v2 machinery -- the image authority (the kustomize overlay), release lockfiles, Argo CD app status, Argo Rollouts progressive delivery, and the in-cluster deploy gate -- as a small set of unary RPCs.

Read RPCs map raw `kubectl ... -o json` + on-disk overlay/lockfile state into typed status (pure mappers in status.go / overlay.go / lockfile.go). Write RPCs go through the sanctioned actions (`git revert`, `kubectl argo rollouts`) via the Executor boundary -- never ad-hoc `kubectl set image`.

Every RPC operates on THIS installation and takes no environment (epic memql#3943). Where the cluster is addressed, it is addressed by the three constants below.

Every write RPC is gated to owner/admin (#728) and emits an audit event (success / failure / blocked). Read RPCs are NOT audited per call (too noisy).

Index

Constants

View Source
const (
	// ReasonNoClusterAPI: the process is not running inside a cluster, so
	// there is no ServiceAccount token and no API server to reach.
	ReasonNoClusterAPI = "no_cluster_api"
	// ReasonNoRolloutPlugin: the verb is an out-of-tree kubectl plugin with
	// no single-call API form.
	ReasonNoRolloutPlugin = "no_rollout_plugin"
)

ReasonNoClusterAPI and ReasonNoRolloutPlugin are machine-readable prefixes, in the same style as ReasonNoOverlayCheckout / ReasonLocalCluster: a client branches on the prefix without parsing the prose after it.

View Source
const (
	ReasonLocalCluster      = "local_cluster"
	ReasonNoOverlayCheckout = "no_overlay_checkout"
)

The two reasons an overlay read finds nothing, as machine-readable prefixes the portal branches on. They are DIFFERENT situations wanting different words, and a caller cannot tell them apart from an ENOENT:

local_cluster        this cluster is not a deploy target at all. Local
                     installations are operated with `make up` (k3d +
                     ArgoCD); driver.go has refused `docker-local` deploys
                     since the console was written, but nothing set the
                     provider on the local overlay, so that deliberate
                     refusal was unreachable and an operator got an ENOENT
                     instead of the sentence explaining it.

no_overlay_checkout  this node has no deploy checkout on disk. The console
                     was designed around one (MEMQL_DEPLOY_REPO_ROOT, see
                     the deploy-bundle runbook) back when it ran from an
                     operator's machine; when it moved into the identity
                     node the convention did not move with it, and no
                     manifest sets the variable. Where an in-cluster node
                     SHOULD get an overlay is an open design question --
                     this constant is how the surface stays honest until it
                     is answered.
View Source
const (
	MaxPodFileBytes int64 = 2 << 30
)

Variables

This section is empty.

Functions

func AuditEventIdFromError

func AuditEventIdFromError(err error) string

AuditEventIdFromError returns the audit correlation id a refusal carries, or "" for any error that is not one.

Exported because the id is only useful to whoever is presenting the refusal: the streamed bridge (Dispatch) calls it to populate DeployControlResult.audit_event_id, and a dialed Go client calls it to show an operator the reference. "" is a normal answer -- an INVALID_ARGUMENT rejection runs before the gate and writes no event, so there is no id to find.

func Dispatch

Dispatch routes one bridged DeployControlMsg to the matching DeployControlServiceServer method and folds the (result, error) pair into a DeployControlResult.

A unary caller receives failure as a gRPC status error. A multiplexed stream has no per-message status channel -- returning an error there would tear down the whole stream and every other in-flight request with it -- so the status is carried IN the reply: error_code holds the canonical gRPC code and error_message its message. A caller mapping error_code back to a code observes exactly what the unary caller observes.

srv is an interface rather than *Service so the bridge is provably incapable of reaching past the RPC surface into the service's internals (and so a test can substitute a recorder without touching the gate).

func InClusterAvailable

func InClusterAvailable() bool

InClusterAvailable reports whether this process can reach the Kubernetes API with a ServiceAccount identity: the projected token exists AND the API server's address is in the environment.

Both halves are required and neither implies the other. KUBERNETES_SERVICE_* is injected into every pod in the cluster including ones with automountServiceAccountToken false; the token file exists only where a ServiceAccount is actually projected. A substrate chosen on the address alone would build a client that 401s on its first call.

func IsConflict

func IsConflict(err error) bool

IsConflict reports whether err is a 409 from the API server: AlreadyExists on a create, or a resourceVersion mismatch on an update.

func IsForbiddenQuota

func IsForbiddenQuota(err error) bool

IsForbiddenQuota reports whether err is the API server refusing a create because it would exceed a ResourceQuota: a 403 whose body names "exceeded quota". The code alone is not the answer, because a 403 is also what a missing Role says, and the caller waits out the one and must fail on the other.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is a 404 from the API server.

func MapArgoStatus

func MapArgoStatus(raw []byte) (*memqlv1.ArgoStatus, error)

MapArgoStatus maps the raw `kubectl -n argocd get app <name> -o json` bytes into the ArgoStatus proto. An empty/nil input yields a zero-value status (not an error) so a missing Argo app surfaces as "unknown" rather than failing the whole status call.

func MapGateResult

func MapGateResult(raw []byte) (*memqlv1.GateResult, error)

MapGateResult maps `kubectl -n memql get analysisrun -o json` into a GateResult proto. It picks the most-recently-created AnalysisRun and maps each metricResult to a GateLeg. Overall result is "pass" when the run's phase is Successful, "fail" for Failed/Error/Inconclusive, and "unknown" otherwise (Running / no runs).

func MapRolloutList

func MapRolloutList(raw []byte) ([]*memqlv1.RolloutStatus, error)

MapRolloutList maps a `kubectl -n memql get rollout -o json` LIST response (with a top-level items[] array) into RolloutStatus protos. A single-object response (no items[]) is also accepted and mapped as one entry.

func MapRolloutStatus

func MapRolloutStatus(raw []byte) (*memqlv1.RolloutStatus, error)

MapRolloutStatus maps one rollout's raw JSON into a RolloutStatus proto. kind is derived from spec.strategy (blueGreen vs canary).

func NamespaceFromEnv

func NamespaceFromEnv() string

NamespaceFromEnv reports the namespace this process is running in.

The projected file first and the environment second, because the file is what the API server itself considers authoritative and MEMQL_NAMESPACE is a convenience an operator can set wrongly. Empty when neither is present, which every caller here treats as "not in a cluster".

func RestartDeployment

func RestartDeployment(ctx context.Context, namespace, name string) error

RestartDeployment performs the in-cluster equivalent of `kubectl rollout restart deployment/<name>` in namespace.

It is idempotent in the only sense that matters: calling it twice stamps two different timestamps and therefore rolls twice, which is what "restart" means. It is NOT a no-op on a second call, and a caller that wants one has to decide that for itself -- the package pipeline does, by rolling only when the active-set pointer actually moved.

Refuses with ReasonNoClusterAPI when this process is not in a cluster, so a developer machine gets a named refusal rather than a confusing dial error.

func RollTargetsEnvNameForHint

func RollTargetsEnvNameForHint() string

RollTargetsEnvNameForHint exposes that literal to the test that pins it. Exported for one caller and named so that reading it as a general accessor is uncomfortable -- the value an operator should read is packages.RollTargetsEnv.

Types

type ClusterAPI

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

ClusterAPI is a minimal Kubernetes API-server client authenticated with the pod's own projected ServiceAccount.

It is the whole of this repository's in-cluster write substrate, and it is deliberately small: a request method, a streaming GET for the reads that outlive one, a token that is re-read, and the cluster CA. Everything above it composes paths and bodies. See the header of this file for why the API server rather than kubectl, a sidecar or client-go -- the reasoning applies unchanged to every caller, which is why this is one type rather than one per feature.

func NewClusterAPI

func NewClusterAPI() (*ClusterAPI, error)

NewClusterAPI builds the API-server client from the pod's projected ServiceAccount. It reads the token ONCE here, which is a deliberate limitation worth stating: a projected token is refreshed in place by the kubelet, so a long-lived process holding the first read would eventually present an expired one. The re-read is in tokenNow() below; this field is the fallback for the case where the file becomes unreadable later.

func NewClusterAPIWith

func NewClusterAPIWith(base, token string, client *http.Client) *ClusterAPI

NewClusterAPIWith builds a ClusterAPI against an explicit API server. Tests pass an httptest server; production code keeps NewClusterAPI.

token is sent as given and is the whole credential: the projected ServiceAccount file NewClusterAPI re-reads is never consulted, so a test that runs inside a pod does not present the pod's own token to whatever server it named. client is the per-call client, used as given, and its Timeout bounds every Do. Stream runs on a copy of it that shares its Transport and has no Timeout. A nil client is the stock transport with the per-call timeout.

func (*ClusterAPI) Do

func (e *ClusterAPI) Do(ctx context.Context, method, path, contentType string, body []byte) ([]byte, error)

Do issues one API-server request and returns the body. The exported form of `do`, for callers outside this file.

`path` is everything after the API server's host, e.g. `apis/networking.k8s.io/v1/namespaces/memql/ingresses/x`.

func (*ClusterAPI) GetMetadata

func (e *ClusterAPI) GetMetadata(ctx context.Context, path string) ([]byte, error)

GetMetadata reads one named object's identity without requesting its data. Like ListMetadata, it refuses servers that cannot provide metadata alone.

func (*ClusterAPI) ListMetadata

func (e *ClusterAPI) ListMetadata(ctx context.Context, path string) ([]byte, error)

ListMetadata issues a GET of a collection, as Do does, asking for the objects' metadata alone (metadataListAccept): a list of Secrets carries none of their values. Measured against a v1.35 k3s API server (2026-10-04): the answer is a PartialObjectMetadataList whose items hold metadata only, labelSelector, limit and continue apply as to a full list, and metadata.continue is absent on the last page. `path` is as for Do, query string included.

func (*ClusterAPI) ReadPodFile

func (e *ClusterAPI) ReadPodFile(ctx context.Context, namespace, pod, container, file string, dst io.Writer, maxBytes int64) (int64, error)

ReadPodFile copies one file through Kubernetes' authenticated exec protocol. It executes only cat with a separate literal path argument: no shell, stdin, terminal, uploaded executable, or caller-selected command. The caller must authorize and bind the pod/container identity before and after this read; Kubernetes exec itself offers no UID precondition. Bytes remain untrusted.

Output is streamed with bounded memory and a 2 GiB maximum. Success requires the remote command's Success status AND normal transport closure. Partial bytes, a lost status, cancellation, stderr overflow and protocol errors are failures; a caller must discard partial output. This call never retries. A supplied writer must return from Write (and honor cancellation if it can block). The caller owns it. The operation has a maximum 30-minute lifetime.

func (*ClusterAPI) ReadPodFileResumable

func (e *ClusterAPI) ReadPodFileResumable(ctx context.Context, namespace, pod, container, file string, dst io.Writer, maxBytes int64) (int64, error)

ReadPodFileResumable reads an immutable file in bounded ranges. Each range must finish with a successful command status and normal transport closure and contain its full expected length before any bytes reach dst. The file length is obtained with a fixed read-only stat command. An incomplete range is discarded and retried, at most three attempts; earlier verified ranges are never replayed.

The caller must establish immutability and bind the pod/container identity before and after the complete read, as for ReadPodFile. Partial overall output must be discarded on failure. The fixed read-only dd command uses literal arguments, no shell, stdin, output file or caller-selected options. Memory is bounded by one 8 MiB range, output by maxBytes, and total time by 30 minutes (or the caller's earlier deadline). No credentials are sent to the container.

func (*ClusterAPI) Stream

func (e *ClusterAPI) Stream(ctx context.Context, path string) (io.ReadCloser, error)

Stream issues a GET whose body the caller reads incrementally: a pod's log with follow=true is the case it exists for. `path` is as for Do, query string included.

It is NOT bounded by the per-call timeout (k8sRequestTimeout). A followed log runs for its step's whole lifetime, and Client.Timeout would cut the body read off with it, so the caller's context is the only bound: a caller that never cancels it holds the connection until the server ends the stream. The caller owns the returned reader and must Close it.

A non-2xx answer is a *StatusError, the same as Do's, carrying at most the first 64 KiB of the body; the response body is closed before it is returned.

The JSON Accept header it shares with Do is deliberate even though a log is text: the API server negotiates a serializer before it streams, so `Accept: text/plain` alone is refused with a 406, while `application/json` is answered 200 with the text body (measured against a v1.32 k3s API server, 2026-10-03).

type Executor

type Executor interface {
	// RunRollback reverts the overlay commit identified by sha via
	// `git revert --no-edit <sha>`. Because a digest change is one commit
	// touching one overlay, reverting it re-pins exactly the prior digests --
	// which is what makes rollback a git operation rather than a second
	// forward action.
	RunRollback(ctx context.Context, sha string) (output string, err error)

	// RunRolloutAction runs `kubectl argo rollouts <action> <rollout>
	// -n <the installation's namespace>` for action in {promote, abort}.
	//
	// `promote`/`abort` here is the ARGO ROLLOUT verb -- advance or cancel an
	// in-flight progressive rollout. It is unrelated to the environment-to-
	// environment promote epic memql#3943 removed, and to the DSL authoring
	// catalog promote; only the name is shared.
	RunRolloutAction(ctx context.Context, rollout, action string) (output string, err error)

	// RunRepair asks ArgoCD to re-converge this installation onto its
	// committed overlay (memql#4209): a hard refresh of the installation's
	// Application (re-fetch the manifests, discarding the repo-server cache)
	// followed by an explicit sync operation with prune, both through
	// `kubectl -n argocd ... app <the installation's Application>` -- the
	// command deploy/argocd/README.md documents for an operator-triggered
	// sync, not a new dialect and never a direct apply.
	//
	// marker is stamped into the Operation's info list under
	// repairOperationInfoName, which is how the watcher tells THIS sync apart
	// from whatever operation the Application last ran: ArgoCD echoes the
	// executed Operation on status.operationState, so a "Succeeded" observed
	// before the controller has picked the new operation up is recognisable
	// as the previous one's verdict rather than this one's.
	//
	// Provider-neutral by construction: the local k3d cluster and the cloud
	// cluster reconcile through the same Application (environment parity),
	// so the effect is one command on both. What differs is only what it
	// undoes -- on the cloud the Application is on MANUAL sync, so this is
	// the one act that re-applies drift at all; locally it is the immediate
	// form of the selfHeal the Application already carries.
	RunRepair(ctx context.Context, marker string) (output string, err error)

	// KubectlJSON runs `kubectl <args...>` and returns stdout. Used for
	// the read paths (argo app / rollouts / analysisruns -o json).
	KubectlJSON(ctx context.Context, args ...string) ([]byte, error)

	// Git runs `git <args...>` rooted at the repo and returns stdout.
	Git(ctx context.Context, args ...string) (output string, err error)
}

Executor is THE single side-effect boundary for MemQL deployments (Epic 2 / #2098). Every cluster read, git operation, and action-script invocation goes through it, so the Service logic is testable with a fake AND -- crucially -- so the deploy PACK (examples/deploypack) drives the EXACT same effects through the IntegrationProvider layer instead of re-implementing the shell-outs. The pack acquires this boundary via the exported NewExecutor(repoRoot); its capabilities (commit / argoSync / observeReconciledState) call the same methods the gRPC Service does. Keeping the effects here -- one place -- is what makes the DSL automation layer ADDITIVE rather than a parallel, drifting copy.

Read paths use KubectlJSON and never mutate. Action paths go through `git revert` and `kubectl argo rollouts promote|abort` -- NEVER ad-hoc `kubectl set image`.

Every cluster address here is THIS installation's (service.go's clusterNamespace). It was a per-environment lookup for the length of epic memql#3748; memql#3943 removed the concept, so there is one address again.

Capability-script contract (#2221): the deploy/ops scripts a DSL action resolves to are CAPABILITY SCRIPTS -- non-interactive, structured params in, a single JSON result envelope on stdout, logs on stderr, honest exit codes (docs/internal/design/capability-script-contract.md). Those are run by component/automations/steps, which parses the envelope with core/capabilityresult.ParseCapabilityResult rather than scraping prose. No effect on THIS interface invokes one; git and kubectl are not capability scripts and their output is read directly.

Scope note: the effect SEAM is consolidated here (the deploy pack reuses this Executor). The synchronous Go deploy LIFECYCLE that deploy.go's Deploy/RollbackDeployment once ran (select driver -> apply -> terminal transition) was RETIRED in #2115 step 6: those actions now only validate + kick off the lifecycle (transition to in_progress), and the deploy pack automations (examples/deploypack, anchored on the identity node) own the terminal transition through THIS Executor's effects. The legacy console actions (Rollback / RolloutAction) still call these effects synchronously.

func NewExecutor

func NewExecutor(repoRoot string) Executor

NewExecutor returns the real Executor anchored at repoRoot -- the SAME side-effect boundary the deploy-control Service uses, exported so the deploy PACK (examples/deploypack, Epic 2 / #2095) can drive the same effects through the IntegrationProvider boundary without duplicating the wiring. An empty repoRoot anchors at the process working directory, matching NewService's RepoRoot default.

WHICH SUBSTRATE, and why it is detected rather than configured (memql#4257). Inside a cluster the effects go through the Kubernetes API with the pod's own ServiceAccount (k8sapi.go); outside one they shell out to kubectl + git as they always have. The choice is made by asking whether a ServiceAccount token is actually projected here, because that is the fact that decides whether the in-cluster path can work at all -- an env var would let an operator select a substrate this process cannot use, and the failure would arrive at the first deploy verb rather than at boot.

It is NOT an `if env == "..."` branch, and the distinction matters because this repository forbids those outright (TestNoEnvironmentBranchingInEngineCode, empty exemption map). There is no environment here to read. A pod in the k3d parity cluster and a pod on AKS take the SAME branch, for the same reason, and an operator machine takes the other one -- that is the local/cloud deploy TARGET axis the design keeps, resolved from an observable fact about the process rather than from a label somebody set.

A construction failure is not fatal: it falls back to the exec substrate and the verbs refuse as they did before, which is strictly better than a node that will not start because its deploy console cannot reach ArgoCD.

type Lockfile

type Lockfile struct {
	// Version is the release version.
	Version string
	// ValidatedAt is the RFC3339 timestamp stamped when the deep gate
	// passed.
	ValidatedAt string
	// Gate is the gate provenance string.
	Gate string
	// EngineVersion is the engine version the carrier + SPA were built
	// against.
	EngineVersion string
	// Components maps short component name -> its pinned digest + repo.
	Components map[string]LockfileComponent
}

Lockfile is the typed projection of a release lockfile (releases/<version>.yaml) -- the ATOMIC unit of promotion (deployment-v2 Phase 4, znasllc-io/memql#702).

The components map is keyed by the short component name (no acr prefix); the two cross-repo entries (the carrier + the product SPA) additionally carry builtAgainstEngine, which the coherence gate requires to equal EngineVersion.

func ParseLockfile

func ParseLockfile(raw []byte) (Lockfile, error)

ParseLockfile parses a release lockfile's raw bytes into a Lockfile.

type LockfileComponent

type LockfileComponent struct {
	// Repo is the source repository (e.g. "znasllc-io/memql").
	Repo string
	// Digest is the pinned "sha256:<64hex>" image authority.
	Digest string
	// BuiltAgainstEngine is set only on the cross-repo components
	// (the carrier + the product SPA); must equal EngineVersion.
	BuiltAgainstEngine string
}

LockfileComponent is one entry of the lockfile's components map.

type Options

type Options struct {
	// Logger is required.
	Logger *slog.Logger
	// Audit is the identity AuditLogger that write actions + denials
	// emit to. Required.
	Audit identity.AuditLogger
	// RepoRoot anchors on-disk overlay/lockfile reads + action-script
	// invocation. Defaults to the current working directory when empty.
	RepoRoot string
	// Executor is the side-effect boundary. Defaults to the real
	// os/exec-backed executor anchored at RepoRoot when nil.
	Executor Executor
	// Clock is the time source (defaults to time.Now UTC).
	Clock func() time.Time
	// Engine, when set, persists deployments as v1:cluster:deployment
	// records (#1872): the write RPCs write a record at deploy start
	// (in_progress) and transition it (succeeded/failed) as the rollout
	// resolves. Optional -- nil leaves the deploy path unchanged (no
	// persistence), which is what unit tests + engineless binaries get.
	Engine identity.EngineExecutor
	// RepairPollInterval and RepairCeiling bound the repair watcher
	// (memql#4209): how often the identity node re-reads the ArgoCD
	// Application after a repair kick-off, and how long it waits for the
	// sync to land synced AND healthy before the repair record is resolved
	// to failed. Zero selects the defaults (defaultRepairPollInterval /
	// defaultRepairCeiling).
	RepairPollInterval time.Duration
	RepairCeiling      time.Duration
}

Options configures NewService.

type Overlay

type Overlay struct {
	// PromotedVersion is the release version parsed from the prod
	// overlay's "Promoted from releases/<version>.yaml" comment.
	// Empty for staging.
	PromotedVersion string
	// Namespace is the kustomization's namespace field.
	Namespace string
	// Images is the ordered images: list (8 components).
	Images []OverlayImage
}

Overlay is the typed projection of a kustomize overlay kustomization.yaml -- specifically the images: block that is the SINGLE image authority for an environment (deployment-v2 Phase 1, znasllc-io/memql#699).

PromotedVersion is parsed from a LEGACY provenance comment

# Promoted from releases/<version>.yaml by scripts/release/promote.sh ...

that the retired promote script wrote as the prod overlay's first line. No overlay in this tree carries one any more and nothing writes one: since memql#3769 both environments live in ONE repository, so a promote's provenance is the COMMIT (executor.go's promoteCommitMessage) -- the author, the timestamp and the exact digest diff, none of which a comment line can restate without becoming a second copy to keep honest.

The parse is kept because it is free and reads an older checkout correctly. Treat an empty PromotedVersion as the normal case rather than as missing data: GetDeploymentStatus's `version` field is empty for both environments today, and the answer to "what is production on" is the digest set below it.

func ParseOverlay

func ParseOverlay(raw []byte) (Overlay, error)

ParseOverlay parses a kustomize overlay kustomization.yaml's raw bytes into an Overlay. The promoted-version provenance comment (if present) is parsed from the leading comment lines; yaml.Unmarshal ignores comments, so we scan the raw bytes for it separately.

type OverlayImage

type OverlayImage struct {
	// Name is the fully-qualified image name (e.g.
	// "acrmemql.azurecr.io/memql-identity").
	Name string
	// Digest is the pinned "sha256:<64hex>" image authority.
	Digest string
}

OverlayImage is one entry of the overlay's images: list.

func (OverlayImage) ShortName

func (i OverlayImage) ShortName() string

ShortName returns the image name with the ACR registry prefix stripped, matching the lockfile's component map keys (e.g. "acrmemql.azurecr.io/memql-identity" -> "memql-identity").

type RepairUndefinedError

type RepairUndefinedError struct {
	Provider string
}

RepairUndefinedError is the typed refusal for a provider with no defined repair. It is returned INSIDE the ActionResult (ok=false, audited as a failure, the audit id on the result) rather than as a gRPC status, matching how Deploy reports a provider it cannot ship to; errors.As recovers it from the failure reason a test or a log reader holds.

func (*RepairUndefinedError) Error

func (e *RepairUndefinedError) Error() string

type Service

type Service struct {
	memqlv1.UnimplementedDeployControlServiceServer
	// contains filtered or unexported fields
}

Service implements memqlv1.DeployControlServiceServer.

func NewService

func NewService(opts Options) (*Service, error)

NewService constructs the deploy-control service.

func (*Service) CutVersion

CutVersion creates a new pending deployment at the chosen next version (#1877). The target is the current version bumped by `bump` (patch default), or an explicit `version` override. Developer-or-above gated (#1876); emits exactly one audit event (success / failure). Invalid or duplicate versions are rejected.

func (*Service) Deploy

Deploy ships a cut `pending` deployment record (#1877) to its target. It validates the record's provider, transitions the record pending -> in_progress, and returns an async ack: the in_progress CDC edge triggers the deploy pack's driveDeploymentInProgress automation (examples/deploypack, E2.3), which observes ArgoCD's reconciled state and owns the succeeded|failed terminal transition. Owner/admin/developer gated; emits exactly one audit event.

func (*Service) GetDeploymentStatus

GetDeploymentStatus returns the aggregate deployment view for this installation. Read-only; gated to owner/admin (#728). A successful read is NOT audited (reads stay un-audited on success); a denial emits a blocked audit event via authorize.

func (*Service) Register

func (s *Service) Register(grpcServer *grpc.Server)

Register attaches the DeployControlService implementation to the supplied gRPC server. Must be called BEFORE the server starts serving.

func (*Service) Repair

Repair re-converges this installation onto its committed overlay (memql#4209): see the file comment for what that is and is not.

Owner-only (authorizeOwner) -- the RollbackDeployment floor, not Deploy's: a repair mutates a running cluster with no Git revert trail. The gate runs FIRST; there is no argument to validate after it (RepairRequest is empty). Every refusal after the gate -- undefined provider, a repair already in flight, a sync already running on the Application, a kick-off that failed -- is an ActionResult with ok=false and a reason, audited as a failure with its id on the result, so the caller can quote it on either transport.

func (*Service) Rollback

Rollback reverts the overlay commit identified by commit_sha via `git revert`.

func (*Service) RollbackDeployment

func (s *Service) RollbackDeployment(ctx context.Context, req *memqlv1.RollbackDeploymentRequest) (*memqlv1.ActionResult, error)

RollbackDeployment redeploys a prior SUCCEEDED deployment's stored image digest (#1878). It is NOT a blue-green color flip: it creates a NEW deployment record at in_progress pointing at the historical digest (previousDeploymentId -> toDeploymentId). That create-at-in_progress CDC edge triggers the deploy pack's driveDeploymentInProgress automation, which re-pins the historical digest via deployRunPromote and -- because the record carries previousDeploymentId -- lands it in `rolled_back` (#2168). Rollback is owner-only (#1876); emits one audit event.

func (*Service) RolloutAction

func (s *Service) RolloutAction(ctx context.Context, req *memqlv1.RolloutActionRequest) (*memqlv1.ActionResult, error)

RolloutAction promotes or aborts an in-flight Argo Rollout.

func (*Service) SuggestNextVersion

SuggestNextVersion proposes the next major/minor/patch off this installation's current version (#1877). Read-only; developer-or-above gated as the read companion to CutVersion (#1876), not audited on success (a denial emits a blocked audit event via authorizeDeploy).

type StatusError

type StatusError struct {
	Method string
	Path   string
	Code   int
	Status string
	Body   string
}

StatusError is a non-2xx response from the API server.

It exists so a caller can branch on the CODE rather than on the rendered message. The one that needs it today is a delete treating NotFound as success -- unbinding twice is a legitimate thing for a retry to do, and a string match for "404" would also swallow a 500 that merely mentioned one.

func (*StatusError) Error

func (e *StatusError) Error() string

Jump to

Keyboard shortcuts

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