Documentation
¶
Overview ¶
Package application manages applications, their config, and deployments.
Index ¶
- Constants
- Variables
- type CanaryPreview
- type CanaryPreviewRequest
- type CanaryPreviewRule
- type CanaryRouting
- type ClusterCap
- type ConfigReader
- type CreateInput
- type DeployResult
- type ErrCanaryMatchRegex
- type ImageGuard
- type LiveStatus
- type NetworkEnsurer
- type NodeDocker
- type NodeGuard
- type NodeNamer
- type Overview
- type Pipelines
- type PortSpec
- type RouteSyncer
- type ServerInfo
- type Service
- func (s *Service) AbortCanary(ctx context.Context, app *models.Application) error
- func (s *Service) ApplyServiceEndpointMode(ctx context.Context, clusterID uint, mode models.ServiceEndpointMode)
- func (s *Service) AppsMountingConfig(workspaceID, configID uint) ([]models.Application, error)
- func (s *Service) AppsReferencingSecret(workspaceID uint, name string) ([]models.Application, error)
- func (s *Service) AttachConfig(app *models.Application, configID uint, key, path, mode string) error
- func (s *Service) AttachHostMount(app *models.Application, preset, path string, readOnly bool) error
- func (s *Service) AttachVolume(app *models.Application, volumeID uint, path string) error
- func (s *Service) AutoRedeploy(app *models.Application) (*models.Deployment, error)
- func (s *Service) ClusterOfServer(serverID uint) uint
- func (s *Service) Create(workspaceID uint, in CreateInput) (*models.Application, error)
- func (s *Service) Delete(ctx context.Context, app *models.Application) error
- func (s *Service) DeleteEnvVar(appID uint, key string) error
- func (s *Service) DeleteRelease(ctx context.Context, app *models.Application, releaseID uint) error
- func (s *Service) Deploy(app *models.Application, registryOverride *uint, tagOverride string, ...) (*models.Deployment, error)
- func (s *Service) DetachConfig(app *models.Application, configID uint, key string) error
- func (s *Service) DetachHostMount(app *models.Application, preset string) error
- func (s *Service) DetachVolume(app *models.Application, volumeID uint) error
- func (s *Service) EnforcesNoNewPrivileges(workspaceID uint) bool
- func (s *Service) EnsureExecAllowed(workspaceID uint) error
- func (s *Service) Exec(ctx context.Context, app *models.Application, opts docker.ExecOptions) (docker.ExecStream, error)
- func (s *Service) ExternalLabelTaken(label string, exceptAppID uint) (bool, error)
- func (s *Service) Get(workspaceID, id uint) (*models.Application, error)
- func (s *Service) GetDeployment(id uint) (*models.Deployment, error)
- func (s *Service) GetRelease(app *models.Application, releaseID uint) (*models.Release, error)
- func (s *Service) IDByUID(uid string) (uint, error)
- func (s *Service) ImportEnvVars(appID uint, content string, isSecret bool) (int, error)
- func (s *Service) InvalidateBuildCache(app *models.Application) error
- func (s *Service) List(workspaceID uint) ([]models.Application, error)
- func (s *Service) ListDeployments(appID uint, limit int) ([]models.Deployment, error)
- func (s *Service) ListEnvVars(appID uint) ([]models.AppEnvVar, error)
- func (s *Service) ListReleases(appID uint) ([]models.Release, error)
- func (s *Service) LiveStatus(ctx context.Context, app *models.Application) LiveStatus
- func (s *Service) MarkNodeRemoved(serverID uint)
- func (s *Service) MarkRedeployRequired(app *models.Application) (bool, error)
- func (s *Service) Overview(app *models.Application) *Overview
- func (s *Service) PauseCanary(app *models.Application) error
- func (s *Service) Processes(ctx context.Context, app *models.Application, psArgs string) (docker.ProcessList, error)
- func (s *Service) PromoteCanary(app *models.Application) (*models.Deployment, error)
- func (s *Service) ReconcileRedeploy(app *models.Application, reason string) (*models.Deployment, error)
- func (s *Service) Redeploy(app *models.Application) (*models.Deployment, error)
- func (s *Service) Reencrypt(ctx context.Context, workspaceID uint) (int, error)
- func (s *Service) RepoPipelineForApp(appID uint) (*models.PipelineDefinition, error)
- func (s *Service) RequestDeploy(app *models.Application, registryOverride *uint, tagOverride string, ...) (*DeployResult, error)
- func (s *Service) ResourceLimits() (maxCPUCores, maxMemoryMB int)
- func (s *Service) Restart(ctx context.Context, app *models.Application) (*models.Deployment, error)
- func (s *Service) ResumeCanary(app *models.Application) error
- func (s *Service) ResyncPipeline(ctx context.Context, app *models.Application, userID *uint) (*models.PipelineDefinition, bool, error)
- func (s *Service) RevealEnvVar(appID uint, key string) (string, error)
- func (s *Service) Rollback(app *models.Application, releaseID uint) (*models.Deployment, error)
- func (s *Service) Scale(ctx context.Context, app *models.Application, replicas int) error
- func (s *Service) SetCanaryRouting(ctx context.Context, app *models.Application, in CanaryRouting) ([]string, error)
- func (s *Service) SetCanaryWeight(ctx context.Context, app *models.Application, weight int) error
- func (s *Service) SetClusterCap(c ClusterCap)
- func (s *Service) SetConfigs(c ConfigReader)
- func (s *Service) SetContainerLabels(app *models.Application, labels map[string]string) error
- func (s *Service) SetEnvVar(appID uint, key, value string, isSecret bool) error
- func (s *Service) SetGrantsEnabled(on bool)
- func (s *Service) SetImageGuard(g ImageGuard)
- func (s *Service) SetName(app *models.Application, newName string) error
- func (s *Service) SetNetworkEnsurer(e NetworkEnsurer)
- func (s *Service) SetNetworks(app *models.Application, networkIDs []uint) error
- func (s *Service) SetNodeGuard(g NodeGuard)
- func (s *Service) SetNodeNamer(n NodeNamer)
- func (s *Service) SetPipelines(p Pipelines)
- func (s *Service) SetPortBindings(r *repositories.PortBindingRepository)
- func (s *Service) SetPorts(app *models.Application, specs []PortSpec) error
- func (s *Service) SetQuota(q *quota.Service)
- func (s *Service) SetReleasePinned(app *models.Application, releaseID uint, pinned bool) (*models.Release, error)
- func (s *Service) SetRouteSyncer(rs RouteSyncer)
- func (s *Service) SetServerInfo(si ServerInfo)
- func (s *Service) SetSettings(p *settings.Provider)
- func (s *Service) SetSource(app *models.Application, in SourceInput) (*SourceChange, error)
- func (s *Service) SetWorkspaceInfo(w WorkspaceInfo)
- func (s *Service) Start(ctx context.Context, app *models.Application) (*models.Deployment, error)
- func (s *Service) StartCanary(app *models.Application, registryOverride *uint, tagOverride string) (*models.Deployment, error)
- func (s *Service) Stop(ctx context.Context, app *models.Application) error
- func (s *Service) Update(app *models.Application) error
- func (s *Service) WaitRunning(ctx context.Context, app *models.Application) error
- type SourceChange
- type SourceInput
- type WorkspaceInfo
Constants ¶
const ( CanaryPreviewStable = "stable" CanaryPreviewCanary = "canary" // CanaryPreviewSplit means the request is eligible for both and the gateway // picks by weight, so no single answer is truthful. CanaryPreviewSplit = "split" )
Backends a preview can resolve to.
const GomaProxyDocsURL = "https://goma.jkaninda.dev/usermanual/running-behind-a-proxy.html"
GomaProxyDocsURL documents configuring the gateway's trusted proxies. Linked from the client-IP warning, because an ip rule is only as trustworthy as that setting.
const MaxReplicas = models.MaxServiceReplicas
MaxReplicas caps a service app's replica count.
Variables ¶
var ( ErrSlugTaken = errors.New("application name already taken") ErrNameInvalid = errors.New("name must contain only lowercase letters, digits and hyphens") ErrImageRequired = errors.New("image is required for image-source applications") // ErrImageNotPermitted rejects an image that lives in the built-in registry // under a namespace this workspace does not own. Pulling it would use the // platform credential, which every namespace accepts. ErrImageNotPermitted = errors.New("image is not available to this workspace") ErrGitRepoRequired = errors.New("git_repo is required for git-source applications") ErrPipelinesUnavailable = errors.New("pipelines are not available on this platform") // ErrRepoPipelinesDisabled is the operator kill-switch for adopting pipelines out of repositories. ErrRepoPipelinesDisabled = errors.New("repository pipelines are disabled on this platform") // ErrNotGitApp means the operation only applies to an application that builds from git. ErrNotGitApp = errors.New("application does not build from a git repository") ErrBuildConfigOnImage = errors.New("build configuration is only valid for git-source applications") ErrInvalidBuildMethod = errors.New("invalid build method") ErrNotDeployable = errors.New("application has no active release") ErrVolumeNotFound = errors.New("volume not found in workspace") ErrEnvVarNotFound = errors.New("environment variable not found") ErrMountPathRequired = errors.New("mount path is required") ErrReleaseNotFound = errors.New("release not found") ErrReleaseActive = errors.New("cannot delete the active release") ErrReleasePinned = errors.New("cannot delete a pinned release") ErrStackNotFound = errors.New("stack not found in workspace") ErrAppRunning = errors.New("stop the application before deleting it") ErrNodeMismatch = errors.New("the volume is on a different node than this application") ErrVolumeLocation = errors.New("the volume is in a different location than this application") ErrStackLocation = errors.New("the stack is in a different location than this application") ErrConfigNotFound = errors.New("config not found in workspace") ErrConfigKeyNotFound = errors.New("the config does not contain that file") ErrMountNotFound = errors.New("that mount is not attached to this application") ErrUnknownHostPreset = errors.New("unknown host mount preset") ErrHostMountNotPrivileged = errors.New("host mounts require a privileged workspace") ErrInvalidGPUCount = errors.New("gpu_count must be between 0 and 64") ErrClusterDisabled = errors.New("cluster mode is not enabled; cannot run this application as a service") ErrNotService = errors.New("this operation is only valid for service-runtime (cluster) applications") ErrLocalVolumeReplicated = errors.New("a replicated (replicas>1) service cannot mount a node-local volume; use a shared (nfs/cifs) volume or set replicas to 1") ErrHostBindService = errors.New("a service-runtime app cannot use a privileged host mount; host paths are node-local and don't follow a rescheduled task — use the container runtime or a managed volume") // ErrVolumeUnverifiable fails the storage guards closed. A guard that cannot read a // mounted volume cannot prove it is shared, and guessing "shared" forks the data. ErrVolumeUnverifiable = errors.New("a mounted volume could not be read, so it cannot be confirmed as shared storage; replication is refused until it resolves") ErrTooManyReplicas = fmt.Errorf("replica count exceeds the maximum of %d", MaxReplicas) ErrPortRange = errors.New("container port must be between 1 and 65535") )
var ( // ErrCustomLabelsDisabled is returned when the fleet-wide kill-switch is off. ErrCustomLabelsDisabled = &labelError{code: "FEATURE_DISABLED", msg: "custom container labels are disabled by the administrator"} // ErrLabelReserved is returned when a user tries to set a platform-reserved key. ErrLabelReserved = &labelError{code: "LABEL_RESERVED", msg: "label key is reserved by the platform (io.miabi.*, com.docker.*)"} // ErrTooManyLabels / ErrLabelInvalid guard size and shape. ErrTooManyLabels = &labelError{code: "LABELS_TOO_MANY", msg: fmt.Sprintf("too many container labels (max %d)", maxContainerLabels)} ErrLabelInvalid = &labelError{code: "LABEL_INVALID", msg: "label key must be non-empty and within length limits"} )
var ( ErrNoCanary = errors.New("no canary deployment in progress") ErrCanaryActive = errors.New("a canary deployment is already in progress") )
var ( ErrCanaryModeInvalid = errors.New("canary mode must be auto or manual") // ErrCanaryRulesNeedManual rejects rules in automatic mode: the ramp owns the // weight there, and automatic mode is defined as the empty rule set. ErrCanaryRulesNeedManual = errors.New("canary match rules require manual mode") // ErrCanaryExclusiveNoMatch rejects exclusive without rules — the gateway // would hand the canary every request, which is almost never intended. ErrCanaryExclusiveNoMatch = errors.New("an exclusive canary needs at least one match rule; without one it takes all traffic") // ErrCanaryPooledZeroWeight rejects a non-exclusive rule set at weight 0: the // canary joins the pool with no share, so matching requests still all go to // stable and the rules look active while doing nothing. ErrCanaryPooledZeroWeight = errors.New("a canary at 0% needs exclusive routing; otherwise its match rules send no traffic") ErrCanaryTooManyRules = fmt.Errorf("a canary may have at most %d match rules", maxCanaryMatchRules) ErrCanaryMatchSource = fmt.Errorf("match source must be one of: %s", strings.Join(models.CanaryMatchSources, ", ")) ErrCanaryMatchOperator = fmt.Errorf("match operator must be one of: %s", strings.Join(models.CanaryMatchOperators, ", ")) // ErrCanaryMatchName is returned for a header/query/cookie rule with no key. // An ip rule reads the client address and needs no name. ErrCanaryMatchName = errors.New("match rules on a header, query or cookie need a name") ErrCanaryMatchValue = errors.New("match rules need a value") // ErrCanaryPriority bounds the tie-breaker to a sane range. ErrCanaryPriority = errors.New("canary priority must be between 0 and 1000") )
Canary routing validation. Each of these is a configuration that looks right and sends traffic somewhere surprising, so each gets its own refusal rather than a generic "invalid".
var ErrNoActiveContainer = errors.New("application has no active container")
ErrNoActiveContainer is returned by Exec when the app has no running container to attach a shell to.
var ErrResourceCap = errors.New("requested resources exceed the platform limit")
ErrResourceCap is returned when a requested CPU/memory exceeds a platform cap.
var ErrSourceTypeInvalid = errors.New("source_type must be \"image\" or \"git\"")
ErrSourceTypeInvalid is returned for a source that is neither image nor git.
var ErrTaskOnUnmanagedNode = errors.New(
"this app's task runs on a swarm node with no Miabi agent, so a shell cannot be opened. " +
"Add the node to Miabi (install the agent) to use exec")
ErrTaskOnUnmanagedNode is the user-facing form of nodes.ErrTaskUnreachable: the app IS running, but on a swarm node with no Miabi agent, so there is no engine to open a shell through. Docker offers no manager-side exec, so this is a hard limit. Logs are unaffected — the manager aggregates those.
Functions ¶
This section is empty.
Types ¶
type CanaryPreview ¶ added in v1.9.0
type CanaryPreview struct {
Backend string `json:"backend"` // stable | canary | split
// CanaryChance is the percentage of such requests the canary would serve:
// 0, 100, or the weight when the request lands in the weighted pool.
CanaryChance int `json:"canary_chance"`
Matched bool `json:"matched"` // every rule held
Reason string `json:"reason"`
Rules []CanaryPreviewRule `json:"rules"`
}
CanaryPreview answers "which backend would serve this request?".
func PreviewCanaryRouting ¶ added in v1.9.0
func PreviewCanaryRouting(app *models.Application, req CanaryPreviewRequest) CanaryPreview
PreviewCanaryRouting resolves a hypothetical request against the app's canary configuration, mirroring the gateway's selection: an exclusive canary takes every matching request, a non-exclusive one joins the weighted pool, and a request matching nothing goes to stable. Pure — no deploy, no canary and no gateway required to run it.
type CanaryPreviewRequest ¶ added in v1.9.0
type CanaryPreviewRequest struct {
Headers map[string]string `json:"headers,omitempty"`
Query map[string]string `json:"query,omitempty"`
Cookies map[string]string `json:"cookies,omitempty"`
IP string `json:"ip,omitempty"`
}
CanaryPreviewRequest is the request attributes to evaluate the rules against. Header names are matched case-insensitively (as HTTP does); query and cookie names are matched exactly, as the gateway reads them.
type CanaryPreviewRule ¶ added in v1.9.0
type CanaryPreviewRule struct {
Rule models.CanaryMatchRule `json:"rule"`
Actual string `json:"actual"`
Matched bool `json:"matched"`
}
CanaryPreviewRule is one rule's verdict, with the value the gateway would have read — so a preview that surprises the user shows why.
type CanaryRouting ¶ added in v1.9.0
type CanaryRouting struct {
Mode models.CanaryMode
Exclusive bool
Priority int
Match []models.CanaryMatchRule
}
CanaryRouting is the user-settable steering for an app's canary: who moves the weight, and which requests the canary is eligible for.
type ClusterCap ¶
type ClusterCap interface {
IsSwarm(clusterID uint) bool
Manager(ctx context.Context, clusterID uint) (docker.Client, error)
ClusterOfServer(serverID uint) uint
}
ClusterCap is the per-cluster control path. Implemented by the cluster service; used to gate "service" runtime apps and to reach the swarm they run in.
type ConfigReader ¶ added in v1.9.0
type ConfigReader interface {
Get(workspaceID, id uint) (*models.Config, error)
Data(cfg *models.Config) (map[string]string, error)
}
ConfigReader reads a mounted config's files, for the secret-reference scan.
type CreateInput ¶
type CreateInput struct {
// DisplayName is the free-text label. Handle is the desired unique slug
// (the URL/CLI handle); when blank it is derived from DisplayName.
DisplayName string
Handle string
ServerID uint // node to place on (0 = local)
SourceType models.AppSourceType
Icon string // optional logo (URL or "mdi-…" class); set from a template
Image string
Tag string
GitRepo string
GitRef string
// Build config (git source only). BuildMethod defaults to auto; Builder,
// Buildpacks, and BuildEnv tune a buildpack build. Rejected for image apps.
BuildMethod models.AppBuildMethod
Builder string
Buildpacks []string
BuildEnv map[string]string
RegistryID *uint
GitRepositoryID *uint
StackID *uint
NetworkIDs []uint
Ports []PortSpec
Command []string
Port int
MemoryBytes int64
NanoCPUs int64
// GPUCount / GPUKind request whole GPU devices. Gated by the AllowGPU plan
// capability at create time; 0 = none.
GPUCount int
GPUKind string
// RunAsUser pins the container to an account ("uid", "uid:gid", "name",
// "name:group"); empty keeps the image's user. Validated against the
// workspace's security profile.
RunAsUser string
// AddCapabilities / Devices grant kernel privileges beyond the container
// default. Both are allow-listed and gated on the workspace; empty grants
// nothing.
AddCapabilities []string
Devices []string
// ReadOnlyRootFilesystem, NoNewPrivileges and DropCapabilities harden the container on top of the
// workspace's security profile.
ReadOnlyRootFilesystem bool
NoNewPrivileges bool
DropCapabilities []string
// DeployStrategy is the app's default rollout method. Empty leaves the model's
// own default (rolling), so a caller that does not care says nothing.
DeployStrategy models.DeployStrategy
RestartPolicy models.RestartPolicy
ImagePullPolicy models.ImagePullPolicy
// Cluster runtime (cluster mode). RuntimeKind defaults to container; service
// runs the app as a replicated Swarm service (rejected when cluster mode is
// off). Replicas/PlacementConstraints/UpdateConfig apply to the service runtime.
RuntimeKind models.RuntimeKind
Replicas int
PlacementConstraints []string
UpdateConfig *models.ServiceUpdateConfig
// Metadata is the app's initial metadata. Callers may set reserved
// "miabi.io/" keys (e.g. provenance); a missing managed-by defaults to
// "user". HTTP handlers must sanitize user input before setting reserved keys.
Metadata models.Metadata
// Annotations is the app's initial annotations: free-form descriptive notes
// with no reserved keys (the manifest's metadata.annotations).
Annotations models.Metadata
// ContainerLabels are user-defined Docker labels for the app's container(s)
// (Traefik &c.). Reserved keys (io.miabi.*, com.docker.*) are sanitized on
// create regardless of caller.
ContainerLabels map[string]string
// UsePipeline asks Miabi to adopt the pipeline-as-code document the repository carries (git source
// only). Adoption re-reads the repository regardless of the inspect endpoint, and a repository that
// turns out to carry none is not an error — the app is created and builds directly.
UsePipeline bool
// UserID attributes the adopted pipeline's first run. nil for non-interactive
// callers (GitOps, marketplace).
UserID *uint
}
CreateInput describes a new application.
type DeployResult ¶ added in v1.6.8
type DeployResult struct {
Deployment *models.Deployment
Run *models.PipelineRun
}
DeployResult is what a deploy request produced: a Deployment for an app that builds directly, or the PipelineRun that will build and deploy an app whose repository carries pipeline-as-code. Exactly one is set.
type ErrCanaryMatchRegex ¶ added in v1.9.0
ErrCanaryMatchRegex reports a regex rule whose pattern does not compile. The gateway logs and fails such a rule closed at request time, so it is caught at save instead — a pattern that never matches is invisible in production.
func (*ErrCanaryMatchRegex) Error ¶ added in v1.9.0
func (e *ErrCanaryMatchRegex) Error() string
func (*ErrCanaryMatchRegex) Unwrap ¶ added in v1.9.0
func (e *ErrCanaryMatchRegex) Unwrap() error
type ImageGuard ¶ added in v1.6.8
ImageGuard authorizes a user-supplied image reference against the workspace that will run it. It only constrains references into the built-in registry, where a pull uses the platform credential. The deploy worker enforces the same rule; this copy reports it when the app is saved.
type LiveStatus ¶
type LiveStatus struct {
Status string `json:"status"` // running|restarting|unhealthy|starting|exited|stopped|paused|created|no_container
ContainerState string `json:"container_state,omitempty"`
Health string `json:"health,omitempty"`
Running bool `json:"running"`
Restarting bool `json:"restarting"`
RestartCount int `json:"restart_count"`
ExitCode int `json:"exit_code"`
StartedAt string `json:"started_at,omitempty"`
UptimeSeconds int64 `json:"uptime_seconds"`
HasContainer bool `json:"has_container"`
StoredStatus models.AppStatus `json:"stored_status"`
Stats *docker.StatsSample `json:"stats,omitempty"`
// Networks lists the running container's in-network IPs (ephemeral).
Networks []docker.ContainerNetwork `json:"networks,omitempty"`
// Cluster (service) runtime: the desired replica count and how many tasks are
// currently running. Zero/omitted for container apps.
ServiceReplicas uint64 `json:"service_replicas,omitempty"`
ServiceRunningTasks uint64 `json:"service_running_tasks,omitempty"`
}
LiveStatus is the real-time status of an application's container, derived from Docker inspect (not the stored, deploy-time status). It also carries a live resource-usage snapshot when the container is running.
type NetworkEnsurer ¶
type NetworkEnsurer interface {
EnsureDefault(ctx context.Context, workspaceID uint) (*models.Network, error)
}
NetworkEnsurer resolves — creating if necessary — a workspace's default, platform-managed Docker network, so every app joins it even when the network wasn't provisioned at workspace-creation time. Implemented by the network service; an interface keeps application decoupled from it.
type NodeDocker ¶
type NodeDocker interface {
For(serverID uint) (docker.Client, error)
LocalID() uint
// ForServiceTask finds the engine holding a swarm service's task container.
// A service has no fixed node, and only the node running the task can see it.
ForServiceTask(ctx context.Context, clusterID uint, serviceName string) (docker.Client, string, error)
}
NodeDocker resolves the Docker client for a node id (0 = local).
type NodeGuard ¶
NodeGuard validates that a node can accept a new placement (exists, not cordoned). Implemented by the node service; injected after construction.
type NodeNamer ¶
NodeNamer resolves a swarm node id to its Miabi display name, so a cluster app's real replica placement can be shown by node name. Implemented by the node service; optional — placement degrades to a short swarm id when unset.
type Overview ¶
type Overview struct {
Status models.AppStatus `json:"status"`
SourceType models.AppSourceType `json:"source_type"`
Image string `json:"image,omitempty"`
Tag string `json:"tag,omitempty"`
GitRepo string `json:"git_repo,omitempty"`
CurrentVersion int `json:"current_version"` // 0 = no active release
CurrentImage string `json:"current_image,omitempty"`
// Hostname is the app's stable internal DNS name, reachable from other
// managed containers on the shared network across redeploys. StackHostname
// is its service name within its stack network (empty when ungrouped).
Hostname string `json:"hostname"`
StackHostname string `json:"stack_hostname,omitempty"`
RedeployRequired bool `json:"redeploy_required"`
VolumesCount int `json:"volumes_count"`
RoutesCount int `json:"routes_count"`
NetworksCount int `json:"networks_count"`
EnvCount int `json:"env_count"`
CreatedAt time.Time `json:"created_at"`
RecentEvents []models.AppEvent `json:"recent_events"`
}
Overview is an aggregated summary of an application for the detail page.
type Pipelines ¶ added in v1.6.8
type Pipelines interface {
// AdoptForApp probes the app's repository and, on finding pipeline-as-code,
// creates a repo-owned pipeline bound to the app. Reports
// pipeline.ErrNoPipelineInRepo when the repository carries none.
AdoptForApp(ctx context.Context, app *models.Application, userID *uint) (*models.PipelineDefinition, error)
// RepoPipelineForApp returns the app's enabled repo-owned pipeline, or nil.
RepoPipelineForApp(appID uint) (*models.PipelineDefinition, error)
// TriggerForApp starts a run of that pipeline.
TriggerForApp(app *models.Application, trigger string, userID *uint, noCache bool) (*models.PipelineRun, error)
// DeleteForApp drops the app's repo-owned pipelines and unbinds the rest.
DeleteForApp(workspaceID, appID uint) error
// SyncFromRepo re-reads a repo-owned pipeline's spec from its repository, reporting whether
// the stored spec changed. An empty ref uses the pipeline's tracked one.
SyncFromRepo(ctx context.Context, p *models.PipelineDefinition, ref string) (bool, error)
}
Pipelines adopts, finds and triggers the pipeline a repository carries at .miabi/pipeline.yaml. Implemented by pipeline.Service; an interface so this package doesn't depend on the pipeline service and its git machinery just to ask whether an app has one.
type RouteSyncer ¶
type RouteSyncer interface {
SyncRoute(ctx context.Context, appID uint) error
// RemoveAppRoutes deletes all of an app's routes (generated + user) from the
// database and the proxy, used when the app itself is deleted.
RemoveAppRoutes(ctx context.Context, appID uint) error
}
RouteSyncer reconciles an application's reverse-proxy routes. The route service implements it; injected after construction to avoid an import cycle.
type ServerInfo ¶
ServerInfo resolves a node's display metadata by id. Implemented by the node service; injected after construction (optional — read paths degrade to an empty server name when unset).
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
func NewService ¶
func NewService( apps *repositories.ApplicationRepository, deployments *repositories.DeploymentRepository, releases *repositories.ReleaseRepository, volumes *repositories.VolumeRepository, routes *repositories.RouteRepository, networks *repositories.NetworkRepository, stacks *repositories.StackRepository, ports *repositories.AppPortRepository, appEvents *repositories.AppEventRepository, clients NodeDocker, producer *worker.Producer, evts events.Recorder, ) *Service
func (*Service) AbortCanary ¶
AbortCanary stops the canary container, discards its release, and returns all traffic to the stable release.
func (*Service) ApplyServiceEndpointMode ¶ added in v1.10.0
func (s *Service) ApplyServiceEndpointMode(ctx context.Context, clusterID uint, mode models.ServiceEndpointMode)
ApplyServiceEndpointMode switches the running service apps of a cluster to how the cluster reaches services by name. Tasks keep running; a service that cannot be switched now takes the mode on its next deploy.
func (*Service) AppsMountingConfig ¶ added in v1.8.1
func (s *Service) AppsMountingConfig(workspaceID, configID uint) ([]models.Application, error)
AppsMountingConfig lists the apps whose mounts reference a config, which drives both the delete guard and the redeploy fan-out on a content change.
func (*Service) AppsReferencingSecret ¶
func (s *Service) AppsReferencingSecret(workspaceID uint, name string) ([]models.Application, error)
AppsReferencingSecret returns the workspace's apps whose env references the named secret (`${{ secrets.NAME }}`). Used by the Vault for "used by", the delete guard, and rotation fan-out. Satisfies secret.Consumers.
func (*Service) AttachConfig ¶ added in v1.8.1
func (s *Service) AttachConfig(app *models.Application, configID uint, key, path, mode string) error
AttachVolume mounts a workspace volume into the app at path. Takes effect on the next deploy. AttachConfig mounts a workspace config into the app. Projection is per file, so this never becomes a directory bind and the mount is always read-only.
func (*Service) AttachHostMount ¶
func (s *Service) AttachHostMount(app *models.Application, preset, path string, readOnly bool) error
AttachHostMount attaches an allow-listed privileged host bind (see package hostmount) to the app at path, using the preset default target when empty. Requires a privileged workspace; the host source is resolved from the preset at deploy time, never taken from the client. Applies on the next deploy.
func (*Service) AttachVolume ¶
func (*Service) AutoRedeploy ¶
func (s *Service) AutoRedeploy(app *models.Application) (*models.Deployment, error)
func (*Service) ClusterOfServer ¶ added in v1.10.0
ClusterOfServer is the cluster a node belongs to, resolved even for the local node.
func (*Service) Create ¶
func (s *Service) Create(workspaceID uint, in CreateInput) (*models.Application, error)
func (*Service) Delete ¶
Delete removes the application and its active container. Refuses while the app is running — it must be stopped first, to avoid yanking a live workload.
func (*Service) DeleteRelease ¶
DeleteRelease removes a non-active, non-pinned release and its retired container (best-effort).
func (*Service) Deploy ¶
func (s *Service) Deploy(app *models.Application, registryOverride *uint, tagOverride string, strategy models.DeployStrategy) (*models.Deployment, error)
Deploy creates a deployment for the current app config and enqueues it. registryOverride, when non-nil, uses a different registry credential for this one deploy; tagOverride, when non-empty, deploys a specific image tag for an image-source app.
func (*Service) DetachConfig ¶ added in v1.9.4
DetachConfig removes a config mount. key selects one of several mounts of the same config; an empty key removes the whole-config mount. Takes effect on the next deploy, like every other mount change.
func (*Service) DetachHostMount ¶
func (s *Service) DetachHostMount(app *models.Application, preset string) error
DetachHostMount removes a privileged host bind from the app.
func (*Service) DetachVolume ¶
func (s *Service) DetachVolume(app *models.Application, volumeID uint) error
DetachVolume removes a volume mount from the app.
func (*Service) EnforcesNoNewPrivileges ¶ added in v1.10.0
EnforcesNoNewPrivileges reports whether the workspace's security profile turns no-new-privileges on for its apps, whatever an app asks for.
func (*Service) EnsureExecAllowed ¶
EnsureExecAllowed returns a CapabilityDenied error when the workspace's plan does not permit opening an interactive shell into a container. Nil-safe on a disabled quota service (returns nil).
func (*Service) Exec ¶
func (s *Service) Exec(ctx context.Context, app *models.Application, opts docker.ExecOptions) (docker.ExecStream, error)
Exec opens an interactive command stream inside the app's active container. Returns ErrNoActiveContainer when nothing is running. The caller owns the returned stream and must Close it.
func (*Service) ExternalLabelTaken ¶
ExternalLabelTaken reports whether another application already owns the given external-access label. The label maps to a platform-wide host, so it must be unique across all workspaces; exceptAppID excludes the app being reconciled.
func (*Service) GetDeployment ¶
func (s *Service) GetDeployment(id uint) (*models.Deployment, error)
func (*Service) GetRelease ¶
GetRelease loads a release and verifies it belongs to the application.
func (*Service) ImportEnvVars ¶
ImportEnvVars upserts every variable parsed from .env-style content (later duplicate keys win), encrypting them when isSecret. Returns the number set.
func (*Service) InvalidateBuildCache ¶ added in v1.8.4
func (s *Service) InvalidateBuildCache(app *models.Application) error
InvalidateBuildCache names a new build cache generation for the app. The next build of it runs cold and repopulates the cache; nothing is deleted, so a build already in flight is unaffected.
func (*Service) ListDeployments ¶
func (*Service) LiveStatus ¶
func (s *Service) LiveStatus(ctx context.Context, app *models.Application) LiveStatus
LiveStatus inspects the app's active container and returns its real-time status (plus a stats snapshot when running). Falls back to the stored status when there is no running container.
func (*Service) MarkNodeRemoved ¶ added in v1.10.2
MarkNodeRemoved records that every application on a deleted node has stopped. Deleting a node leaves its apps pointing at a server row that no longer exists, holding whatever status they had at that moment — usually "running", for something with no container behind it.
func (*Service) MarkRedeployRequired ¶
func (s *Service) MarkRedeployRequired(app *models.Application) (bool, error)
func (*Service) Overview ¶
func (s *Service) Overview(app *models.Application) *Overview
Overview aggregates summary fields and resource counts for an application.
func (*Service) PauseCanary ¶ added in v1.9.4
func (s *Service) PauseCanary(app *models.Application) error
PauseCanary holds the ramp at the current weight.
func (*Service) Processes ¶
func (s *Service) Processes(ctx context.Context, app *models.Application, psArgs string) (docker.ProcessList, error)
Processes lists the running processes in the app's active container (the "docker top" view). Read-only — no shell capability needed. Returns ErrNoActiveContainer when nothing is running.
func (*Service) PromoteCanary ¶
func (s *Service) PromoteCanary(app *models.Application) (*models.Deployment, error)
PromoteCanary makes the canary the new stable release. It enqueues a normal deploy of the canary's image; the deploy pipeline retires the old stable and the in-progress canary, leaving a single full-traffic release.
func (*Service) ReconcileRedeploy ¶ added in v1.10.1
func (s *Service) ReconcileRedeploy(app *models.Application, reason string) (*models.Deployment, error)
ReconcileRedeploy brings an app back where it already runs, after the control manager found its container or service gone. It is deliberately the ordinary deploy path — same queue, same per-app lock, same guards, routed by the app's own ServerID — so nothing is placed or moved, and the data guard in enqueue refuses it outright if a volume is missing. The distinct trigger is what tells this apart from a deploy a person asked for, in history and in the timeline.
func (*Service) Redeploy ¶
func (s *Service) Redeploy(app *models.Application) (*models.Deployment, error)
Redeploy enqueues a deploy that applies the app's current configuration. Used by Start/Restart when a redeploy is required.
func (*Service) Reencrypt ¶
Reencrypt re-encrypts every secret env var of the workspace's applications under the workspace's active DEK. Non-secret vars (stored plaintext) are skipped. Idempotent; returns the number rewritten.
func (*Service) RepoPipelineForApp ¶ added in v1.6.8
func (s *Service) RepoPipelineForApp(appID uint) (*models.PipelineDefinition, error)
RepoPipelineForApp returns the repo-owned pipeline that owns this app's deploys, or nil when it deploys directly. Handlers use it to explain the app's build path in the UI.
func (*Service) RequestDeploy ¶ added in v1.6.8
func (s *Service) RequestDeploy(app *models.Application, registryOverride *uint, tagOverride string, strategy models.DeployStrategy, userID *uint, noCache bool) (*DeployResult, error)
RequestDeploy is the user-facing deploy entry point. When the app's repository owns a pipeline the request starts a pipeline run instead of a direct build, so a deploy can never skip the declared test and scan steps. Internal redeploys don't come through here — they must not re-run CI.
func (*Service) ResourceLimits ¶
ResourceLimits returns the platform per-app CPU/memory caps (0 = unlimited), for surfacing as hints in the UI.
func (*Service) Restart ¶
func (s *Service) Restart(ctx context.Context, app *models.Application) (*models.Deployment, error)
Restart restarts the app's active container. If a redeploy is required (config changed while stopped) it redeploys instead, so the new config is applied rather than restarting a stale container, returning that deployment so the caller can follow its logs. A plain restart returns nil.
func (*Service) ResumeCanary ¶ added in v1.9.4
func (s *Service) ResumeCanary(app *models.Application) error
ResumeCanary hands the rollout back to the ramp from its current weight.
func (*Service) ResyncPipeline ¶ added in v1.8.0
func (s *Service) ResyncPipeline(ctx context.Context, app *models.Application, userID *uint) (*models.PipelineDefinition, bool, error)
ResyncPipeline re-reads the repository's pipeline-as-code and brings the app's pipeline in line with it: adopting one when the app has none (the file was added after the app was created, or the app only just became a git app), and re-syncing the stored spec when it already has one.
It reports the pipeline it ended up with, and whether the stored spec actually changed.
func (*Service) RevealEnvVar ¶
RevealEnvVar returns the decrypted value of a single env var, scoped to the app. Secret values are decrypted; non-secret values are returned as-is. Used by the audited reveal endpoint so an operator can read a value they otherwise only see masked.
func (*Service) Rollback ¶
func (s *Service) Rollback(app *models.Application, releaseID uint) (*models.Deployment, error)
Rollback re-deploys a previous release's image.
func (*Service) Scale ¶
Scale sets the replica count of a cluster (service) app and applies it to the live Swarm service immediately (no redeploy). Rejected for container apps or when cluster mode is off.
func (*Service) SetCanaryRouting ¶ added in v1.9.0
func (s *Service) SetCanaryRouting(ctx context.Context, app *models.Application, in CanaryRouting) ([]string, error)
SetCanaryRouting validates and stores the app's canary steering, then re-syncs the route so a rule change takes effect immediately — no redeploy. The traffic weight is not touched: rules never shift traffic as a side effect of saving.
Returned warnings are advisory (the save happened); an error means nothing was written.
func (*Service) SetCanaryWeight ¶
SetCanaryWeight changes the share of traffic sent to the canary (1–99) and re-syncs the route immediately — no redeploy, no downtime.
0 is allowed only for an exclusive canary, where the rules alone decide who reaches it. For any other canary a 0 weight is a rule set that quietly routes nothing, so it is refused rather than clamped.
func (*Service) SetClusterCap ¶
func (s *Service) SetClusterCap(c ClusterCap)
SetClusterCap wires the cluster-capability check (nil-safe; nil means cluster mode is treated as off, so service-runtime apps are rejected).
func (*Service) SetConfigs ¶ added in v1.9.0
func (s *Service) SetConfigs(c ConfigReader)
SetConfigs supplies the config reader used to spot secrets referenced from a mounted file rather than from env.
func (*Service) SetContainerLabels ¶
SetContainerLabels validates and persists an app's user-defined Docker labels, enforcing the plan capability, the global kill-switch and the reserved-prefix protection. Labels take effect on the next deploy, exactly like port, volume and env edits.
func (*Service) SetGrantsEnabled ¶ added in v1.9.6
SetGrantsEnabled sets the platform master switch (MIABI_CONTAINER_GRANTS_ENABLED).
func (*Service) SetImageGuard ¶ added in v1.6.8
func (s *Service) SetImageGuard(g ImageGuard)
SetImageGuard wires the internal-registry image check (nil skips it).
func (*Service) SetName ¶
func (s *Service) SetName(app *models.Application, newName string) error
SetName validates and applies a new handle to app in memory; the caller persists via Update. The value is normalized to canonical slug form and must be unique within the workspace. Unlike create it does not auto-suffix, so a rename onto a taken handle is an error. Mirrors workspace.SetName.
func (*Service) SetNetworkEnsurer ¶
func (s *Service) SetNetworkEnsurer(e NetworkEnsurer)
SetNetworkEnsurer wires default-network self-healing (nil-safe). Without it, SetNetworks still attaches an already-existing default network, but cannot create a missing one.
func (*Service) SetNetworks ¶
func (s *Service) SetNetworks(app *models.Application, networkIDs []uint) error
SetNetworks attaches the given workspace networks to the app, always including the workspace's default. The default is what the app shares with its databases (a Swarm overlay in cluster mode), so an app on none deploys happily and resolves nothing. A missing default is repaired, not tolerated.
func (*Service) SetNodeGuard ¶
SetNodeGuard wires the placement guard consulted when creating an app on a node.
func (*Service) SetNodeNamer ¶
SetNodeNamer wires the swarm-node-id → name resolver used to annotate a cluster app with where its replicas actually run.
func (*Service) SetPipelines ¶ added in v1.6.8
SetPipelines wires repository pipeline adoption (nil-safe). Without it, a git app always builds and deploys directly, exactly as before this existed.
func (*Service) SetPortBindings ¶
func (s *Service) SetPortBindings(r *repositories.PortBindingRepository)
SetPortBindings wires the port-binding repository, whose rows go with a deleted app.
func (*Service) SetPorts ¶
func (s *Service) SetPorts(app *models.Application, specs []PortSpec) error
SetPorts replaces an application's declared container ports and keeps the primary Port field in sync with the first declared port.
func (*Service) SetReleasePinned ¶
func (s *Service) SetReleasePinned(app *models.Application, releaseID uint, pinned bool) (*models.Release, error)
SetReleasePinned protects (or unprotects) a release from cleanup deletion.
func (*Service) SetRouteSyncer ¶
func (s *Service) SetRouteSyncer(rs RouteSyncer)
SetRouteSyncer wires the route reconciler used by canary traffic changes.
func (*Service) SetServerInfo ¶
func (s *Service) SetServerInfo(si ServerInfo)
SetServerInfo wires the resolver used to annotate apps with their node's name.
func (*Service) SetSettings ¶
SetSettings wires the platform settings provider used to enforce resource caps.
func (*Service) SetSource ¶ added in v1.8.0
func (s *Service) SetSource(app *models.Application, in SourceInput) (*SourceChange, error)
SetSource replaces where an application's image comes from, including switching between a prebuilt image and a Git build. Before this existed the only way to change it was to delete the app and recreate it, which threw away its domains, env, volumes and history.
The fields of the source being left are CLEARED rather than kept. An app that still carried a git_repo after moving to an image would deploy correctly and read as though it built from that repo — and the stale value would come back to life the moment anyone switched it back.
func (*Service) SetWorkspaceInfo ¶
func (s *Service) SetWorkspaceInfo(w WorkspaceInfo)
SetWorkspaceInfo wires the resolver used to check a workspace's privileged flag.
func (*Service) Start ¶
func (s *Service) Start(ctx context.Context, app *models.Application) (*models.Deployment, error)
Start starts the app's stopped active container. If a redeploy is required (config changed while stopped) it redeploys instead, so the new config is applied rather than starting a stale container, returning that deployment so the caller can follow its logs. A plain start returns nil.
func (*Service) StartCanary ¶
func (s *Service) StartCanary(app *models.Application, registryOverride *uint, tagOverride string) (*models.Deployment, error)
func (*Service) Stop ¶
Stop stops the app's active container (it stays stopped; no auto-restart). For a service app it scales the service to zero replicas (the desired count stays recorded on the app, so Start restores it).
func (*Service) WaitRunning ¶
WaitRunning polls the app's active container until it reports the running state, or returns an error on timeout. Used as a basic readiness gate for rolling restarts so the next app isn't restarted until this one recovers.
type SourceChange ¶ added in v1.8.0
type SourceChange struct {
From models.AppSourceType `json:"from"`
To models.AppSourceType `json:"to"`
// Switched is false when only the details changed (a new tag, a different branch).
Switched bool `json:"switched"`
// PipelineRemoved is true when leaving git dropped a repo-owned pipeline.
PipelineRemoved bool `json:"pipeline_removed"`
// RedeployRequired is true when the running container no longer matches the source.
RedeployRequired bool `json:"redeploy_required"`
}
SourceChange reports what SetSource did, so the caller can tell the operator what else moved — none of it is guessable from the app record afterwards.
type SourceInput ¶ added in v1.8.0
type SourceInput struct {
SourceType models.AppSourceType
// Image source.
Image string
Tag string
RegistryID *uint
// Git source.
GitRepo string
GitRef string
GitRepositoryID *uint
BuildMethod models.AppBuildMethod
Builder string
Buildpacks []string
BuildEnv map[string]string
}
SourceInput is a complete replacement of an application's source. It is deliberately not a patch: switching image <-> git changes which fields are even meaningful, so a partial payload would leave the app describing two sources at once.