Documentation
¶
Index ¶
- Constants
- Variables
- func RewriteImageForCluster(image, currentClusterID string, store RegistryStore) string
- func ValidateContainerImage(image string) error
- func VaultSecretName(user string) string
- type APIKeyItem
- type APIKeyResult
- type APIKeyService
- type ArmWaiter
- type CentralLogScope
- type ClusterConfigSink
- type ClusterEndpoints
- type ClusterService
- type CreateAPIKeyInput
- type CreateKeyRequest
- type CreateKeyResponse
- type CreateSandboxEnvInput
- type CreateSandboxInput
- type CrossClusterForwarder
- type EgressRepusher
- type EnvRouter
- type EnvShellService
- type ExecTokenInfo
- type ExecTokenRecord
- type IAMResolveResult
- type IAMService
- type KeyMetadata
- type LastCreateBumper
- type ListSandboxesResult
- type OrganizationService
- type QuotaService
- type RegistryStore
- type SandboxEnvService
- type SandboxListFilter
- type SandboxService
- type SandboxTemplateService
- type SyncHTTPError
- type SyncService
- type URLKind
- type UpdateSandboxEnvInput
- type VaultCreateInput
- type VaultItem
- type VaultReplicatedEntry
- type VaultReplicator
- type VaultService
- type VaultSink
- type VaultUpdateInput
- type VolumeConfig
- type VolumeService
Constants ¶
const ( // URLKindNative forwards to GatewayConfig.NativeAPIBaseURL. URLKindNative = cluster.URLKindNative // URLKindE2B forwards to GatewayConfig.E2BAPIBaseURL. URLKindE2B = cluster.URLKindE2B )
const ( // VaultLabelOwner carries the hashed user so entries can be listed with a // label selector rather than by parsing object names. VaultLabelOwner = "agentbox.navix.sh/vault-owner" // VaultLabelManagedBy marks the Secret as vault-owned. VaultLabelManagedBy = "agentbox.navix.sh/managed-by" // VaultManagedByValue is the value of VaultLabelManagedBy. VaultManagedByValue = "vault" // VaultAnnotationUser records the unhashed user for operators reading the // object; the slug in the name is lossy and the hash is opaque. VaultAnnotationUser = "agentbox.navix.sh/vault-user" // VaultAnnotationMeta holds per-entry bookkeeping as JSON: version, // timestamps and caller metadata. Values live in data, never here. VaultAnnotationMeta = "agentbox.navix.sh/vault-meta" )
const MetaKeyNoWait = "agentbox.scitix.ai/no-wait"
MetaKeyNoWait is the reserved create-metadata key that opts a single create request out of waiting for the sandbox to be armed (runtimes answering, env vars delivered, egress policy and credentials pushed). It is consumed by the service and never stored on the pod.
The default — waiting — is what makes "create returned" mean "the sandbox works". Opting out hands back an ID whose first command may fail, whose env vars may be missing, and whose egress rules may not be in force yet; that is only ever the right trade for a caller that runs its own readiness gate.
const MetaKeyScalingGroup = "agentbox.scitix.ai/scaling-group"
MetaKeyScalingGroup is the reserved create-metadata key that pins a sandbox to a specific autoscaling group (e.g. "1c2Gi"). Both the E2B-compatible and the native create handlers consume it into CreateSandboxInput.RequestedScalingGroup and strip it from the metadata that gets stored on the pod. Empty / absent = no group constraint (any member pool of the env is eligible — unchanged behaviour). The value is matched verbatim against a member's EnvClusterMemberConfig.ScalingGroup.
const SandboxContainerName = "sandbox"
SandboxContainerName is the sandbox's own container: the one running the user's image. It is containers[0] by construction — the renderer and the in-place image update both address it by that index — and everything else in the Pod (the egress proxy, the tini/envd injectors) is the platform's.
Variables ¶
var ErrSyncNotConnected = errors.New("ws-proxy sync not connected")
ErrSyncNotConnected is returned when an operation requires an active sync session to ws-proxy but none is established.
Functions ¶
func RewriteImageForCluster ¶ added in v0.0.2
func RewriteImageForCluster(image, currentClusterID string, store RegistryStore) string
RewriteImageForCluster rewrites the registry host of image to the registry owned by currentClusterID. See sandboxrender.RewriteImageForCluster.
func ValidateContainerImage ¶
ValidateContainerImage is a thin alias kept so service-package callers can stay against the existing symbol; the implementation lives in pkg/sandboxrender so the controller layer can validate without taking a service-package dependency.
func VaultSecretName ¶ added in v0.0.10
VaultSecretName is the object name holding one user's entries.
The slug keeps the name readable; the hash keeps it unique, because slugging is lossy ("a.b" and "a-b" slug alike) and two users must never share a Secret. Exported so the sync layer can name the same object on every cluster.
Types ¶
type APIKeyItem ¶ added in v0.0.5
type APIKeyItem struct {
KeyMetadata
// ShortName is the Kubernetes Secret name (without namespace prefix).
ShortName string
}
APIKeyItem holds the displayable metadata for a single API key (no token).
type APIKeyResult ¶ added in v0.0.5
type APIKeyResult struct {
RawToken string // shown once only
KeyMetadata
}
APIKeyResult is the result of a successful Create operation. RawToken is the opaque token and is returned only on creation.
type APIKeyService ¶
type APIKeyService interface {
Create(ctx context.Context, input CreateAPIKeyInput) (*APIKeyResult, *domain.AppError)
List(ctx context.Context) ([]APIKeyItem, *domain.AppError)
ListByTeamAndUser(ctx context.Context, team, user string) ([]APIKeyItem, *domain.AppError)
Get(ctx context.Context, keyID string) (*APIKeyItem, *domain.AppError)
Delete(ctx context.Context, keyID string) *domain.AppError
// Promote elevates a locally-created key to a global key by syncing it
// through the ws-proxy manager to all Worker clusters.
Promote(ctx context.Context, keyID string) *domain.AppError
}
APIKeyService defines business operations for API key management.
func NewAPIKeyService ¶
func NewAPIKeyService(store apikey.KeyStore) APIKeyService
NewAPIKeyService creates a new APIKeyService backed by the provided KeyStore. If store is nil, all operations will return a ServiceUnavailable error.
func NewAPIKeyServiceWithSync ¶
func NewAPIKeyServiceWithSync(store apikey.KeyStore, syncSvc SyncService) APIKeyService
NewAPIKeyServiceWithSync creates a new APIKeyService that forwards Create/Delete operations to the master cluster via the provided SyncService WS channel. Local List/Get continue to use the local store.
type ArmWaiter ¶ added in v0.0.10
type ArmWaiter interface {
// Wait returns the channel the verdict will arrive on and a cancel
// function the caller must defer. Register before the work that produces
// the verdict can start: one delivered with no waiter registered is
// dropped.
Wait(sandboxID string) (<-chan error, func())
}
ArmWaiter registers interest in a sandbox's arming verdict.
The verdict travels in memory, not through the API server: the hook runner that produces it and the create request that wants it are two goroutines of the same process. Recording it on the Pod would cost one write per sandbox, fanned out to every Pod informer in the cluster, to move a fact between goroutines that already share an address space.
type CentralLogScope ¶ added in v0.0.11
type CentralLogScope struct {
// Filters scope a query to this cluster. Pod names are unique per cluster,
// not globally, so without them a query can answer with another cluster's
// output for the same name.
Filters map[string]string
// SplitProject says this cluster's output is sharded across log stores by
// namespace. See logclient.ProjectFor.
SplitProject bool
}
CentralLogScope addresses the local cluster in the central log service.
Read live rather than captured at startup: it arrives on the cluster-config snapshot the hub distributes, and that can change without a restart.
type ClusterConfigSink ¶
type ClusterConfigSink interface {
ApplyClusterConfig(ctx context.Context, cfg cluster.ClusterConfig) error
}
ClusterConfigSink receives ClusterConfig snapshots from ws-proxy and persists them (e.g. to a Kubernetes ConfigMap) so that other Worker components (ExtProc, in-process DNS resolver, ...) can read the latest state. Implementations must treat a zero-valued snapshot (no clusters and no host aliases) as a no-op.
type ClusterEndpoints ¶ added in v0.0.8
type ClusterEndpoints struct {
// NativeURL, E2BURL, DataURL are the gateway URLs verbatim, scheme included
// (e.g. "https://gw.example.com/agent-sandbox/api/e2b").
NativeURL string
E2BURL string
DataURL string
// DataDomain is DataURL without its scheme ("gw.example.com/agent-sandbox/api/data").
// The E2B SDK's E2B_DOMAIN expects exactly this form.
DataDomain string
// Host is the bare hostname shared by the gateway URLs, taken from DataURL
// ("gw.example.com"). It is what an /etc/hosts entry or a hostAliases
// override has to name.
Host string
// InnerIP is the in-cluster address Host resolves to per the host-alias set,
// empty when no alias covers it. Pointing Host at it keeps traffic inside
// the cluster instead of going out over the public gateway.
InnerIP string
// HTTPS reports whether DataURL uses https, so docs can render the SDK's
// E2B_HTTPS switch instead of hardcoding it.
HTTPS bool
// RegistryHost is the cluster's first configured registry host — the region
// -local registry sandbox images are rewritten to.
RegistryHost string
}
ClusterEndpoints is the client-facing view of one cluster's gateway config: where to point an SDK, and how to shortcut the public path from inside the cluster. Used to render the ${AGBX_*_URL} / ${AGBX_HOST} / ${AGBX_INNER_IP} / ${AGBX_REGISTRY_HOST} placeholders in template documentation.
type ClusterService ¶
type ClusterService interface {
// List returns the cluster catalog sorted by ID. When store or localID are
// empty the result is a single-entry list containing the local cluster, or an
// empty slice when neither is configured. The list is a defensive copy; the
// caller may mutate it freely.
List(ctx context.Context) ([]gen.ClusterSummary, *domain.AppError)
// Endpoints returns the client-facing addresses configured for one cluster.
// Every field is best-effort: an unconfigured gateway, a data URL that does
// not parse, a host with no matching host alias, or a cluster with no
// registries each leave the corresponding field empty rather than failing.
// Callers render what they got and omit the rest.
Endpoints(clusterID string) ClusterEndpoints
}
ClusterService exposes the routing-visible cluster list to API consumers. It wraps a cluster.Store and tags the local cluster so SDK/CLI callers can distinguish the native home of a request from remote worker clusters.
func NewClusterService ¶
func NewClusterService(store *cluster.Store, localClusterID string) ClusterService
NewClusterService returns a ClusterService backed by the given store and local cluster ID. store may be nil (common in single-cluster deployments); in that case List reports only the local cluster if localID is set.
type CreateAPIKeyInput ¶ added in v0.0.5
type CreateAPIKeyInput struct {
Namespace string
User string
Team string
Description string
ExpiresAt time.Time // zero means no expiry
// RequireApproval marks the key as acting unattended, so its platform
// writes are held until a person approves them. This is the "agent" mode a
// caller picks at issue time.
RequireApproval bool
// Import mode fields (admin-only).
// When TokenHash is non-empty the key is imported using the given hash
// (via CreateFromHash) instead of generating a new random token.
TokenHash string
HashPrefix string
IssuedAt time.Time // preserve original issue time (import mode)
}
CreateAPIKeyInput carries parameters for issuing a new API key.
type CreateKeyRequest ¶
type CreateKeyRequest struct {
Namespace string
User string
Team string
Role string
Description string
QuotaURL string
ExpiresAt string // RFC3339; empty = never expires
// Import/promote mode: when TokenHash + HashPrefix are set the Hub calls
// CreateFromHash instead of generating a new token.
TokenHash string
HashPrefix string
IssuedAt string // RFC3339
RawToken string // plaintext token for promote
// RequireApproval is the "agent" mode. It travels on the create because it
// is chosen at issue time and cannot be added afterwards; a key born
// unrestricted stays unrestricted.
RequireApproval bool
}
CreateKeyRequest carries the parameters for forwarding an API key CreateKey RPC to the Hub.
type CreateKeyResponse ¶
type CreateKeyResponse struct {
RawToken string
KeyID string
TokenHash string
HashPrefix string
IssuedAt string // RFC3339
}
CreateKeyResponse is the parsed result of a successful Hub-side CreateKey.
type CreateSandboxEnvInput ¶ added in v0.0.5
type CreateSandboxEnvInput struct {
Name string
Namespace string
Team string // copied from auth, injected as label
User string // copied from auth, injected as label
TemplateRef agentsv1alpha1.SandboxEnvTemplateRef
Mode agentsv1alpha1.SandboxEnvMode
Overrides *agentsv1alpha1.EnvOverridesSpec
// ImagePullSecret, when non-nil, instructs the service to materialise a
// dockerconfigjson Secret named ips-{envName} with an OwnerRef pointing
// at the Env (cascade-delete free). The Env Reconciler stamps a
// LocalObjectReference to that Secret into every member Pool.
ImagePullSecret *gen.ImagePullSecretInput
Labels map[string]string
Annotations map[string]string
}
CreateSandboxEnvInput is the parsed CreateSandboxEnvRequest with auth context resolved. Members and Autoscaling are intentionally absent — the caller adds them via the embedded sub-services after the env shell is created.
type CreateSandboxInput ¶ added in v0.0.5
type CreateSandboxInput struct {
ClusterID string // target cluster ID parsed from pool name prefix; empty means local
PoolName string
Namespace string
Image string
ContainerImages map[string]string
Labels map[string]string
Annotations map[string]string
Metadata map[string]string
StartupTimeout time.Duration // 0 means no timeout
IdleTimeout time.Duration // 0 means no expiry
// RequestedScalingGroup, when non-empty, hard-scopes pool selection to the
// env's member pools whose autoscaling group
// (EnvClusterMemberConfig.ScalingGroup) equals this value. If no member of
// the env belongs to that group the create fails (503) rather than falling
// back to another group. Empty = no constraint. Set from the reserved
// metadata key MetaKeyScalingGroup by the create handlers.
RequestedScalingGroup string
// Role is the caller's authenticated role (domain.AuthInfo.Role). Only
// "admin" is meaningful here: it waives the check that the target Pool
// belongs to the caller's tenant. Empty means "not an admin", which is the
// safe reading for any caller that did not set it.
Role string
// PostStartHooks are actions to run after the sandbox transitions Starting → Running.
// Serialized to a pod annotation at claim time; consumed by the controller.
PostStartHooks []poststarthooks.Action
// NetworkPolicy, when non-nil, overrides the Pool's Env-default egress policy
// for this sandbox only (E2B create body: network / allow_internet_access).
// Rejected when the target Pool has no networkPolicy (no filter sidecar).
NetworkPolicy *agentsv1alpha1.SandboxNetworkPolicy
// User is the authenticated caller. It scopes the credential vault: two
// users sharing a namespace (the `default` case) must not resolve each
// other's secrets.
User string
// VaultRules are per-sandbox credential-injection rules parsed from the
// create request, with header values still holding ${e2b.secrets.<name>}
// references. They are deliberately not part of NetworkPolicy: a request may
// not hand the service a ready-made SecretInjection, and these only become
// one after every reference has been resolved against the caller's own vault.
VaultRules []agentsv1alpha1.InjectionRule
}
CreateSandboxInput carries all parameters needed to create a new sandbox. The shape is service-internal: it holds parsed timeouts (durations), the cluster prefix already split out of the pool name, and post-start hooks (which are not part of the native wire spec — they are injected by the E2B compatibility handler).
type CrossClusterForwarder ¶
type CrossClusterForwarder struct {
// contains filtered or unexported fields
}
CrossClusterForwarder transparently forwards HTTP requests to a remote cluster's API endpoint. It is protocol-agnostic: the original gin.Context request (method, path, query string, headers, body) is forwarded verbatim; only the base URL is swapped according to urlKind and the target cluster's gateway configuration.
Callers (handlers) should:
- Detect the cross-cluster case early (right after extracting clusterID).
- Call Forward — it writes the remote response directly to gc.Writer.
- Return from the handler immediately after Forward returns.
func NewCrossClusterForwarder ¶
func NewCrossClusterForwarder(store *cluster.Store, localClusterID string) *CrossClusterForwarder
NewCrossClusterForwarder creates a forwarder. Returns nil if store or localClusterID is empty, which disables cross-cluster support.
The forwarder's HTTP client uses a custom Dialer that consults the Manager- pushed host-alias resolver before falling back to the system DNS, so that gateway hostnames unreachable via kube-dns (e.g. internal zones on the worker network) can be resolved purely via the sync channel without touching Pod spec.
func (*CrossClusterForwarder) Forward ¶
func (f *CrossClusterForwarder) Forward(gc *gin.Context, targetClusterID string, urlKind URLKind, body io.Reader)
Forward transparently proxies the incoming gin request to targetCluster. urlKind selects whether to target the Native or E2B endpoint.
body overrides the request body sent to the remote cluster. Pass nil to use gc.Request.Body as-is (suitable for GET/DELETE or when the body has not yet been consumed). Pass a non-nil reader when the handler has already read the body (e.g. strict-server mode where oapi-codegen parses the body before the handler runs) — in that case the caller should re-marshal the parsed struct and pass it here.
The full remote response (status, headers, body) is written directly to gc.Writer. On network/configuration errors, Forward writes a 502 JSON error response itself so the caller can always return immediately after this call.
func (*CrossClusterForwarder) IsCrossCluster ¶
func (f *CrossClusterForwarder) IsCrossCluster(clusterID string) bool
IsCrossCluster reports whether clusterID refers to a remote cluster that requires forwarding. Returns false when the forwarder is nil (cross-cluster disabled), clusterID is empty, or clusterID equals the local cluster.
func (*CrossClusterForwarder) LocalClusterID ¶
func (f *CrossClusterForwarder) LocalClusterID() string
LocalClusterID returns the configured local cluster ID. Empty when the forwarder is nil (cross-cluster disabled) or no local ID was configured.
type EgressRepusher ¶ added in v0.0.10
EgressRepusher delivers a revised egress policy to a running sandbox's proxy sidecar. Implemented by the post-start hook runner, which owns the exec channel into the Pod.
Only the policy: the credential half is fixed at claim time, because the CA the sidecar uses to intercept TLS is minted per claim and installed into the sandbox's trust store during arming. Replacing it on a live sandbox would mean re-running that install, and the install rides on the same envd /init call that carries the sandbox's environment.
type EnvRouter ¶ added in v0.0.5
type EnvRouter interface {
Resolve(ns, clusterID, poolOrEnvName string) envscheduler.ResolveResult
// SelectPool picks a member pool of envKey. scalingGroup, when non-empty,
// hard-scopes the choice to that autoscaling group (returns "" when the
// group has no member). Empty = no constraint.
SelectPool(envKey types.NamespacedName, scalingGroup string) string
// SelectForeignTarget returns the cluster ID and member pool a create for
// envKey should be forwarded to (local has no idle capacity for the group,
// a foreign cluster's member does); ok is false when it should be served
// locally.
SelectForeignTarget(envKey types.NamespacedName, scalingGroup string) (clusterID, memberPool string, ok bool)
}
EnvRouter is the subset of envscheduler.Manager that sandbox_service uses at request-entry time to translate bare template names into a target Pool. It is an interface (rather than a concrete *envscheduler.Manager) so unit tests can substitute a fake without standing up a real Manager.
May be nil — when nil, sandbox_service skips Env routing entirely and treats every template as a direct Pool reference (legacy behaviour, used by tests that don't wire the Env layer).
type EnvShellService ¶ added in v0.0.5
type EnvShellService interface {
// List returns a lightweight summary of the SandboxEnvs in namespace
// visible to the caller. When team/user are non-empty the result is
// filtered by the standard scheduling.navix.sh/{team,user} labels
// (matching the Pool model). Callers needing the full spec/status fetch
// each Env via Get.
List(ctx context.Context, namespace, team, user string) ([]gen.SandboxEnvSummary, *domain.AppError)
// Get returns a single Env or NotFound.
Get(ctx context.Context, namespace, name string) (*gen.SandboxEnv, *domain.AppError)
// Editable returns the body a write to this Env takes, read off the live
// object — the same shape Update accepts, so a client can export it, edit
// it and send it straight back. It is separate from Get because the read
// shape is not the write shape: handing a reader the object and calling it
// a request body is what made an exported file clear the fields it did not
// carry.
Editable(ctx context.Context, namespace, name string) (*gen.UpsertSandboxEnvRequest, *domain.AppError)
// Create posts a new SandboxEnv shell. The body carries TemplateRef +
// Overrides + optional ImagePullSecret only — Members are added via
// AddMember (from the embedded MemberPoolService), which also
// materialises the matching autoscaling group automatically.
Create(ctx context.Context, input CreateSandboxEnvInput) (*gen.SandboxEnv, *domain.AppError)
// Update patches Overrides / ImagePullSecret on an existing Env.
// Members and autoscaling groups are intentionally not part of this
// surface — use the dedicated CRUD methods from the embedded
// sub-services to avoid accidental wholesale replacement.
Update(ctx context.Context, input UpdateSandboxEnvInput) (*gen.SandboxEnv, *domain.AppError)
// Delete issues a foreground delete on the Env. Member Pools are
// cascade-deleted via OwnerReferences (controller=true,
// blockOwnerDeletion=true) stamped by the Env Reconciler.
Delete(ctx context.Context, namespace, name string) (*gen.DeleteSandboxEnvResult, *domain.AppError)
// ListEvents returns recent K8s Events emitted against the Env and its
// member SandboxPools, merged and sorted descending by lastTimestamp.
// Drives the activity timeline on the Env detail page in the dashboard.
ListEvents(ctx context.Context, namespace, name string, limit int) ([]gen.EnvEvent, *domain.AppError)
}
EnvShellService is the env-only CRUD slice of SandboxEnvService. Lives as its own interface so the composed SandboxEnvService can be assembled from three orthogonal contracts (env shell + member CRUD + autoscaler CRUD) without method-name collisions.
type ExecTokenInfo ¶ added in v0.0.5
ExecTokenInfo carries the information stored in an exec token. It is returned by ValidateExecToken after successful token validation.
type ExecTokenRecord ¶
type ExecTokenRecord struct {
SandboxID string
Namespace string
PodName string
Containers []string
ExpiresAt time.Time
}
ExecTokenRecord holds the information associated with a one-time exec token.
type IAMResolveResult ¶
type IAMResolveResult struct {
// Username is the normalised username.
Username string
// Team is the team derived from ScitixQuota labels. Empty when no quota found.
Team string
// Namespace is the effective Kubernetes namespace to use for this user.
// When the computed namespace (t-{team}-{username}) exists in the cluster it
// equals that value; otherwise it falls back to "default".
Namespace string
// QuotaURL is the quota URL label value, if found.
QuotaURL string
}
IAMResolveResult holds the resolved identity information for an IAM user.
type IAMService ¶
type IAMService interface {
// ResolveNamespace resolves the namespace a tenant acts in ON THIS CLUSTER.
//
// This is the ONLY way a request's namespace is decided, for every kind of
// credential. A namespace is a per-cluster fact and a credential is used
// across clusters, so nothing a credential carries about namespaces can be
// right everywhere — and a credential that named one would only be right
// where it happened to be minted.
//
// Never returns empty: a tenant this cluster has no namespace for shares
// the default one.
//
// Results are cached permanently (until process restart) for performance.
ResolveNamespace(ctx context.Context, team, user string) (string, *domain.AppError)
}
IAMService defines operations related to IAM identity resolution.
func NewIAMService ¶
func NewIAMService(c client.Client) IAMService
NewIAMService creates an IAMService backed by Kubernetes ScitixQuota CRs.
type KeyMetadata ¶ added in v0.0.5
type KeyMetadata struct {
// KeyID is the fully qualified secret identifier: "<namespace>/<name>".
KeyID string
Namespace string
Role string
User string
Team string
Description string
IssuedAt time.Time
ExpiresAt time.Time // zero value means no expiry
// SyncSource is "global" when the key was created/synced via ws-proxy.
// Empty means locally-created or a legacy resource — both are treated as non-global.
SyncSource string
// RawToken is the full raw API key recovered from storage. Empty for legacy keys
// that pre-date plaintext storage. Exposed via API to authorised callers for recovery.
RawToken string
// RequireApproval is the "agent" mode: this key acts unattended, so its
// platform writes are held until a person approves them.
RequireApproval bool
}
KeyMetadata is the service-layer view of an API key's stored metadata. It is kept distinct from `apikey.KeyMetadata` (the K8s-Secret storage shape) so the service can evolve its presentation independently of the storage utility.
type LastCreateBumper ¶ added in v0.0.5
type LastCreateBumper interface {
// Bump records the current time as the most-recent Sandbox.Create
// for the named Pool. Must be safe to call from the request hot
// path; the production implementation takes a brief mutex on an
// in-memory map.
Bump(namespace, name string)
}
LastCreateBumper is the minimal interface k8sSandboxService needs from pkg/lifecycle/lastcreate.Tracker. Defined here (rather than imported) so the service package stays free of the concrete dependency and the tracker can be swapped/disabled in tests.
type ListSandboxesResult ¶
ListSandboxesResult wraps the paginated result and total count for List operations.
type OrganizationService ¶
type OrganizationService interface {
// ListTeams returns all unique team names found across API Key secrets.
ListTeams(ctx context.Context) ([]string, *domain.AppError)
// ListUsersByTeam returns all unique user names belonging to the given team,
// derived from API Key secrets filtered by team label.
ListUsersByTeam(ctx context.Context, team string) ([]string, *domain.AppError)
// ListNamespaces returns all Kubernetes namespace names visible to the operator.
ListNamespaces(ctx context.Context) ([]string, *domain.AppError)
}
OrganizationService defines operations for querying organizational structure (teams, users, namespaces) derived from API Key Secret labels.
func NewOrganizationService ¶
func NewOrganizationService(c client.Client, ks apikey.KeyStore) OrganizationService
NewOrganizationService creates an OrganizationService backed by Kubernetes resources. keyStore is used to enumerate teams and users via API Key Secret labels.
type QuotaService ¶
type QuotaService interface {
// ListForUser returns all quotas matching the given user and team. When
// the underlying provider is disabled the result is an empty list, not
// an error — callers should treat that as "feature unavailable".
ListForUser(ctx context.Context, user, team string) ([]gen.Quota, *domain.AppError)
}
QuotaService defines operations for querying user-visible quotas.
The concrete behaviour (ScitixQuota CRD, external API, disabled stub, ...) is selected by the quota.Provider injected at construction time. The service layer itself stays vendor-neutral — see pkg/plugins/quota for the provider contract and pkg/scitix/quota for the Scitix implementation.
func NewQuotaServiceFromProvider ¶
func NewQuotaServiceFromProvider(p quotaplugin.Provider) QuotaService
NewQuotaServiceFromProvider wraps a quota.Provider in the service-level interface consumed by HTTP handlers. The provider may be a Noop, which yields a service whose ListForUser always returns (nil, nil).
type RegistryStore ¶ added in v0.0.2
type RegistryStore = sandboxrender.RegistryStore
The registry-rewrite implementation lives in pkg/sandboxrender so the Pool renderer can rewrite template-owned images (idleImage, containers, initContainers) as well as the caller-supplied ones rewritten here at claim time. It cannot live in this package: pkg/controllers/.../poolrender calls the renderer, and this package depends on poolrender through envmember, so the reverse edge would be an import cycle.
These aliases keep the claim-time call sites in sandbox_service.go unchanged.
type SandboxEnvService ¶ added in v0.0.5
type SandboxEnvService interface {
EnvShellService
envmember.MemberPoolService
envautoscaler.AutoscalerService
}
SandboxEnvService is the business-layer surface for SandboxEnv resources. It composes the env shell CRUD with the two sub-resource interfaces (MemberPool CRUD + Autoscaler CRUD) so the router only needs to inject one service instance and handlers call e.g. s.env.AddMember(...) or s.env.UpdateAutoscalingGroup(...).
Method names on the sub-interfaces carry a noun suffix (AddMember, UpdateAutoscalingGroup, …) so embedding doesn't produce conflicts and the call site reads naturally.
func NewSandboxEnvService ¶ added in v0.0.5
func NewSandboxEnvService( c client.Client, pm *plugins.PluginManager, instProv instancetypeplugin.Provider, quotaProv quotaplugin.Provider, imageRegistry *sandboxrender.RegistryRewrite, apiReader client.Reader, volumeCfg VolumeConfig, ) SandboxEnvService
NewSandboxEnvService constructs the default service implementation. The PluginManager / provider arguments flow through to the embedded MemberPoolService; the autoscaler sub-service currently needs only the k8s client. A nil *plugins.PluginManager is treated as "no plugins"; nil providers are normalised to their Noop forms inside envmember.New. imageRegistry may be nil (rewriting disabled); when set it must be the same value the SandboxEnv Reconciler holds. apiReader may be nil, in which case PersistentVolumeClaim reads fall back to the cached client — acceptable for tests, but see preflightVolumeClaims for why production wants the uncached reader.
type SandboxListFilter ¶ added in v0.0.5
type SandboxListFilter struct {
Namespace string
PoolName string
Status string // comma-separated multi-value supported (e.g. "Running,Failed")
Team string // when non-empty, only return sandboxes with this team label
User string // when non-empty, only return sandboxes with this user label
Limit int // default 20, max 100; 0 means no limit
Offset int
}
SandboxListFilter is the service-side projection of gen.ListSandboxesParams: the (often pointer-typed) query params are dereferenced and combined with the auth-derived namespace/team/user.
type SandboxService ¶
type SandboxService interface {
Create(ctx context.Context, input CreateSandboxInput) (*gen.Sandbox, *domain.AppError)
List(ctx context.Context, filter SandboxListFilter) (*ListSandboxesResult, *domain.AppError)
Get(ctx context.Context, namespace, sandboxID string) (*gen.Sandbox, *domain.AppError)
// GetLive is Get without the history-store fallback: NotFound once the
// sandbox has no Pod. Use it wherever the result is handed back as something
// the caller will then act on.
GetLive(ctx context.Context, namespace, sandboxID string) (*gen.Sandbox, *domain.AppError)
// UpdateSandboxNetwork replaces a running sandbox's egress policy and
// delivers it to its gateway sidecar. Egress filtering only — see the
// implementation for why credential injection is fixed at claim time.
UpdateSandboxNetwork(ctx context.Context, namespace, sandboxID string, np *agentsv1alpha1.SandboxNetworkPolicy) *domain.AppError
Delete(ctx context.Context, namespace, sandboxID string) (*gen.DeleteSandboxResult, *domain.AppError)
// SetTimeout updates the idle timeout annotation on the sandbox pod.
// A timeout of 0 removes the annotation (no expiry).
SetTimeout(ctx context.Context, namespace, sandboxID string, timeout time.Duration) *domain.AppError
// GetLogs retrieves logs for a sandbox. For active sandboxes it fetches live
// logs from the K8s API; for runtime sources it reads the log file via exec.
GetLogs(ctx context.Context, namespace, sandboxID string, params gen.GetSandboxLogsParams) (*gen.SandboxLogsResult, *domain.AppError)
// CreateExecToken generates a single-use exec token (TTL 30 s) for the given sandbox.
// The sandbox must be in the Running phase.
CreateExecToken(ctx context.Context, namespace, sandboxID string) (string, *domain.AppError)
// ValidateExecToken validates and consumes the token.
// Returns ExecTokenInfo on success, or a 401 AppError if the token is invalid / expired.
ValidateExecToken(tokenStr string) (*ExecTokenInfo, *domain.AppError)
// ExecCommand runs a one-shot command inside the sandbox pod (non-interactive, no TTY).
// The sandbox must be in Running phase. clientset must be non-nil.
ExecCommand(ctx context.Context, namespace, sandboxID string, req gen.ExecCommandRequest) (*gen.ExecCommandResult, *domain.AppError)
// IsReady checks if all runtime readiness probes for a sandbox pass.
// If a runtime has no ReadinessProbe configured, it is considered ready.
IsReady(ctx context.Context, namespace, sandboxID string) (*gen.SandboxReadinessResult, *domain.AppError)
}
SandboxService defines business operations for sandboxes.
func NewSandboxService ¶
func NewSandboxService(c client.Client, cs kubernetes.Interface, restCfg *rest.Config, s store.SandboxStore, gatewayBaseURL string, localClusterID string, registryStore RegistryStore) SandboxService
NewSandboxService creates a new SandboxService backed by the given K8s client and optional stores. clientset is used for live log retrieval and exec; it may be nil (live logs and exec will be unavailable). restConfig is the Kubernetes REST config for exec via SPDY; it may be nil (exec will be unavailable). gatewayBaseURL is the base URL of the Envoy gateway (e.g. http://gateway.example.com); it may be empty. localClusterID identifies the local cluster for cross-cluster sandbox ID prefixing; it may be empty. registryStore supplies per-cluster registry metadata for automatic image host rewriting; may be nil (no rewriting).
type SandboxTemplateService ¶
type SandboxTemplateService interface {
// List returns templates visible to the caller (auth). isAdmin=true bypasses
// visibility filtering and returns all templates.
List(ctx context.Context, auth domain.AuthInfo, isAdmin bool) ([]gen.SandboxTemplate, *domain.AppError)
// Get returns a single template if it is visible to the caller. isAdmin=true
// bypasses visibility filtering. Returns ErrCodeNotFound when the template
// does not exist or the caller cannot see it (to avoid leaking names).
Get(ctx context.Context, name string, auth domain.AuthInfo, isAdmin bool) (*gen.SandboxTemplate, *domain.AppError)
// Admin only:
Create(ctx context.Context, tmpl *agentsv1alpha1.SandboxTemplate) (*gen.SandboxTemplate, *domain.AppError)
Update(ctx context.Context, tmpl *agentsv1alpha1.SandboxTemplate) (*gen.SandboxTemplate, *domain.AppError)
Delete(ctx context.Context, name string) *domain.AppError
// CreateOrUpdate upserts a SandboxTemplate. It is used by SyncService to apply
// sync events from ws-proxy. The operation is idempotent: if the template already
// exists its spec is replaced; otherwise it is created.
CreateOrUpdate(ctx context.Context, tmpl *agentsv1alpha1.SandboxTemplate) *domain.AppError
// StripStaleGlobalLabels removes the sync-source=global label from any local
// template whose name is NOT present in knownNames. This corrects templates
// that were mistakenly (or historically) labeled as global but no longer exist
// on the master cluster, preventing delete requests from being forwarded to
// ws-proxy and receiving a 404.
StripStaleGlobalLabels(ctx context.Context, knownNames map[string]struct{}) *domain.AppError
}
SandboxTemplateService defines business operations for SandboxTemplates.
func NewSandboxTemplateService ¶
func NewSandboxTemplateService(c client.Client, quotaProv quotaplugin.Provider) SandboxTemplateService
NewSandboxTemplateService creates a new SandboxTemplateService backed by the given K8s client and quota Provider.
The Provider is consulted on every read (List/Get/Create/Update) to project gen.SandboxTemplate.RequiresQuota — whether a Pool of this template must name a quota and an instance type. A nil Provider means "the open-source answer": false for every template.
type SyncHTTPError ¶
SyncHTTPError carries an HTTP-style status code translated from a gRPC status code. It is the cross-package error type that pkg/apiserver/handlers/server.go uses to map sync forwarding failures into the appropriate native API responses.
func (*SyncHTTPError) Error ¶ added in v0.0.3
func (e *SyncHTTPError) Error() string
type SyncService ¶
type SyncService interface {
// OnConnect registers a new ClientConn (produced by wsmux.DialGRPC after
// a fresh /v1/ws/sync upgrade). Returns a connection generation ID that
// must be passed back to OnDisconnect so that a stale teardown does not
// race against a newer connect.
OnConnect(conn *grpc.ClientConn) uint64
// OnDisconnect tears down all background Watch goroutines associated
// with connID and clears the ClientConn — but only if connID still
// matches the currently-registered conn.
OnDisconnect(connID uint64)
RequestCreate(ctx context.Context, req CreateKeyRequest) (*CreateKeyResponse, error)
RequestDelete(ctx context.Context, name string) error
RequestTemplateCreate(ctx context.Context, raw json.RawMessage) error
RequestTemplateUpdate(ctx context.Context, raw json.RawMessage) error
RequestTemplateDelete(ctx context.Context, name string) error
}
SyncService manages the gRPC client connection to ws-proxy. It exposes synchronous request methods for the apiserver business layer and runs background goroutines that consume the three Watch* streams to keep the local KeyStore / SandboxTemplate / ClusterConfig state up to date.
func NewSyncService ¶
func NewSyncService(store apikey.KeyStore) SyncService
NewSyncService creates a new SyncService.
func NewSyncServiceFull ¶
func NewSyncServiceFull(store apikey.KeyStore, templateSvc SandboxTemplateService, clusterSink ClusterConfigSink) SyncService
NewSyncServiceFull creates a SyncService with all optional components wired in.
func NewSyncServiceWithTemplate ¶
func NewSyncServiceWithTemplate(store apikey.KeyStore, templateSvc SandboxTemplateService) SyncService
NewSyncServiceWithTemplate creates a SyncService that also handles SandboxTemplate sync events.
type URLKind ¶
URLKind selects which base URL from GatewayConfig to use when forwarding. It is an alias for cluster.URLKind so existing callers keep their import surface while the header-merge logic shares the canonical enum.
type UpdateSandboxEnvInput ¶ added in v0.0.5
type UpdateSandboxEnvInput struct {
Name string
Namespace string
// NameInFile is the `name` the request body carried, when it carried one.
//
// An update's identity is the address, so this is not a field of the
// object. It is here because one document serves both verbs — the file a
// create wrote is the file an update takes — which makes "this file is
// about a different Env" a mistake a caller can really make, and the only
// safe reading of it is to refuse.
NameInFile *string
Overrides *agentsv1alpha1.EnvOverridesSpec
// ImagePullSecret, when non-nil, replaces the dockerconfigjson Secret
// backing this Env's image-pull credentials.
ImagePullSecret *gen.ImagePullSecretInput
// KeepImagePullSecret preserves an existing Secret when the request
// carries no credentials.
//
// It exists because this one field cannot be read back and echoed like
// every other: the request is desired state, and a caller editing an
// unrelated setting has nothing to re-send. Without an explicit keep, the
// only two expressible intents would be "replace" and "revoke", and every
// ordinary edit would mean the second.
KeepImagePullSecret bool
// The Env's fixed fields, carried so the update can check them.
//
// A nil pointer means the body did not mention the field at all. For a
// fixed field that is NOT the same as "leave it alone": the fields a client
// can set are one shape now (see UpsertSandboxEnvRequest), so a body that
// loses the template is almost always the caller having built itself out of
// a read shape that does not contain it — and answering 400 with the value
// in force turns a silent wrong write into one line of advice.
TemplateRef *agentsv1alpha1.SandboxEnvTemplateRef
Mode *gen.UpsertSandboxEnvRequestMode
Labels *map[string]string
Annotations *map[string]string
}
UpdateSandboxEnvInput carries the editable patch for an Env shell. Members and Autoscaling are intentionally not exposed here so callers can't accidentally wholesale-replace either set; use the dedicated sub-service methods instead.
type VaultCreateInput ¶ added in v0.0.10
VaultCreateInput is a create request. Value is write-only.
type VaultItem ¶ added in v0.0.10
type VaultItem struct {
Name string
Version int64
Metadata map[string]string
CreatedAt time.Time
UpdatedAt time.Time
}
VaultItem is one entry's metadata. There is deliberately no value field: a read path that cannot express a value cannot leak one, which is a stronger guarantee than remembering not to set it.
type VaultReplicatedEntry ¶ added in v0.0.10
type VaultReplicatedEntry struct {
Namespace string
User string
Name string
Value string
Version int64
Metadata map[string]string
CreatedAt time.Time
UpdatedAt time.Time
}
VaultReplicatedEntry is one entry as it travels between clusters.
type VaultReplicator ¶ added in v0.0.10
type VaultReplicator interface {
RequestVaultPut(ctx context.Context, e VaultReplicatedEntry) (*VaultReplicatedEntry, error)
RequestVaultDelete(ctx context.Context, namespace, user, name string) error
}
VaultReplicator forwards writes to the Hub. Implemented by the sync service.
type VaultService ¶ added in v0.0.10
type VaultService interface {
List(ctx context.Context, ns, user string) ([]VaultItem, *domain.AppError)
Get(ctx context.Context, ns, user, idOrName string) (*VaultItem, *domain.AppError)
Create(ctx context.Context, ns, user string, in VaultCreateInput) (*VaultItem, *domain.AppError)
Update(ctx context.Context, ns, user, idOrName string, in VaultUpdateInput) (*VaultItem, *domain.AppError)
Delete(ctx context.Context, ns, user, idOrName string) *domain.AppError
// ResolveRefs maps entry names to the Secret key each lives in, for the
// claim path to embed in a SecretInjection. It reports the first name that
// does not exist rather than resolving what it can: a rule referencing a
// missing credential must fail the create, not produce a sandbox that
// reaches its upstream with a decoy.
ResolveRefs(ctx context.Context, ns, user string, names []string) (map[string]agentsv1alpha1.SecretKeyRef, *domain.AppError)
}
VaultService is the vault's read/write surface.
func NewVaultService ¶ added in v0.0.10
func NewVaultService(c client.Client) VaultService
NewVaultService returns a VaultService backed by Kubernetes Secrets.
type VaultSink ¶ added in v0.0.10
type VaultSink interface {
ApplyVaultEntry(ctx context.Context, e VaultReplicatedEntry) error
DeleteVaultEntry(ctx context.Context, namespace, user, name string) error
// ReconcileVault drops local entries absent from an authoritative snapshot.
// Without it, a delete that happened while this cluster was disconnected
// would survive forever here.
ReconcileVault(ctx context.Context, keep []VaultReplicatedEntry) error
}
VaultSink applies replicated vault entries to local storage.
type VaultUpdateInput ¶ added in v0.0.10
type VaultUpdateInput struct {
Name string
Value string
Metadata map[string]string
// MetadataSet distinguishes "no metadata given" from "metadata cleared".
MetadataSet bool
}
VaultUpdateInput is an update request. E2B's update always carries a value — there is no "leave it as it was" state — so neither does this.
type VolumeConfig ¶ added in v0.0.10
type VolumeConfig struct {
// Enabled is the kill switch. When false a non-empty overrides.volumes is
// rejected outright — not merely hidden in the dashboard. The failure mode
// this feature can produce is an agent with write access to a user's
// dataset, so the gate has to stop writes, not just UI.
Enabled bool
// AllowedRuntimeClasses lists runtimeClassName values whose CSI
// passthrough has been verified. Empty (the default) permits only the
// cluster's default runtime, i.e. a Template that leaves runtimeClassName
// unset. A sandbox running under a VM-isolated runtime reaches the backing
// filesystem through a different path than a plain container does, and an
// unverified one silently yields an empty directory or a Pod that never
// starts.
AllowedRuntimeClasses []string
// DisplayNameLabels is an ordered list of PVC label keys consulted to
// derive a human-readable volume name; the first non-empty value wins.
// Empty means fall back to the claim name. Deliberately configurable
// rather than hardcoded: the label vocabulary belongs to whichever storage
// platform is deployed, not to this codebase.
DisplayNameLabels []string
}
VolumeConfig gates and constrains Env-level PersistentVolumeClaim mounts.
type VolumeService ¶ added in v0.0.10
type VolumeService interface {
// List returns the Bound claims in namespace. The caller passes the
// namespace their identity resolved to; there is no way for an API client
// to name a different one, which is what makes this the authorisation
// boundary rather than a filter.
List(ctx context.Context, namespace string) ([]gen.VolumeItem, *domain.AppError)
}
VolumeService lists the PersistentVolumeClaims a caller may mount into a sandbox.
func NewVolumeService ¶ added in v0.0.10
func NewVolumeService(reader client.Reader, cfg VolumeConfig) VolumeService
NewVolumeService constructs the default VolumeService. reader should be an uncached reader; see the field comment. cfg supplies the display-name label keys and the feature gate.
Source Files
¶
- apikey_inputs.go
- apikey_service.go
- cluster_service.go
- cross_cluster_forwarder.go
- egress_policy.go
- env_imagepull.go
- env_volumes.go
- exec_token_store.go
- iam_service.go
- image_rewrite.go
- image_validation.go
- inputs.go
- organization_service.go
- quota_service.go
- sandbox_service.go
- sandboxenv_events.go
- sandboxenv_service.go
- sandboxtemplate_service.go
- sync_service.go
- sync_service_federation.go
- sync_vault.go
- vault.go
- volume_service.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package envautoscaler serves the Env-scoped autoscaler-config CRUD surface.
|
Package envautoscaler serves the Env-scoped autoscaler-config CRUD surface. |
|
Package envcommon hosts the helpers shared between the env shell service (pkg/apiserver/service) and the per-resource sub-services (envmember, envautoscaler).
|
Package envcommon hosts the helpers shared between the env shell service (pkg/apiserver/service) and the per-resource sub-services (envmember, envautoscaler). |
|
Package envmember serves the Env-scoped Pool CRUD surface: `/v1/sandboxenvs/{name}/sandboxpools/*`.
|
Package envmember serves the Env-scoped Pool CRUD surface: `/v1/sandboxenvs/{name}/sandboxpools/*`. |
|
Package envscheduler implements the in-process Env-level request router.
|
Package envscheduler implements the in-process Env-level request router. |
|
Package federation holds the Worker-side soft-state view of cross-cluster SandboxEnv capacity.
|
Package federation holds the Worker-side soft-state view of cross-cluster SandboxEnv capacity. |