workload

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package workload runs services (§4, §5.2–5.3): it validates task definitions, places tasks on nodes and reconciles desired with observed state.

Index

Constants

View Source
const (
	MinImagePoll     = 60
	MaxImagePoll     = 24 * 3600
	DefaultImagePoll = 300
)

Image watch polling bounds (seconds).

View Source
const (
	TopicService = "service.updated"
	TopicTask    = "task.updated"
	// TaskIDPrefix marks service tasks (system tasks use "sys-").
	TaskIDPrefix = "task_"
	// Network is the Docker network every service task joins (§8).
	Network = "syncloud"
)

Event topics.

View Source
const (
	ResourceShared   = "" // the default; "shared" is accepted for it
	ResourceReserved = "reserved"
)

Resource modes.

View Source
const (
	KindService  = "service"
	KindDatabase = "database"
)

Task kinds.

View Source
const AwaitingBuild = "@build"

AwaitingBuild is the image of a service built from Git before its first build: it runs no tasks until a build is deployed (§5.8).

View Source
const NoMemoryLimit = -1

NoMemoryLimit as memoryLimit lets a task use whatever memory is free (Phase 27); left out, the limit is twice memory, as it always was.

View Source
const TLSTerminate = "terminate"

TLS modes of a public TCP port.

Variables

View Source
var CentralCheck = func(taskID string) (state, err string) { return "", "" }

CentralCheck returns the controller's probe state of a task (set by the health monitor).

View Source
var DefaultDrain = 5 * time.Second

DefaultDrain is the drain time of tasks with ports when the spec sets none.

View Source
var DefaultPublicPorts = [2]int{20000, 20999}

DefaultPublicPorts is the range public TCP/UDP ports are assigned from.

View Source
var Discovery = func(sv store.Service) (vip, dnsName string) { return "", "" }

Discovery returns a service's VIP and internal DNS name (set by the discovery layer).

View Source
var Endpoints = func(sv store.Service, spec Spec, domains []store.Domain, routing []store.PortRouting) []string {
	return nil
}

Endpoints returns the public URLs of a service (set by the routing layer).

View Source
var ProjectBase func(project, base string) string

ProjectBase returns the base domain of a project's generated addresses and public ports (nil: the cluster's). A project with its own ingress nodes gets the first one's sslip.io name (Phase 23).

Functions

func Allocatable

func Allocatable(cores int, memoryBytes uint64) (float64, int)

Allocatable keeps headroom for the OS, Docker and the agent.

func CPUShares added in v0.1.5

func CPUShares(r Resources) int64

CPUShares is the Docker CPU weight of a task: its cpu in units of 1024 per core, reservedWeight times that when reserved, within Docker's 2–262144.

func DomainRouteName added in v0.1.4

func DomainRouteName(id string) string

DomainRouteName is the Traefik router and service name of a custom domain ("dom_xy34" → "dom-xy34").

func HasDigest added in v0.1.7

func HasDigest(image string) bool

HasDigest reports whether an image reference names its own digest ("repo@sha256:…"): nothing to resolve.

func HostName

func HostName(sv store.Service, p Port, first bool, base string) string

HostName is the default hostname of a service's HTTP port: <service>-<env>-<project> for the first one, <service>-<port>-<env>-<project> for the others, under base (or "localhost" before a base domain exists).

func Place

func Place(cands []Candidate, r Resources, strategy string) (string, string)

Place picks a node for one task (§5.3): filter, then score. It returns "" and a reason when no node fits.

Shared CPU never rules a node out: CPU is shared out by weight, so a busy node is slower, not full. Reserved CPU needs that many unreserved cores. Memory, shared or reserved, needs that much free on the node (FreeMemory).

func PublicAddress

func PublicAddress(base string, port int) string

PublicAddress is where clients reach a public TCP/UDP port.

func ServiceEndpoints

func ServiceEndpoints(sv store.Service, spec Spec, base, scheme, port string, routing []store.PortRouting) []string

ServiceEndpoints returns a service's generated public URLs.

func TaskSpec

func TaskSpec(sv store.Service, spec Spec, t store.Task) *agentv1.TaskSpec

TaskSpec is what the agent runs for a task.

func ValidName

func ValidName(s string) error

ValidName checks project, environment, service and port names: DNS labels short enough to combine into hostnames like <svc>-<env>-<project>.<domain>.

func ValidNodeName

func ValidNodeName(s string) bool

ValidNodeName checks a node name.

func ValidateEnv

func ValidateEnv(env map[string]string) error

ValidateEnv checks environment variable names.

func WithCause

func WithCause(ctx context.Context, c Cause) context.Context

WithCause marks the deployments started under ctx.

func WithHeldFirstDeploy

func WithHeldFirstDeploy(ctx context.Context) context.Context

WithHeldFirstDeploy makes a service created under ctx wait for its pre-deploy jobs before its first tasks start: the caller adds the jobs, then starts them with DeployHooks.RunPreDeploy for the service's deployment.

func WithImageRefresh added in v0.1.7

func WithImageRefresh(ctx context.Context) context.Context

WithImageRefresh makes Apply resolve the image's tag again even when the image is unchanged, picking up a newer push (image auto-deploys).

Types

type AdmitRequest

type AdmitRequest struct {
	EnvironmentID string
	ServiceID     string // "" for a new service
	Spec          *Spec  // nil: the current spec
	Desired       int
}

AdmitRequest is a change to a service's footprint, checked against quotas (§7.2) before it is stored.

type Candidate

type Candidate struct {
	ID, Name  string
	CPU       float64 // allocatable cores
	MemoryMiB int     // allocatable MiB
	// ReservedCPU and ReservedMemory are set aside by reserved tasks and
	// database members.
	ReservedCPU    float64
	ReservedMemory int
	// UsedMemory is what the node really uses (its last report), plus what
	// tasks still starting are expected to use. CPULoad is the cores in use.
	UsedMemory  int
	CPULoad     float64
	ServiceRuns int // active tasks of the service being placed
	TotalRuns   int // active tasks of all services
	Eligible    bool
	Why         string // why not eligible
}

Candidate is a node as the scheduler sees it.

func (Candidate) FreeMemory added in v0.1.5

func (c Candidate) FreeMemory() int

FreeMemory is the memory a new task can have: what is neither reserved nor in use, whichever is more.

type Cause

type Cause struct {
	Trigger string // store.Trigger*
	BuildID string
}

Cause says what started a deployment (Phase 15a).

type Change

type Change struct {
	Field string `json:"field"`
	From  string `json:"from,omitempty"`
	To    string `json:"to,omitempty"`
}

Change is one difference between two revisions of a service (Phase 15a). Variable values are never included, only their names.

func DecodeChanges

func DecodeChanges(raw string) []Change

DecodeChanges reads a stored change summary.

func Diff

func Diff(a, b Spec) []Change

Diff summarizes what changes from revision a to b.

type CloneResult

type CloneResult struct {
	Environment store.Environment `json:"environment"`
	Services    []string          `json:"services"`
	// ServiceIDs maps each source service ID to its copy's (jobs and
	// security groups follow them).
	ServiceIDs map[string]string `json:"-"`
}

CloneResult is what cloning an environment created.

type DeployHooks

type DeployHooks interface {
	// HasPreDeploy reports whether the service has pre-deploy jobs.
	HasPreDeploy(ctx context.Context, sv store.Service) bool
	// RunPreDeploy starts them for revision toRev of deployment depID; the
	// outcome comes back through Manager.PreDeployDone.
	RunPreDeploy(ctx context.Context, sv store.Service, toRev int, depID string)
	// RunPostDeploy starts post-deploy jobs after a deployment succeeded.
	RunPostDeploy(ctx context.Context, sv store.Service, dep store.Deployment)
	// CancelHooks stops the pre-deploy runs of a cancelled deployment.
	CancelHooks(ctx context.Context, depID string)
}

DeployHooks lets the jobs subsystem gate and follow deployments.

type Deployment

type Deployment struct {
	// CircuitBreaker stops a rollout whose new tasks keep failing (default on).
	CircuitBreaker *bool `json:"circuitBreaker,omitempty"`
	// Rollback returns to the previous revision when the breaker trips (default on).
	Rollback *bool `json:"rollback,omitempty"`
	// DrainSeconds keeps a retired task running after it leaves the routes
	// and service VIPs, so Traefik (which polls every 2s) and in-flight
	// requests stop using it before it stops (default 5, 0 = stop at once).
	DrainSeconds *int `json:"drainSeconds,omitempty"`
}

Deployment controls rollouts (§5.4).

type DeploymentDetail

type DeploymentDetail struct {
	store.Deployment
	Changes []Change                `json:"changes"`
	Events  []store.DeploymentEvent `json:"events"`
}

DeploymentDetail is a deployment with its timeline and what changed.

type DomainInput

type DomainInput struct {
	Host        string // validated and normalized by the caller
	Port        string // the HTTP port ("" = the first)
	Path        string // a path prefix ("" = the whole host)
	StripPrefix bool
	RedirectTo  string // validated and normalized by the caller; "" = route
}

DomainInput is a custom domain to add (Phase 15c adds Path, StripPrefix and RedirectTo).

type ErrDeploysByHand added in v0.1.7

type ErrDeploysByHand struct{ Environment string }

ErrDeploysByHand means the environment takes no automatic deploys.

func (ErrDeploysByHand) Error added in v0.1.7

func (e ErrDeploysByHand) Error() string

type ErrInvalid

type ErrInvalid struct{ Err error }

ErrInvalid wraps validation errors.

func (ErrInvalid) Error

func (e ErrInvalid) Error() string

type ErrLocked

type ErrLocked struct{ Lock store.DeployLock }

ErrLocked means the environment's deploys are locked.

func (ErrLocked) Error

func (e ErrLocked) Error() string

type ErrNotWatchable added in v0.1.7

type ErrNotWatchable struct{ Reason string }

ErrNotWatchable means the service cannot follow its image's tag.

func (ErrNotWatchable) Error added in v0.1.7

func (e ErrNotWatchable) Error() string

type ErrQuota

type ErrQuota struct{ Msg string }

ErrQuota means a change would exceed a quota.

func (ErrQuota) Error

func (e ErrQuota) Error() string

type HealthCheck

type HealthCheck struct {
	Type        string   `json:"type"`                  // http | tcp | cmd
	Path        string   `json:"path,omitempty"`        // http (default /)
	Port        string   `json:"port,omitempty"`        // port name (default: the first port)
	Command     []string `json:"command,omitempty"`     // cmd: exit 0 = healthy
	Interval    int      `json:"interval,omitempty"`    // seconds (default 10)
	Timeout     int      `json:"timeout,omitempty"`     // seconds (default 3)
	Retries     int      `json:"retries,omitempty"`     // consecutive failures before unhealthy (default 3)
	StartPeriod int      `json:"startPeriod,omitempty"` // seconds in which failures do not count (default 10)
}

HealthCheck defines how a task's health is probed.

type ImageUpdate added in v0.1.7

type ImageUpdate struct {
	Deployed bool   `json:"deployed"`
	Digest   string `json:"digest"`
	Revision int    `json:"revision"`
	Message  string `json:"message"`
}

ImageUpdate is the outcome of a check for a newer image.

type Manager

type Manager struct {

	// OnChange runs after a reconcile that changed tasks or services (routes, certificates).
	OnChange func()
	// OnTaskChange runs whenever a task's state changes (service directory).
	OnTaskChange func()
	// AdmitCount checks a count quota (domains) before adding one.
	AdmitCount func(ctx context.Context, envID, what string) error

	// NodePool names a node's pool and its role ("" and "worker" for nodes
	// outside any pool); edge nodes only run tasks that ask for their pool.
	NodePool func(nodeID string) (pool, role string)
	// Admit checks a change against quotas (§7.2); nil admits everything.
	Admit func(ctx context.Context, req AdmitRequest) error
	// Reachable reports whether the controller can reach a task over the
	// private network (§5.6); routes leave out tasks it cannot.
	Reachable func(taskID string) bool
	// DNS returns the resolver and search domains for a task on a node
	// (nil before the node's private network exists).
	DNS func(nodeID string, sv store.Service) (servers, search []string)
	// Hooks runs pre- and post-deploy jobs (§5.11); may be nil.
	DeployHooks DeployHooks
	// ResolveImage turns "@registry/…" into the private registry's reference
	// and returns pull credentials for the node (§5.9); may be nil.
	ResolveImage func(image string) (ref, registryAuth string)
	// ResolveDigest returns the digest an image's tag points to now (an
	// image of the built-in registry or of any other); may be nil.
	ResolveDigest func(ctx context.Context, image string) (string, error)
	// RegistryCA returns a certificate nodes must trust to pull a resolved
	// image ("" = none): the platform registry's, while self-signed.
	RegistryCA func(ref string) string
	// S3Bindings lists a service's S3 bindings for a new revision; S3Env
	// turns one into environment variables with credentials (§16).
	S3Bindings func(ctx context.Context, serviceID string) ([]S3Ref, error)
	S3Env      func(ctx context.Context, ref S3Ref) (map[string]string, error)
	// ExtraUsage is per-node reservations outside service tasks (database
	// members), counted when placing.
	ExtraUsage func(ctx context.Context) map[string]Usage
	// ImageAvailable reports whether an image can still be pulled (false
	// once registry cleanup removed it); may be nil.
	ImageAvailable func(ctx context.Context, image string) (bool, error)
	// PublicPortRange is where public TCP/UDP ports are assigned from (zero:
	// DefaultPublicPorts); OnPublicPorts runs when the set of public ports
	// changes (Traefik entrypoints and firewall rules follow it).
	PublicPortRange [2]int
	OnPublicPorts   func()
	// Ports is the port table (Phase 26): public ports are checked and
	// claimed there (nil: a table of its own, every port on one node).
	Ports *ports.Ledger
	// contains filtered or unexported fields
}

Manager owns the reconciler (§5.2) and scheduler (§5.3).

func NewManager

func NewManager(st *store.Store, gw *agentgw.Gateway, reg *nodes.Registry, netReady NetworkReady, bus *events.Bus, log *slog.Logger) *Manager

func (*Manager) ActiveTasks

func (m *Manager) ActiveTasks(ctx context.Context) ([]TaskView, error)

ActiveTasks lists every active task in the cluster.

func (*Manager) AddDomain

func (m *Manager) AddDomain(ctx context.Context, serviceID string, in DomainInput) (store.Domain, error)

AddDomain routes a host (or a path of it) to one of the service's HTTP ports, or makes it redirect to another host.

func (*Manager) Apply

func (m *Manager) Apply(ctx context.Context, env store.Environment, name string, spec Spec, desired int, actor string) (ServiceView, bool, error)

Apply creates the service or updates it (a spec change creates a revision and rolls it out). desired < 0 keeps the current count (1 for new services).

func (*Manager) CancelDeployment

func (m *Manager) CancelDeployment(ctx context.Context, serviceID, depID, actor string) (ServiceView, error)

CancelDeployment stops a deployment that is running or waiting on its pre-deploy jobs. A running one rolls back to the revision before it.

func (*Manager) CloneEnvironment

func (m *Manager) CloneEnvironment(ctx context.Context, src store.Environment, name string, start bool, actor string) (CloneResult, error)

CloneEnvironment creates an environment from another: its shared variables and every service's current spec, scaled to 0 unless start. Domains, public ports, Git sources, S3 bindings and databases are not copied.

func (*Manager) Delete

func (m *Manager) Delete(ctx context.Context, serviceID string) error

Delete stops all tasks, then removes the service.

func (*Manager) DeleteEnvironment

func (m *Manager) DeleteEnvironment(ctx context.Context, e store.Environment, force bool) (pending bool, err error)

DeleteEnvironment deletes an environment. Without force it must be empty; with force its services are deleted first and the environment goes when they are gone. Databases are never deleted this way.

func (*Manager) DeleteProject

func (m *Manager) DeleteProject(ctx context.Context, p store.Project, force bool) (pending bool, err error)

DeleteProject deletes a project the same way, environment by environment.

func (*Manager) DeployNewImage added in v0.1.7

func (m *Manager) DeployNewImage(ctx context.Context, serviceID, actor string) (ImageUpdate, error)

DeployNewImage deploys the image the service's tag points to now, when it differs from the running revision's. actor names who asked (the watcher, the webhook). The environment's policy applies: a locked environment, or one that deploys by hand, is not deployed to.

func (*Manager) DeploymentEvent

func (m *Manager) DeploymentEvent(ctx context.Context, depID, kind, msg string)

DeploymentEvent appends a step to a deployment's timeline.

func (*Manager) Detail

Detail decodes a deployment's change summary and loads its timeline.

func (*Manager) Enqueue

func (m *Manager) Enqueue(serviceID string)

Enqueue schedules a reconcile of one service.

func (*Manager) EnqueueAll

func (m *Manager) EnqueueAll()

EnqueueAll schedules every service.

func (*Manager) Hooks

func (m *Manager) Hooks() agentgw.Hooks

func (*Manager) InvalidateRoutes

func (m *Manager) InvalidateRoutes()

InvalidateRoutes rebuilds routes on the next read (e.g. a task became unreachable from the controller).

func (*Manager) KickImageWatch added in v0.1.7

func (m *Manager) KickImageWatch()

KickImageWatch checks the watched images of the built-in registry now (after a push to it).

func (*Manager) ListServices

func (m *Manager) ListServices(ctx context.Context, environmentID string) ([]ServiceView, error)

ListServices returns services in an environment ("" = all).

func (*Manager) PlaceBuild

func (m *Manager) PlaceBuild(ctx context.Context, spec Spec) (string, string)

PlaceBuild picks a node for a platform build: like PlaceSpec, but the controller node is a candidate even when it takes no user tasks, as BuildKit runs there by default (§5.0) and small clusters may have no worker with room for a build.

func (*Manager) PlaceSpec

func (m *Manager) PlaceSpec(ctx context.Context, spec Spec) (string, string)

PlaceSpec picks a node for a one-off task with spec's resources.

func (*Manager) PortWants added in v0.4.0

func (m *Manager) PortWants(ctx context.Context) map[ports.Owner][]ports.Want

PortWants are every service's public ports, for the port table's resync.

func (*Manager) PreDeployDone

func (m *Manager) PreDeployDone(ctx context.Context, depID string, ok bool, msg string)

PreDeployDone finishes the pre-deploy phase of a deployment: on success the new revision becomes current and rolls out; on failure the deployment fails and the old revision keeps running.

func (*Manager) PublicRoutes

func (m *Manager) PublicRoutes(ctx context.Context) []PublicRoute

PublicRoutes returns every public TCP/UDP port with the running tasks behind it.

func (*Manager) Redeploy

func (m *Manager) Redeploy(ctx context.Context, serviceID, actor string, runHooks bool) (ServiceView, error)

Redeploy restarts every task with a rolling deployment of the current spec, as a new revision marked with the time. Pre-deploy jobs run with runHooks.

func (*Manager) RemoveDomain

func (m *Manager) RemoveDomain(ctx context.Context, serviceID, ref string) error

RemoveDomain stops routing a domain (by ID, or every path of a host) to the service.

func (*Manager) Reserved

func (m *Manager) Reserved(ctx context.Context) map[string]Usage

Reserved is every node's reservations: service tasks plus ExtraUsage.

func (*Manager) RestartTask

func (m *Manager) RestartTask(ctx context.Context, taskID string) error

RestartTask stops one task; the reconciler starts a replacement.

func (*Manager) RestrictToEnvironment

func (m *Manager) RestrictToEnvironment(ctx context.Context, envID string, spec Spec) Spec

RestrictToEnvironment limits spec to the allowed nodes of the environment's project (for job runs).

func (*Manager) Rollback

func (m *Manager) Rollback(ctx context.Context, serviceID string, revision int, actor string, runHooks bool) (ServiceView, error)

Rollback makes an earlier revision current again (as a new revision). Pre-deploy hooks run only with runHooks: migrations are usually forward-only.

func (*Manager) Routes

func (m *Manager) Routes(ctx context.Context, base string) []Route

Routes returns every service route for base domain base. It is cheap to call often (Traefik polls every 2s): results are cached until tasks or services change.

func (*Manager) Routing

func (m *Manager) Routing(ctx context.Context, serviceID, base string) ([]PortRoute, error)

Routing returns how each port of a service is reached.

func (*Manager) Run

func (m *Manager) Run(ctx context.Context)

Run processes the queue until ctx ends. Services are reconciled one at a time per service; different services run in parallel.

func (*Manager) RunImageWatch added in v0.1.7

func (m *Manager) RunImageWatch(ctx context.Context)

RunImageWatch checks watched images until ctx ends: those in the built-in registry at every tick (and on a kick), others every pollSeconds.

func (*Manager) RunSpec

func (m *Manager) RunSpec(sv store.Service, spec Spec, t store.Task) *agentv1.TaskSpec

RunSpec builds the agent spec for a job run on a node, with the node's DNS.

func (*Manager) Scale

func (m *Manager) Scale(ctx context.Context, serviceID string, desired int, actor string) (ServiceView, error)

Scale sets the desired count.

func (*Manager) ServiceTasks

func (m *Manager) ServiceTasks(ctx context.Context, serviceID string) ([]TaskView, error)

ServiceTasks lists a service's tasks (active first, then recent history).

func (*Manager) ServiceView

func (m *Manager) ServiceView(ctx context.Context, id string) (ServiceView, error)

func (*Manager) Serving

func (m *Manager) Serving(ctx context.Context, t store.Task) bool

Serving reports whether a task receives traffic (running and healthy).

func (*Manager) SetRouting

func (m *Manager) SetRouting(ctx context.Context, serviceID string, in map[string]RoutingInput, base string) ([]PortRoute, error)

SetRouting changes how a service's ports are reached. Making a TCP or UDP port public assigns it a free port from PublicPorts, or the one asked for; the ports are claimed in the port table on every node of the project's load balancer, in the same transaction. OnPublicPorts runs when the set of public ports changed (Traefik needs new entrypoints).

func (*Manager) SetSharedEnv

func (m *Manager) SetSharedEnv(ctx context.Context, env store.Environment, vars map[string]string, actor string) ([]string, error)

SetSharedEnv replaces an environment's shared variables and rolls them out: every service whose variables change gets a new revision (a normal rolling deployment). It returns the services that were redeployed.

func (*Manager) SpecFor

func (m *Manager) SpecFor(ctx context.Context, serviceID string, rev int) (Spec, error)

SpecFor returns a revision's spec (cached; revisions never change).

func (*Manager) TaskEvent added in v0.2.4

func (m *Manager) TaskEvent(ctx context.Context, t store.Task, kind, level, msg string, at time.Time)

TaskEvent records a step of one task (its node's agent pulling or starting it, a health check, the controller's probe) in its deployment's log.

func (*Manager) UnplacedDemand

func (m *Manager) UnplacedDemand() []Unplaced

UnplacedDemand lists services waiting for capacity.

func (*Manager) Watchable added in v0.1.7

func (m *Manager) Watchable(ctx context.Context, sv store.Service) error

Watchable reports whether a service can auto-deploy pushes of its image: not one built from Git (its builds deploy it), and not one whose image names a fixed digest.

type NetworkReady

type NetworkReady func(nodeID string) bool

NetworkReady reports whether tasks can be placed on a node.

type Placement

type Placement struct {
	Strategy string `json:"strategy"` // spread (default) | binpack
	// Node pins tasks to one node by name (e.g. builds on the controller).
	Node string `json:"node,omitempty"`
	// Pools limits tasks to node pools ("default" is nodes outside any pool).
	Pools []string `json:"pools,omitempty"`
	// Nodes limits tasks to these nodes by name, within the project's
	// allowed nodes (§6.3). Naming the controller node runs tasks there even
	// when it takes no general workloads.
	Nodes []string `json:"nodes,omitempty"`
	// contains filtered or unexported fields
}

func (Placement) Allows

func (p Placement) Allows(node string) bool

Allows reports whether a task may run on the named node.

func (Placement) Names

func (p Placement) Names(node string) bool

Names reports whether the node is named explicitly (pinned or listed).

type Port

type Port struct {
	Name      string `json:"name"`
	Container int    `json:"container"`
	Protocol  string `json:"protocol"` // http (default), tcp, udp
}

Port is a container port. HTTP ports get a public route (§5.7).

type PortRoute

type PortRoute struct {
	Port      string `json:"port"`
	Container int    `json:"container"`
	Protocol  string `json:"protocol"`
	// HTTP ports: the generated address is served unless Generated is off;
	// Label replaces its name (<label>.<base domain>).
	Generated bool   `json:"generated"`
	Label     string `json:"label,omitempty"`
	Host      string `json:"host,omitempty"` // the generated address, when served
	// TCP and UDP ports: a public port on the project's load balancer.
	Public     bool     `json:"public"`
	PublicPort int      `json:"publicPort,omitempty"`
	Address    string   `json:"address,omitempty"` // what clients connect to
	Allow      []string `json:"allow"`
	// PortMode is how the public port was picked: auto (from the range) or
	// chosen (Phase 26).
	PortMode string `json:"portMode,omitempty"`
	// TCP only: PROXY protocol to the app, TLS at the load balancer.
	ProxyProtocol bool   `json:"proxyProtocol,omitempty"`
	TLS           string `json:"tls,omitempty"` // "" (raw) | terminate
}

PortRoute is one port of a service with how it is reached.

type PublicRoute

type PublicRoute struct {
	Name      string // stable Traefik name
	Protocol  string // tcp | udp
	Port      int    // the public port
	Servers   []string
	Allow     []string
	ServiceID string
	Project   string
	// TCP only (Phase 26): PROXY protocol to the app, TLS at the load
	// balancer.
	ProxyProtocol bool
	TLS           string
}

PublicRoute is a public TCP or UDP port of a service.

func (PublicRoute) Entrypoint

func (r PublicRoute) Entrypoint() string

Entrypoint is the Traefik entrypoint of a public port.

type Resources

type Resources struct {
	CPU         float64 `json:"cpu"`                   // cores expected, or reserved (default 0.1)
	Memory      int     `json:"memory"`                // MiB expected, or reserved (default 128)
	CPUMode     string  `json:"cpuMode,omitempty"`     // "" (shared) | "reserved"
	MemoryMode  string  `json:"memoryMode,omitempty"`  // "" (shared) | "reserved"
	CPULimit    float64 `json:"cpuLimit,omitempty"`    // cores, hard limit (0 = none)
	MemoryLimit int     `json:"memoryLimit,omitempty"` // MiB, hard limit (default = 2 × memory; NoMemoryLimit = none)
}

Resources are what a task needs, how placement treats it, and optional hard limits.

CPU and memory are shared by default: they say what the task is expected to use. Placement goes by what nodes really use, CPU never stops a task from being placed (a busy node is slower, not full), and under contention tasks get CPU in proportion to their cpu. Reserved (CPUMode or MemoryMode "reserved") sets the amount aside: placement only uses a node with that much unreserved, whatever the node's load.

func (Resources) ReservedCPU added in v0.1.5

func (r Resources) ReservedCPU() float64

ReservedCPU is the CPU the task sets aside (0 when shared).

func (Resources) ReservedMemory added in v0.1.5

func (r Resources) ReservedMemory() int

ReservedMemory is the memory the task sets aside (0 when shared).

type Route

type Route struct {
	Name      string   // stable Traefik router/service name
	Host      string   // public hostname
	Servers   []string // http://<task-ip>:<port> of running tasks
	ServiceID string
	Project   string
	// Generated: the port's generated address (not a custom domain).
	Generated bool
	// Path limits a custom domain's route to a prefix; StripPrefix removes
	// it before forwarding; RedirectTo answers with a 301 to that host.
	Path        string
	StripPrefix bool
	RedirectTo  string
}

Route is one public HTTP route to a service port (§5.7).

type RoutingInput

type RoutingInput struct {
	Generated *bool    `json:"generated,omitempty"`
	Label     *string  `json:"label,omitempty"`
	Public    *bool    `json:"public,omitempty"`
	Allow     []string `json:"allow,omitempty"`
	// PublicPort chooses the public port (tcp/udp; it makes the port
	// public); 0 goes back to an automatic one.
	PublicPort *int `json:"publicPort,omitempty"`
	// ProxyProtocol (tcp) sends the client's address to the app first.
	ProxyProtocol *bool `json:"proxyProtocol,omitempty"`
	// TLS (tcp): "none" or "" for raw bytes, "terminate" for TLS at the
	// load balancer.
	TLS *string `json:"tls,omitempty"`
}

RoutingInput changes one port's routing; nil fields keep their value.

type S3Ref

type S3Ref struct {
	Endpoint  string `json:"endpoint"` // name
	Bucket    string `json:"bucket"`
	Prefix    string `json:"prefix,omitempty"`
	EnvPrefix string `json:"envPrefix,omitempty"`
}

S3Ref is a bucket bound to the service: its tasks get <EnvPrefix>S3_BUCKET, <EnvPrefix>AWS_ACCESS_KEY_ID and so on.

type ServiceView

type ServiceView struct {
	ID           string   `json:"id"`
	Project      string   `json:"project"`
	Environment  string   `json:"environment"`
	Name         string   `json:"name"`
	Revision     int      `json:"revision"`
	DesiredCount int      `json:"desiredCount"`
	Running      int      `json:"running"`
	Pending      int      `json:"pending"`
	Status       string   `json:"status"`
	Deleting     bool     `json:"deleting"`
	Spec         Spec     `json:"spec"`
	Endpoints    []string `json:"endpoints"`
	VIP          string   `json:"vip"`
	// Deployment is the latest rollout.
	Deployment *store.Deployment `json:"deployment"`
	DNSName    string            `json:"dnsName"`
	CreatedAt  time.Time         `json:"createdAt"`
	UpdatedAt  time.Time         `json:"updatedAt"`
}

ServiceView is a service as the API shows it.

type Spec

type Spec struct {
	Image string `json:"image"`
	// ImageDigest pins Image to the exact version its tag pointed to when
	// the revision was made ("sha256:…"), set by the platform: every node
	// pulls exactly that, a redeploy picks up a newer push of the same
	// tag, and a rollback returns to the exact old image. Empty when the
	// image names its own digest or could not be resolved.
	ImageDigest string            `json:"imageDigest,omitempty"`
	Entrypoint  []string          `json:"entrypoint,omitempty"` // replaces the image ENTRYPOINT
	Command     []string          `json:"command,omitempty"`
	Env         map[string]string `json:"env,omitempty"`
	// SharedEnv is a snapshot of the environment's shared variables, taken
	// by the platform for every revision (never user-set). Env wins over it.
	SharedEnv map[string]string `json:"sharedEnv,omitempty"`
	// S3 snapshots the service's S3 bindings (§16) for every revision, set
	// by the platform; credentials are added when a task starts.
	S3        []S3Ref   `json:"s3,omitempty"`
	Ports     []Port    `json:"ports,omitempty"`
	Resources Resources `json:"resources"`
	Placement Placement `json:"placement"`
	// Health is probed by the agent (§5.6); traffic only reaches healthy tasks.
	Health     *HealthCheck `json:"health,omitempty"`
	Deployment Deployment   `json:"deployment"`
	// RedeployedAt is set by the platform for a redeploy of an unchanged
	// spec (Phase 15a), so the restart is a revision of its own.
	RedeployedAt string `json:"redeployedAt,omitempty"`
}

Spec is one immutable task definition revision (one container per task).

func ParseSpec

func ParseSpec(raw string) (Spec, error)

ParseSpec reads a stored spec.

func (Spec) Avoiding

func (s Spec) Avoiding(nodes []string) Spec

Avoiding returns spec kept off the named nodes (e.g. a database's other members). Never stored.

func (Spec) Canonical

func (s Spec) Canonical() string

Canonical is the stored form; equal specs give equal strings.

func (Spec) HTTPPorts

func (s Spec) HTTPPorts() []Port

HTTPPorts returns the ports that get public routes, in order.

func (Spec) ImageRef added in v0.1.7

func (s Spec) ImageRef() string

ImageRef is what nodes pull and run: the image pinned to its digest ("nginx:1.27@sha256:…"; Docker ignores the tag), or the image as given.

func (*Spec) Normalize

func (s *Spec) Normalize() error

Normalize fills defaults and validates.

func (Spec) PortNumber

func (s Spec) PortNumber(name string) (int, bool)

PortNumber resolves a port name.

func (Spec) WithProjectNodes

func (s Spec) WithProjectNodes(nodes []string) Spec

WithProjectNodes returns spec limited to a project's allowed nodes as well (none = any). The limit is applied at placement and not stored, so changing a project's nodes does not create service revisions.

type TaskView

type TaskView struct {
	ID          string `json:"id"`
	ServiceID   string `json:"serviceId"`
	Project     string `json:"project"`
	Environment string `json:"environment"`
	Service     string `json:"service"`
	Revision    int    `json:"revision"`
	NodeID      string `json:"nodeId"`
	Node        string `json:"node"`
	Desired     string `json:"desired"`
	State       string `json:"state"`
	IP          string `json:"ip"`
	ContainerID string `json:"containerId"`
	Health      string `json:"health"`
	// HealthError is why the last health check on the task's node failed.
	HealthError string     `json:"healthError,omitempty"`
	ExitCode    int        `json:"exitCode"`
	Error       string     `json:"error"`
	CreatedAt   time.Time  `json:"createdAt"`
	StartedAt   *time.Time `json:"startedAt"`
	FinishedAt  *time.Time `json:"finishedAt"`
	// Central is the controller's probe over the private network (§5.6):
	// ok, failing or unreachable ("" when not probed).
	Central      string `json:"central,omitempty"`
	CentralError string `json:"centralError,omitempty"`
	// Kind is "service", or "database" for a database member: Database and
	// Engine name it, Member is its name in the database (m0, s1…) and Role
	// its part (primary, replica, sentinel).
	Kind     string `json:"kind"`
	Database string `json:"database,omitempty"`
	Engine   string `json:"engine,omitempty"`
	Member   string `json:"member,omitempty"`
	Role     string `json:"role,omitempty"`
}

TaskView is a task as the API shows it.

type Unplaced

type Unplaced struct {
	ServiceID string
	Count     int
	CPU       float64 // per task
	MemoryMiB int
	Pools     []string
	Since     time.Time
}

Unplaced is demand the cluster cannot place: tasks a service is missing because no node has room (the cluster autoscaler's signal, §6.5).

type Usage

type Usage struct {
	CPU       float64
	MemoryMiB int
	Count     int
}

Usage is resources reserved on a node outside service tasks.

Jump to

Keyboard shortcuts

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