Documentation
¶
Overview ¶
Package workspace manages the full lifecycle of k8shell workspaces: creating and tearing down Helm releases, starting and stopping pods, injecting workspace containers into existing workloads, discovering running workspaces via Kubernetes label selectors, and streaming provisioning status events to callers over a channel.
Index ¶
- Constants
- Variables
- func AppliedPatchesFromValues(values map[string]interface{}) ([]authz.ProvisionPatch, error)
- func BlueprintFromValues(values map[string]interface{}) (*models.Blueprint, error)
- func DeleteWorkspacePAT(ctx context.Context, identityClient *identity.IdentityClient, ...) error
- func DeleteWorkspacePATFromLabels(ctx context.Context, identityClient *identity.IdentityClient, ...) error
- func DeleteWorkspacePod(ctx context.Context, helmClient *helm.Client, ...) error
- func FindWorkspace(ctx context.Context, helmClient *helm.Client, workspace string, ...) (*models.WorkspaceDetails, *corev1.Pod, error)
- func FindWorkspaceByAlias(ctx context.Context, helmClient *helm.Client, org, alias string) (*models.WorkspaceDetails, error)
- func FindWorkspaceHelmRelease(ctx context.Context, helmClient *helm.Client, name string) (*release.Release, error)
- func MarkBlueprintOutdated(workspaces []*models.WorkspaceDetails, current BlueprintRevisionFunc)
- type BlueprintDiff
- type BlueprintRevisionFunc
- type DiffOp
- type DiffOptions
- type DiffRow
- type EjectOptions
- type EventSeverity
- type GetWorkspacesOptions
- type GetWorkspacesResult
- type InjectOptions
- type InjectWorkloadInfo
- type PodEvent
- type PodLifecycleStage
- type PodStateSnapshot
- type PodWatcher
- type ProvisionOptions
- type UpdateOptions
- type UpdateResult
- type Values
- type WorkloadOwner
- type Workspace
- func NewWorkspace(workspaceName string, blueprint *models.Blueprint, user *models.User, ...) (*Workspace, error)
- func NewWorkspaceForEject(name string, helmClient *helm.Client) (*Workspace, error)
- func NewWorkspaceForUninstall(name string, helmClient *helm.Client) (*Workspace, error)
- func NewWorkspaceFromHelmRelease(ctx context.Context, name string, helmClient *helm.Client, ...) (*Workspace, error)
- func (w *Workspace) Blueprint() *models.Blueprint
- func (w *Workspace) CreateLock() *WorkspaceLock
- func (w *Workspace) DeletePAT(ctx context.Context) error
- func (w *Workspace) Eject(ctx context.Context, opts *EjectOptions) error
- func (w *Workspace) EnsureNodeReachable(ctx context.Context) error
- func (w *Workspace) ExistsAndRunning(ctx context.Context) (bool, *models.WorkspaceStatus, error)
- func (w *Workspace) FetchUserEnvVars(ctx context.Context) error
- func (w *Workspace) GetPodStatus(ctx context.Context) (*models.WorkspaceStatus, error)
- func (w *Workspace) Inject(ctx context.Context, opts *InjectOptions) (*models.WorkspaceStatus, error)
- func (w *Workspace) IsInjected(ctx context.Context, namespace, workloadKind, workloadName string) (bool, error)
- func (w *Workspace) IsInstalled(ctx context.Context) (bool, error)
- func (w *Workspace) MintPAT(ctx context.Context, scopes []string) (string, error)
- func (w *Workspace) Provision(ctx context.Context, opts *ProvisionOptions) (*models.WorkspaceStatus, error)
- func (w *Workspace) RefreshPATSecret(ctx context.Context) error
- func (w *Workspace) ReleasedResources(_ context.Context) (map[string]map[string]any, error)
- func (w *Workspace) RenderedResources(ctx context.Context, injectNamespace string) (map[string]map[string]any, error)
- func (w *Workspace) Selector() string
- func (w *Workspace) SetAppliedObligations(obligations map[string]string)
- func (w *Workspace) SetBlueprintChain(chain []string)
- func (w *Workspace) SetBlueprintRevision(revision string)
- func (w *Workspace) SetJobId(jobId string)
- func (w *Workspace) SetPAT(pat string)
- func (w *Workspace) SetProvisionContext(mode authz.WorkspaceProvisionMode, ...)
- func (w *Workspace) StopPod(ctx context.Context) error
- func (w *Workspace) Template(ctx context.Context) (string, error)
- func (w *Workspace) TemplateHash(ctx context.Context) (string, error)
- func (w *Workspace) Uninstall(ctx context.Context, timeout time.Duration, wait bool, lock bool) error
- func (w *Workspace) UpdateResourcesAndNetwork(ctx context.Context, opts UpdateOptions) (*UpdateResult, error)
- func (w *Workspace) UserSource() string
- func (w *Workspace) Username() string
- func (w *Workspace) Values() (map[string]interface{}, error)
- func (w *Workspace) WaitForPodGone(ctx context.Context, timeout time.Duration) error
- type WorkspaceLabels
- type WorkspaceLock
- func (l *WorkspaceLock) Acquire(ctx context.Context) (bool, error)
- func (l *WorkspaceLock) AcquireWithOptions(ctx context.Context, waitForLock bool) (bool, error)
- func (l *WorkspaceLock) KeepAlive(ctx context.Context, interval time.Duration) <-chan error
- func (l *WorkspaceLock) Release(ctx context.Context) error
- func (l *WorkspaceLock) Renew(ctx context.Context) error
- func (l *WorkspaceLock) TryAcquire(ctx context.Context) (bool, error)
Constants ¶
const WORKSPACE_DEFAULT_PAGE_SIZE = 20
Default page size for GetWorkspaces pagination when limit is not specified or invalid
Variables ¶
var ( // ErrWebProxyAliasHeld is returned when a web-proxy alias is already // held by another workspace of the same organization. ErrWebProxyAliasHeld = errors.New("web-proxy alias is held by another workspace") // ErrNoWebProxyRoute is returned when a web-proxy alias is set on a // workspace that publishes no web-proxy route. ErrNoWebProxyRoute = errors.New("workspace publishes no web-proxy route") )
var (
ErrLockAlreadyHeld = fmt.Errorf("lock is already held by another process")
)
var ErrNodeUnreachable = errors.New("workspace node is unreachable")
ErrNodeUnreachable is returned when a workspace cannot be started because its pod is stuck deleting on an unreachable node. The workspace starts once the node returns, or it can be terminated.
var WorkspacesQueryDescriptor = query.NewDescriptor("workspaces"). Field("name", queryv1.FieldType_FIELD_TYPE_STRING, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_IN). Field("username", queryv1.FieldType_FIELD_TYPE_STRING, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_IN). Field("organization", queryv1.FieldType_FIELD_TYPE_STRING, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_IN). Field("blueprint", queryv1.FieldType_FIELD_TYPE_STRING, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_IN). Field("origin", queryv1.FieldType_FIELD_TYPE_STRING, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_IN). Field("namespace", queryv1.FieldType_FIELD_TYPE_STRING, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_IN). Field("status", queryv1.FieldType_FIELD_TYPE_STRING, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_IN). Field("repo_owner", queryv1.FieldType_FIELD_TYPE_STRING, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_IN, queryv1.Operator_OPERATOR_EXISTS). Field("repo_name", queryv1.FieldType_FIELD_TYPE_STRING, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_IN, queryv1.Operator_OPERATOR_EXISTS). Field("repo_ref", queryv1.FieldType_FIELD_TYPE_STRING, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_IN, queryv1.Operator_OPERATOR_EXISTS). Field("workspace_type", queryv1.FieldType_FIELD_TYPE_STRING, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_IN). Field("workload_kind", queryv1.FieldType_FIELD_TYPE_STRING, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_IN, queryv1.Operator_OPERATOR_EXISTS). Field("workload_name", queryv1.FieldType_FIELD_TYPE_STRING, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_IN, queryv1.Operator_OPERATOR_EXISTS). Field("network_policy_class", queryv1.FieldType_FIELD_TYPE_STRING, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_IN, queryv1.Operator_OPERATOR_EXISTS). Field("web_proxy_port", queryv1.FieldType_FIELD_TYPE_STRING, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_IN, queryv1.Operator_OPERATOR_EXISTS). Field("cpu", queryv1.FieldType_FIELD_TYPE_STRING, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_GT, queryv1.Operator_OPERATOR_GTE, queryv1.Operator_OPERATOR_LT, queryv1.Operator_OPERATOR_LTE). Field("memory", queryv1.FieldType_FIELD_TYPE_STRING, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_GT, queryv1.Operator_OPERATOR_GTE, queryv1.Operator_OPERATOR_LT, queryv1.Operator_OPERATOR_LTE). Field("created", queryv1.FieldType_FIELD_TYPE_DATETIME, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_GT, queryv1.Operator_OPERATOR_GTE, queryv1.Operator_OPERATOR_LT, queryv1.Operator_OPERATOR_LTE). Field("blueprint_revision", queryv1.FieldType_FIELD_TYPE_STRING, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_IN, queryv1.Operator_OPERATOR_EXISTS). Field("blueprint_outdated", queryv1.FieldType_FIELD_TYPE_BOOLEAN, queryv1.Operator_OPERATOR_EQ, queryv1.Operator_OPERATOR_NE, queryv1.Operator_OPERATOR_EXISTS). DefaultSort("name", queryv1.SortDir_SORT_DIR_ASC). Build()
WorkspacesQueryDescriptor advertises which workspace fields are queryable/sortable via QueryWorkspaces, and which operators are valid on each. It is served as-is by GetWorkspacesQuerySchema and reused by QueryWorkspaces to validate incoming payloads, so the advertised schema and its enforcement can never drift apart.
Functions ¶
func AppliedPatchesFromValues ¶ added in v0.17.1
func AppliedPatchesFromValues(values map[string]interface{}) ([]authz.ProvisionPatch, error)
AppliedPatchesFromValues returns the policy patches that were applied to a workspace's blueprint when it was provisioned, as recorded in its stored values. Re-applying them to the current blueprint lets a diff show only real blueprint changes. Nothing is evaluated: the patches are replayed exactly as recorded. A release that recorded none yields nil.
func BlueprintFromValues ¶ added in v0.17.1
BlueprintFromValues recovers the blueprint from a workspace's stored Helm values. Decoding into models.Blueprint drops everything that is not a blueprint field, such as the provisioner-internal "__" keys and the per-script "__file" entries.
func DeleteWorkspacePAT ¶ added in v0.16.0
func DeleteWorkspacePAT(ctx context.Context, identityClient *identity.IdentityClient, username, canonicalId string) error
DeleteWorkspacePAT deletes the personal access token minted for a workspace, identified by the canonical ID stored as its token Name under the given username. It is a no-op, not an error, when identityClient is nil, username/canonicalId are empty, or no matching token is found — PAT deletion is always best-effort and must never block workspace teardown.
func DeleteWorkspacePATFromLabels ¶ added in v0.16.0
func DeleteWorkspacePATFromLabels(ctx context.Context, identityClient *identity.IdentityClient, labels map[string]string) error
DeleteWorkspacePATFromLabels deletes a workspace's PAT using the username/canonical-id labels already present on its pod (or injected workload pod template). It is used by cleanup paths that intentionally avoid a full identity lookup, e.g. bulk user-workspace deletion that runs after the owning user may already be gone.
func DeleteWorkspacePod ¶ added in v0.16.0
func DeleteWorkspacePod(ctx context.Context, helmClient *helm.Client, identityClient *identity.IdentityClient, pod *corev1.Pod) error
DeleteWorkspacePod hard-deletes the workspace represented by pod, branching on whether it is a standalone Helm-managed workspace or one injected into another workload. It acquires the workspace's own distributed lock before deleting and releases it when done, mirroring the single-workspace delete path so concurrent requests for the same workspace stay serialised.
Unlike the single-workspace DeleteWorkspace RPC, this does not look up the owning user's identity record — it is used by user-cleanup flows that run after the user has already been deleted, where that lookup would fail. The workspace's PAT is still deleted, using only the username/canonical-id labels already on pod, via identityClient (which may be nil if identity cleanup should be skipped entirely, e.g. no identity client is configured).
If the workspace's lock is already held — e.g. a concurrent DeleteWorkspace call for the same workspace is in flight — it returns ErrLockAlreadyHeld so bulk callers can skip the workspace and continue rather than fail the batch.
func FindWorkspace ¶
func FindWorkspace(ctx context.Context, helmClient *helm.Client, workspace string, injectionNamespaces []string, useCache bool) (*models.WorkspaceDetails, *corev1.Pod, error)
FindWorkspace finds a workspace by name and returns its status. useCache serves the lookup from a short-lived cache (see GetWorkspacesOptions.UseCache) and must only be true for read-only callers — pass false for any lookup that precedes a mutation (stop, delete, eject) so it observes current state.
func FindWorkspaceByAlias ¶ added in v0.16.8
func FindWorkspaceByAlias(ctx context.Context, helmClient *helm.Client, org, alias string) (*models.WorkspaceDetails, error)
FindWorkspaceByAlias returns the workspace holding the web-proxy alias within org. It returns models.ErrWorkspaceNotFound when no workspace holds it, including when the holder's live alias no longer matches the claim.
func FindWorkspaceHelmRelease ¶
func FindWorkspaceHelmRelease(ctx context.Context, helmClient *helm.Client, name string) (*release.Release, error)
FindworkspaceByName finds a workspace by its name using Helm client and returns the corresponding release
func MarkBlueprintOutdated ¶ added in v0.17.1
func MarkBlueprintOutdated(workspaces []*models.WorkspaceDetails, current BlueprintRevisionFunc)
MarkBlueprintOutdated sets BlueprintOutdated on each workspace by comparing its recorded BlueprintRevision with the blueprint's current revision. Each distinct (organization, blueprint) pair is resolved once per call, so listing many workspaces of the same blueprint costs a single lookup.
BlueprintOutdated is left nil when it cannot be determined: the workspace carries no revision, the blueprint no longer resolves, or the workspace was provisioned from a repository's k8shell file. Only the repo form of a userstr sets RepoName, and for it the recorded revision is that of the file composed with its template, not of the template named in Blueprint, so comparing the two would be meaningless.
Types ¶
type BlueprintDiff ¶ added in v0.17.1
type BlueprintDiff struct {
// WorkspaceYAML and BlueprintYAML are the normalized, redacted
// documents that were compared.
WorkspaceYAML string
BlueprintYAML string
// Rows is the full documents aligned side by side.
Rows []DiffRow
// Identical is true when the two documents are equal.
Identical bool
Added, Removed, Changed int
}
BlueprintDiff is the result of comparing a workspace's blueprint with the blueprint it currently resolves to.
func DiffBlueprints ¶ added in v0.17.1
func DiffBlueprints(deployed, current *models.Blueprint, opts DiffOptions) (*BlueprintDiff, error)
DiffBlueprints compares deployed, the blueprint recovered from a workspace's stored values, with current, the blueprint as it evaluates now. Both are normalized per opts and redacted before being compared.
type BlueprintRevisionFunc ¶ added in v0.17.1
BlueprintRevisionFunc returns the current revision of the named blueprint as seen by a user of org, or "" if it does not exist. It is satisfied by (*blueprint.BlueprintManager).GetBlueprintRevision.
type DiffOptions ¶ added in v0.17.1
type DiffOptions struct {
// WorkspaceName and Organization identify the DNS defaults that
// Workspace.Values fills in when the blueprint leaves hostname and
// subdomain unset.
WorkspaceName string
Organization string
// UserEnvKeys are the names of the user's own environment variables,
// which Workspace.Values merges into env on top of the blueprint's.
UserEnvKeys []string
}
DiffOptions describes the workspace a blueprint is being normalized for.
type DiffRow ¶ added in v0.17.1
DiffRow is one aligned row of a side-by-side diff. Line numbers are 1-based; 0 means the side has no line in this row.
type EjectOptions ¶
type EjectOptions struct {
// Namespace is the namespace that contains the target workload.
Namespace string
// WorkloadName is the name of the workload to eject from.
WorkloadName string
// WorkloadKind is the kind of the target workload (Deployment, StatefulSet, DaemonSet).
// Defaults to "Deployment" when empty.
WorkloadKind string
// Timeout is the maximum number of seconds to wait for the rolling update
// that removes the injected containers. 0 means use the default (60 s).
Timeout int
}
EjectOptions controls the behaviour of workspace ejection from a workload.
type EventSeverity ¶
type EventSeverity string
EventSeverity classifies how actionable a pod event is.
const ( EventSeverityInfo EventSeverity = "info" EventSeverityWarning EventSeverity = "warning" EventSeverityCritical EventSeverity = "critical" )
type GetWorkspacesOptions ¶
type GetWorkspacesOptions struct {
// Usernames filters by the owning user(s). Pods matching any listed
// username are returned (an OR match).
Usernames []string
Organization string
Blueprint string
WorkspaceName string
TargetNamespace string
CanonicalId string
// InjectNamespaces controls where injected workspaces are discovered.
// Use "*" for cluster-wide discovery.
InjectNamespaces []string
// InjectWorkload and InjectKind filter injected workspaces by the workload they
// were injected into. InjectKind is optional; omitting it matches any kind.
InjectWorkload string
InjectKind string
// UseCache serves the underlying Kubernetes/Helm listings from the
// per-process informer caches, or a short-lived TTL cache where those
// don't apply (see helm.Client's ListDeployedReleasePodsCached and
// ListPodsCached), instead of issuing fresh calls. Only safe for
// read-only callers: leave false (the default) for anything that mutates
// a workspace based on this result (stop, delete, eject), so it observes
// a just-completed change rather than a stale cached one.
UseCache bool
}
GetWorkspacesOptions defines the options for retrieving workspaces with filtering
type GetWorkspacesResult ¶
type GetWorkspacesResult struct {
Workspaces []*models.WorkspaceDetails // list of workspaces matching the filters and pagination
Pods []corev1.Pod // corresponding pods for the workspaces, used for internal processing
}
GetWorkspacesResult defines the result structure for GetWorkspaces function, including the list of workspaces and pagination token
func GetWorkspaces ¶
func GetWorkspaces( ctx context.Context, helmClient *helm.Client, opts GetWorkspacesOptions, ) (*GetWorkspacesResult, error)
GetWorkspaces lists workspaces matching the filters in opts. It queries the target namespace for standalone workspace pods and, when InjectNamespaces is set, each injection namespace (or cluster-wide) for injected workspace pods. Namespace lists are performed concurrently to reduce latency.
func QueryWorkspaces ¶ added in v0.16.0
func QueryWorkspaces(ctx context.Context, helmClient *helm.Client, identityClient *identity.IdentityClient, injectNamespaces []string, currentRevision BlueprintRevisionFunc, payload *queryv1.Payload) (*GetWorkspacesResult, error)
QueryWorkspaces returns workspaces matching payload, as validated against WorkspacesQueryDescriptor and, independent of payload's own Filters, restricted to whatever payload.Obligations mandates (see obligationScope). Workspace state lives in Kubernetes rather than a queryable store, so unlike a SQL-backed resource this can't push an arbitrary filter down as a single query: it discovers workspaces the same way GetWorkspaces does (standalone plus, when injectNamespaces is set, injected workspaces) and applies payload's filters/sort/page in memory.
Listing every workspace on every call would still be wasteful against etcd/apiserver, so equality/IN conditions on username, organization, blueprint, or name — from either Filters or Obligations — are pushed down into GetWorkspacesOptions first, which GetWorkspaces already compiles into a Kubernetes label selector — or, for an exact name match, a direct Get instead of a List. That's a best-effort fetch-side optimization only: the in-memory checks below still re-verify the full payload and obligations against whatever comes back, so correctness never depends on the pushdown being complete.
identityClient resolves the obligations' "roles" dimension, which has no workspace-side equivalent (workspaces carry no role information); it may be nil as long as no caller ever presents a roles obligation.
type InjectOptions ¶
type InjectOptions struct {
// Namespace is the namespace that contains the target workload.
Namespace string
// WorkloadName is the name of the existing workload to inject into.
WorkloadName string
// WorkloadKind is the kind of the target workload (Deployment, StatefulSet, DaemonSet).
// Defaults to "Deployment" when empty.
WorkloadKind string
// WorkspaceCanonicalId is the canonical identifier of the workspace,
// used for tracking and labeling injected resources.
WorkspaceCanonicalId string
// JobId is the identifier of the provisioning job, used for labeling injected resources.
JobId string
// Timeout is the maximum number of seconds to wait for the injected pods to
// become Running. 0 means use the default (120 s).
Timeout int
// Messages receives streaming status events during injection. May be nil.
Messages chan models.WorkspaceStreamEvent
}
InjectOptions controls the behaviour of workspace injection into an existing workload.
type InjectWorkloadInfo ¶ added in v0.16.0
type InjectWorkloadInfo struct {
Namespace string
Kind string
Name string
Replicas int32
Injected bool
Workspace string
Username string
Organization string
Blueprint string
RepoSource string
RepoRevision string
// BlueprintRevision is the revision of the blueprint the injected
// workspace was created from; unrelated to RepoRevision.
BlueprintRevision string
}
InjectWorkloadInfo describes a workload eligible for workspace injection, together with its current injection state.
func ListInjectWorkloads ¶ added in v0.16.0
func ListInjectWorkloads(ctx context.Context, helmClient *helm.Client, namespaces, kinds []string) ([]InjectWorkloadInfo, error)
ListInjectWorkloads lists workloads eligible for workspace injection across the given namespaces and kinds, reporting each workload's current injection state. namespaces of ["*"] expands to every namespace currently in the cluster. kinds defaults to every supported kind when empty. Results are ordered by namespace, then kind, then name.
type PodEvent ¶
type PodEvent struct {
Time time.Time
ObjectKind string
ObjectName string
Reason string
Message string
Severity EventSeverity
}
PodEvent is an enriched Kubernetes event for a pod or one of its dependent PVCs.
type PodLifecycleStage ¶
type PodLifecycleStage string
PodLifecycleStage is the current stage in a pod's lifecycle. Stages progress roughly in order: Scheduling → Pulling → Initializing → Starting → Running. A pod can enter Terminating, Stopped, or Failed from any stage.
const ( StageScheduling PodLifecycleStage = "Scheduling" StagePulling PodLifecycleStage = "Pulling" StageInitializing PodLifecycleStage = "Initializing" StageStarting PodLifecycleStage = "Starting" StageRunning PodLifecycleStage = "Running" StageStopping PodLifecycleStage = "Stopping" StageTerminating PodLifecycleStage = "Terminating" StageNodeLost PodLifecycleStage = "NodeLost" StageStopped PodLifecycleStage = "Stopped" StageFailed PodLifecycleStage = "Failed" StageUnknown PodLifecycleStage = "Unknown" )
type PodStateSnapshot ¶
type PodStateSnapshot struct {
Created time.Time
Stage PodLifecycleStage
Status models.WorkspaceStatusMessage
Message string
Restarts int32
LastFailMessage string
CriticalErr error
Events []PodEvent
}
PodStateSnapshot is the derived workspace state at a single point in time. Produced by AnalyzePod — a pure function with no side effects.
func AnalyzePod ¶
AnalyzePod derives a PodStateSnapshot from a pod and its associated K8s events. events may be nil/empty for a point-in-time check without event history; in that case StagePulling cannot be detected since it is event-driven only. crashLoopThreshold is the per-container restart count at which a BackOff event becomes critical.
type PodWatcher ¶
type PodWatcher struct {
CrashLoopThreshold int32 // per-container restart count that makes BackOff critical; default 2
// contains filtered or unexported fields
}
PodWatcher observes a pod's lifecycle using the Kubernetes watch API. It calls AnalyzePod on each state change and emits WorkspaceStreamEvents.
func NewPodWatcher ¶
func NewPodWatcher(kubeClient kubernetes.Interface, namespace, podName string, log *zerolog.Logger) *PodWatcher
NewPodWatcher creates a PodWatcher with default configuration.
func (*PodWatcher) Watch ¶
func (pw *PodWatcher) Watch(ctx context.Context, opts *ProvisionOptions, waitForRunning bool) (*PodStateSnapshot, error)
Watch observes the pod lifecycle.
If waitForRunning is false, it fetches the current pod and recent events once, derives a snapshot, and returns immediately — suitable for point-in-time status checks.
If waitForRunning is true, it uses the Kubernetes watch API to observe changes in real time until the pod reaches Running, a critical error is detected, the timeout in opts.Timeout elapses, or ctx is cancelled. Status changes and events are emitted to opts.Messages if set.
func (*PodWatcher) WatchByLabel ¶
func (pw *PodWatcher) WatchByLabel(ctx context.Context, labelSelector string, opts *ProvisionOptions) (*PodStateSnapshot, error)
WatchByLabel waits for the first pod matching labelSelector to appear in pw.namespace, then watches it through its full lifecycle exactly like Watch(waitForRunning=true), streaming status and event messages to opts.Messages.
This is the correct method for injection mode, where the workspace containers run inside a Deployment's pod (whose name is not known in advance — it is assigned by the ReplicaSet controller when the rolling update fires).
The pod-discovery phase uses half of opts.Timeout (min 30 s, max 90 s) so that the remaining budget is available for the lifecycle watch.
type ProvisionOptions ¶
type ProvisionOptions struct {
Timeout int
Messages chan models.WorkspaceStreamEvent
LockTimeout int
// PATScopes is passed to MintPAT when this call actually commits to
// installing or restarting the workspace (see doInstallation/doStart).
// Minting happens there, under the workspace lock and only once the
// exists/status recheck has confirmed this call is doing the work,
// rather than upfront in the caller — minting upfront raced with
// concurrent duplicate requests: both could pass an unlocked
// "not running yet" check and rotate the token, but only one would
// actually win the lock and install, leaving the identity service's
// token out of sync with whatever got baked into the pod's Secret.
PATScopes []string
}
ProvisionOptions represents the options for provisioning a workspace
type UpdateOptions ¶ added in v0.16.0
type UpdateOptions struct {
// ChangeResources gates the CPU/memory resize. When true, CPU and Memory
// are applied to the workspace's main container via the pods/resize
// subresource; an empty CPU or Memory leaves that limit unchanged.
ChangeResources bool
CPU string
Memory string
// ChangeNetwork gates the network policy update. When true, the workspace's
// NetworkPolicies are re-rendered from the chart and re-applied.
ChangeNetwork bool
// NetworkPolicyClass is the desired class. Empty keeps the workspace's
// current class (read from the live pod's k8shell.io/network-policy label)
// and only re-applies egress, without touching the class label.
NetworkPolicyClass string
// ReplaceEgress gates AllowEgressToCIDRs / AllowEgressToPods. When true they
// replace the workspace's egress shortcuts wholesale (empty lists clear
// them); when false the blueprint's existing egress rules are kept.
ReplaceEgress bool
AllowEgressToCIDRs []string
AllowEgressToPods []map[string]string
// ReplaceWebProxy gates WebProxyPort / WebProxyRoles. When true they replace
// the workspace's web-proxy route wholesale: a zero WebProxyPort clears the
// route (drops the pod's port/roles annotations and the discovery label).
// When false the blueprint's route is kept. This is a pure pod-metadata
// change — no NetworkPolicy is re-rendered.
ReplaceWebProxy bool
WebProxyPort int
WebProxyRoles []string
// ChangeWebProxyAlias gates WebProxyAlias: a non-empty value claims and
// applies that alias (the workspace must publish a route, either already
// or through this update), "" clears it. Clearing the route through
// ReplaceWebProxy clears the alias regardless of this gate.
ChangeWebProxyAlias bool
WebProxyAlias string
}
UpdateOptions describes an out-of-band change to a workspace's CPU/memory limits and/or its network policy. It is applied directly to the live Kubernetes objects, leaving the Helm release untouched.
type UpdateResult ¶ added in v0.16.0
type UpdateResult struct {
ResourcesChanged bool
AppliedCPU string
AppliedMemory string
NetworkChanged bool
AppliedNetworkPolicyClass string
WebProxyChanged bool
AppliedWebProxyPort int
WebProxyAliasChanged bool
AppliedWebProxyAlias string
}
UpdateResult reports the settings in effect after UpdateResourcesAndNetwork.
type Values ¶
type Values struct {
Values map[string]interface{}
}
Values is a typed container for a Helm values map.
type WorkloadOwner ¶
WorkloadOwner identifies the workload that owns a pod injected with a workspace
func FindOwnerWorkload ¶
func FindOwnerWorkload(ctx context.Context, kubeClient kubernetes.Interface, pod *corev1.Pod) (*WorkloadOwner, error)
FindOwnerWorkload identifies the supported workload (Deployment, StatefulSet, DaemonSet) that owns the given pod. It returns an error if the pod is missing the identifying labels or if the
type Workspace ¶
Workspace represents a workspace with Helm client
func NewWorkspace ¶
func NewWorkspace( workspaceName string, blueprint *models.Blueprint, user *models.User, userStr *userstr.CanonicalUserStr, helmClient *helm.Client, identityClient *identity.IdentityClient, config *config.Config, ) (*Workspace, error)
NewWorkspace creates a new workspace with the specified Helm chart
func NewWorkspaceForEject ¶
NewWorkspaceForEject creates a minimal workspace object sufficient to call Eject. Only the workspace name and helm client are required; no user, blueprint, or identity needed.
func NewWorkspaceForUninstall ¶ added in v0.16.0
NewWorkspaceForUninstall creates a minimal workspace object sufficient to call Uninstall. Only the workspace name and helm client are required; no identity lookup is performed, since Uninstall only needs the Helm release name. This matters for cleanup flows that run after the owning user has already been deleted, where an identity lookup would fail.
func NewWorkspaceFromHelmRelease ¶
func NewWorkspaceFromHelmRelease(ctx context.Context, name string, helmClient *helm.Client, identityClient *identity.IdentityClient, config *config.Config) (*Workspace, error)
NewWorkspaceFromHelmRelease creates a workspace instance from an existing Helm release
func (*Workspace) Blueprint ¶ added in v0.17.0
Blueprint returns the blueprint the workspace is provisioned from, after any policy patches were applied.
func (*Workspace) CreateLock ¶
func (w *Workspace) CreateLock() *WorkspaceLock
func (*Workspace) DeletePAT ¶ added in v0.16.0
DeletePAT deletes the personal access token minted for this workspace at the Identity service, if one exists. It is a no-op (not an error) when identity information is unavailable, e.g. for workspace objects built via NewWorkspaceForUninstall/NewWorkspaceForEject for post-user-deletion cleanup — callers on those paths should use DeleteWorkspacePAT directly with data read from the workspace pod's labels instead.
func (*Workspace) Eject ¶
func (w *Workspace) Eject(ctx context.Context, opts *EjectOptions) error
Eject reverses a previous Inject call:
- Reads injection tracking annotations from the workload.
- Updates the workload to remove the injected containers/volumes (rolling update fires).
- Deletes all workspace-labeled resources from the target namespace.
func (*Workspace) EnsureNodeReachable ¶ added in v0.17.4
EnsureNodeReachable returns ErrNodeUnreachable when the workspace pod is stuck deleting on an unreachable node. Such a workspace cannot be stopped (the pod is already being deleted and nothing can finish it); it can only be terminated. A missing pod is not an error.
func (*Workspace) ExistsAndRunning ¶
ExistsRunning checks if the workspace already exists and is running
func (*Workspace) FetchUserEnvVars ¶ added in v0.16.0
FetchUserEnvVars retrieves the effective environment variables for the workspace's owning user from the Identity service (org-level variables overridden by any user-owned variable with the same key) and stores them on the workspace so Values() surfaces them to the workspace pod. Secret values come back redacted from ListUserEnvVars, so each is re-fetched in full via GetUserEnvVar. It is a no-op, not an error, when identityClient or the workspace's user is unset. Values() applies these vars for both standalone and injected provisioning, since both share the same call.
func (*Workspace) GetPodStatus ¶
GetPodStatus fetches the current pod and its events once and returns a point-in-time WorkspaceStatus without blocking for the pod to reach Running.
func (*Workspace) Inject ¶
func (w *Workspace) Inject(ctx context.Context, opts *InjectOptions) (*models.WorkspaceStatus, error)
Inject provisions the k8shell workspace by injecting the workspace containers and volumes into an existing workload. The target workload is identified by the namespace and name provided in the InjectOptions
func (*Workspace) IsInjected ¶
func (w *Workspace) IsInjected(ctx context.Context, namespace, workloadKind, workloadName string) (bool, error)
IsInjected returns true when the named workload in the given namespace carries the injection annotation for this workspace.
func (*Workspace) IsInstalled ¶
IsInstalled reports whether a Helm release for this workspace exists in the target namespace, regardless of its status or whether the pod is running.
func (*Workspace) MintPAT ¶ added in v0.16.0
MintPAT creates a fresh personal access token for the workspace's owning user via the Identity service, stores it on the workspace (see SetPAT) so it is picked up by Values()/RefreshPATSecret, and returns the token. Used before (re)creating a workspace pod, since the previous token is deleted when a workspace is stopped (see DeletePAT).
func (*Workspace) Provision ¶
func (w *Workspace) Provision(ctx context.Context, opts *ProvisionOptions) (*models.WorkspaceStatus, error)
Provision provisions the workspace
func (*Workspace) RefreshPATSecret ¶ added in v0.16.0
RefreshPATSecret updates the workspace's PAT secret in the cluster to hold the token currently set via SetPAT. It is used before re-creating a pod directly from a stored Helm release manifest (see doStart), so the recreated pod picks up a freshly rotated token without requiring a full Helm reinstall.
func (*Workspace) ReleasedResources ¶ added in v0.17.0
ReleasedResources returns the documents of the workspace's installed Helm release, as helm.ManifestDocuments does. A restart recreates the pod from this manifest, so it is what will actually run.
func (*Workspace) RenderedResources ¶ added in v0.17.0
func (w *Workspace) RenderedResources(ctx context.Context, injectNamespace string) (map[string]map[string]any, error)
RenderedResources renders the workspace chart as Provision would, or as Inject would when injectNamespace is set, and returns its documents as helm.ManifestDocuments does. The workspace itself is not modified.
func (*Workspace) Selector ¶
Selector returns the label selector for the workspace used to identify the workspace in Kubernetes It uses the app.kubernetes.io/instance label to match the workspace name
func (*Workspace) SetAppliedObligations ¶
SetAppliedObligations stores the policy patch obligations that were applied to the blueprint during provisioning. Keyed by JSON Pointer path, value is the patched string. Written into /etc/k8shell/blueprint.yaml under "obligations".
func (*Workspace) SetBlueprintChain ¶
SetBlueprintChain stores the inheritance chain for this workspace's blueprint.
func (*Workspace) SetBlueprintRevision ¶ added in v0.17.1
SetBlueprintRevision stores the content revision of this workspace's blueprint.
func (*Workspace) SetJobId ¶
SetJobId stores the NATS provisioning job ID on the workspace so it can be embedded in Helm labels and reported back to clients.
func (*Workspace) SetPAT ¶ added in v0.16.0
SetPAT stores the personal access token minted for this workspace so it can be surfaced to the workspace pod as the PAT_TOKEN env var by Values().
func (*Workspace) SetProvisionContext ¶ added in v0.16.0
func (w *Workspace) SetProvisionContext(mode authz.WorkspaceProvisionMode, workloadName, workloadNamespace, workloadKind string)
SetProvisionContext stores the provision mode and, for inject mode, the target workload identity. It is surfaced to the workspace pod as env vars by Values(). In standalone mode workloadName/Namespace/Kind are empty and no workload env vars are emitted.
func (*Workspace) StopPod ¶
StopPod deletes only the workspace pod, leaving the Helm release and all other resources (PVCs, secrets, ConfigMaps) intact. The pod is labeled immediately before deletion so it carries the label through its graceful-termination window, letting AnalyzePod report WorkspaceStatusStopping instead of WorkspaceStatusTerminating.
func (*Workspace) Template ¶
Template renders the workspace Helm chart without installing it, returning the raw manifest YAML. Job ID and manifest hash are zeroed so successive calls for the same configuration produce identical output.
func (*Workspace) TemplateHash ¶
TemplateHash returns the SHA-256 hex digest of the rendered workspace manifest, used to detect configuration drift between Helm releases.
func (*Workspace) Uninstall ¶
func (w *Workspace) Uninstall(ctx context.Context, timeout time.Duration, wait bool, lock bool) error
Uninstall removes the workspace Helm release. When lock is true it acquires the distributed workspace lock first so concurrent delete requests are serialised; the lock is released in a deferred call after uninstall completes.
func (*Workspace) UpdateResourcesAndNetwork ¶ added in v0.16.0
func (w *Workspace) UpdateResourcesAndNetwork(ctx context.Context, opts UpdateOptions) (*UpdateResult, error)
UpdateResourcesAndNetwork applies opts to the workspace's live Kubernetes objects. The web-proxy changes are validated first and the alias claimed, so that a missing route or a contested alias fails the update before anything has changed; resources are resized next (it needs a running pod); the network policy is re-applied after that; the web-proxy route and alias are written last, together in one pod patch. If any step fails, an alias claimed by this update is given back. Each step is skipped when its Change* / Replace* gate is false. The Helm release is never modified, so the workspace reverts to its blueprint's resources, network class, web-proxy route and alias the next time the release is re-applied.
func (*Workspace) UserSource ¶ added in v0.17.0
UserSource returns the identity source of the workspace's owning user, or "" if the workspace was constructed without a user lookup.
func (*Workspace) Username ¶ added in v0.16.0
Username returns the username of the workspace's owning user, or "" if the workspace was constructed without a user lookup (e.g. NewWorkspaceForUninstall).
func (*Workspace) Values ¶
Values builds the complete Helm values map for the workspace by merging the blueprint fields with user data, registry config, cert-manager settings, and provisioner-internal keys (prefixed with "__"). The resulting map is passed directly to Helm install/upgrade/template operations.
func (*Workspace) WaitForPodGone ¶ added in v0.17.4
WaitForPodGone polls until the workspace pod has been deleted or timeout elapses; a non-positive timeout means 20 seconds. Provision uses it to wait for a pod that is being deleted before the pod is re-created.
type WorkspaceLabels ¶
type WorkspaceLabels struct {
Workspace string
Username string
Organization string
Blueprint string
RepoOwner string
RepoName string
RepoRef string
AppVersion string
UserStr *userstr.CanonicalUserStr
JobId string
}
WorkspaceLabels holds parsed workspace metadata stored in k8shell labels.
type WorkspaceLock ¶
type WorkspaceLock struct {
// contains filtered or unexported fields
}
WorkspaceLock provides a distributed mutex for a single workspace using Kubernetes Lease objects (coordination.k8s.io/v1). One lock per workspace prevents concurrent install, upgrade, or delete operations across replicas.
func NewWorkspaceLock ¶
func NewWorkspaceLock(client kubernetes.Interface, namespace, lockName string) *WorkspaceLock
NewWorkspaceLock returns a WorkspaceLock for lockName in the given namespace. The holder ID is unique per process invocation so concurrent provisioner replicas do not share lock identity.
func (*WorkspaceLock) Acquire ¶
func (l *WorkspaceLock) Acquire(ctx context.Context) (bool, error)
Acquire attempts to acquire the lock with waiting behavior
func (*WorkspaceLock) AcquireWithOptions ¶
AcquireWithOptions attempts to acquire the lock with configurable waiting behavior
func (*WorkspaceLock) KeepAlive ¶ added in v0.16.0
KeepAlive renews the lease every interval until ctx is cancelled or a renewal fails, at which point it sends the failure on the returned channel and stops. Callers holding a lock across a long-running operation should watch this channel and abort if it fires, since it means the lock may no longer be exclusively held.
func (*WorkspaceLock) Release ¶
func (l *WorkspaceLock) Release(ctx context.Context) error
Release deletes the Kubernetes Lease if this instance holds it. It is a no-op when the lease does not exist or is held by a different instance.
func (*WorkspaceLock) Renew ¶ added in v0.16.0
func (l *WorkspaceLock) Renew(ctx context.Context) error
Renew extends the lease's RenewTime, keeping it from expiring while this instance still holds it. It returns ErrLockAlreadyHeld if another holder has taken over the lease (e.g. because it expired and a different replica acquired it before this renewal ran).
func (*WorkspaceLock) TryAcquire ¶
func (l *WorkspaceLock) TryAcquire(ctx context.Context) (bool, error)
TryAcquire attempts to acquire the lock without waiting