Help us shape the future of Go! Take the 2026 Go Developer Survey

apiclient

package
v0.34.5 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package apiclient talks over HTTP to the runtime API of the Deckhouse controller (Module v2), served on the pod IP (the "self" port): probes, metrics, pprof, queues, scheduler, requirements and packages.

The controller of deckhouse main at 8010976436 does not serve /api/v1/packages over HTTP yet, so there those routes answer 404.

Index

Constants

View Source
const (
	OutputJSON = "json"
	OutputYAML = "yaml"
)

Output formats the API encodes dumps in, chosen with the output query parameter.

View Source
const (
	// Namespace is where the Deckhouse controller runs.
	Namespace = "d8-system"
	// ContainerName is the controller container of the deckhouse pod.
	ContainerName = "deckhouse"
)
View Source
const APIPrefix = "/api/v1"

APIPrefix is where the controller mounts the versioned API (apiPrefix in deckhouse-controller/internal/packages/api/handlers/root).

Variables

View Source
var (
	// ErrNotFound is a 404: a route the controller does not serve over HTTP, such as
	// any route of a controller without Module v2, or a package it does not know.
	ErrNotFound = errors.New("not found")
	// ErrBadRequest is a 400: an output format the API does not know, or a render
	// of a package that has no Helm chart.
	ErrBadRequest = errors.New("bad request")
	// ErrServerError is a 5xx: the controller failed to answer, a render failure for
	// one, an unknown package included.
	ErrServerError = errors.New("server error")
	// ErrUnknownPackage is a dump that answered null for the package asked for.
	ErrUnknownPackage = errors.New("unknown package")
	// ErrGlobalNotLoaded is the global module dump before the runtime has
	// initialized the global module.
	ErrGlobalNotLoaded = errors.New("global module is not loaded")
	// ErrNotReady is a replica whose /readyz answers that it is not ready.
	ErrNotReady = errors.New("not ready")
	// ErrNoLeader is a cluster without a pod of the leading controller replica.
	ErrNoLeader = errors.New("no Deckhouse leader pod")
	// ErrNoSelfPort is a controller pod whose container declares no "self" port,
	// where the API listens.
	ErrNoSelfPort = errors.New(`no "self" port`)
)

Sentinel errors of the client, for errors.Is. A StatusError unwraps to the one of its status class; the others come wrapped with the name or object they concern.

Functions

func LeaderPod

func LeaderPod(ctx context.Context, kubeCl kubernetes.Interface) (*corev1.Pod, error)

LeaderPod returns the pod of the leading controller replica.

func Pod

func Pod(ctx context.Context, kubeCl kubernetes.Interface, name string) (*corev1.Pod, error)

Pod returns the named controller pod, to query a replica other than the leader.

Types

type Application

type Application struct {
	Status PackageStatus `json:"status"`
	// Name is the instance name.
	Name       string                `json:"name"`
	Namespace  string                `json:"namespace"`
	Path       string                `json:"path"`
	Running    bool                  `json:"running"`
	Definition ApplicationDefinition `json:"definition"`
	Repository Repository            `json:"repository"`
	Digests    map[string]string     `json:"digests"`
	Values     map[string]any        `json:"values,omitempty"`
	Hooks      []string              `json:"hooks,omitempty"`
}

Application is the state of one application package.

type ApplicationDefinition

type ApplicationDefinition struct {
	Name           string              `json:"name"`
	Version        string              `json:"version"`
	Stage          string              `json:"stage"`
	Requirements   PackageRequirements `json:"requirements"`
	Licensing      Licensing           `json:"licensing"`
	DisableOptions DisableOptions      `json:"disableOptions"`
}

ApplicationDefinition is the metadata an application declares.

type BindingSnapshot

type BindingSnapshot struct {
	Snapshot   []SnapshotObject   `json:"snapshot"`
	Operations SnapshotOperations `json:"operations"`
}

BindingSnapshot is what a Kubernetes binding of a hook currently holds.

type CachedObjectsInfo

type CachedObjectsInfo struct {
	Count    uint64 `json:"count"`
	Added    uint64 `json:"added"`
	Deleted  uint64 `json:"deleted"`
	Modified uint64 `json:"modified"`
	Cleaned  uint64 `json:"cleaned"`
}

CachedObjectsInfo is a set of informer cache counters.

type Client

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

Client calls the API through a transport.

func New

func New(transport Transport) *Client

New returns a client that sends its requests through transport.

func (*Client) Endpoints

func (c *Client) Endpoints(ctx context.Context) ([]Endpoint, error)

Endpoints lists the routes the TCP listener serves: GET /endpoints.

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string, query url.Values) ([]byte, error)

Get returns the body of any route.

func (*Client) Global

func (c *Client) Global(ctx context.Context) (*GlobalModule, error)

Global returns the global module, ErrGlobalNotLoaded before the runtime has initialized it: GET /api/v1/packages/global/dump.

func (*Client) Healthz

func (c *Client) Healthz(ctx context.Context) (string, error)

Healthz reports that the controller process is up: GET /healthz.

func (*Client) Metrics

func (c *Client) Metrics(ctx context.Context) ([]byte, error)

Metrics returns the Prometheus exposition of the controller: GET /metrics.

func (*Client) Package

func (c *Client) Package(ctx context.Context, name string) (*NamedPackage, error)

Package returns one package, ErrUnknownPackage when there is none with that name: GET /api/v1/packages/dump?name=.

func (*Client) Packages

func (c *Client) Packages(ctx context.Context) (*PackagesDump, error)

Packages returns every application and module: GET /api/v1/packages/dump.

func (*Client) Pprof

func (c *Client) Pprof(ctx context.Context, name string, query url.Values) ([]byte, error)

Pprof returns /debug/pprof/{name}: a named profile (heap, goroutine, allocs, block, mutex, threadcreate), profile or trace (both take seconds), cmdline or symbol. Query carries seconds, debug and the like as net/http/pprof reads them.

func (*Client) Queues

func (c *Client) Queues(ctx context.Context, pkg string) (*QueuesDump, error)

Queues returns the task queues: GET /api/v1/queues/dump. A non-empty pkg narrows the dump to the queues of that package; the controller treats an unknown package, which selects no queue, as every queue.

func (*Client) Readyz

func (c *Client) Readyz(ctx context.Context) (Readiness, error)

Readyz reports the readiness of the replica: GET /readyz, which answers 500 with the reason while the replica is not ready.

func (*Client) Render

func (c *Client) Render(ctx context.Context, name string) (string, error)

Render returns the Helm manifests rendered for a package as YAML: GET /api/v1/packages/render/{name}. A package without a chart is a 400, a render failure a 500, and so is an unknown package ("render failed: no package found").

func (*Client) Requirements

func (c *Client) Requirements(ctx context.Context) (RequirementsDump, error)

Requirements returns the values stored for the release requirement checks: GET /api/v1/requirements/dump.

func (*Client) Scheduler

func (c *Client) Scheduler(ctx context.Context) (*SchedulerDump, error)

Scheduler returns the scheduler state of every package: GET /api/v1/scheduler/dump.

func (*Client) SchedulerNode

func (c *Client) SchedulerNode(ctx context.Context, pkg string) (*SchedulerNode, error)

SchedulerNode returns the scheduler state of one package, ErrUnknownPackage for an unknown one: GET /api/v1/scheduler/dump?name=.

func (*Client) Snapshots

func (c *Client) Snapshots(ctx context.Context, name string) (Snapshots, error)

Snapshots returns the hook snapshots of a package; an unknown package is a 404: GET /api/v1/packages/snapshots/{name}.

type Condition

type Condition struct {
	Type ConditionType `json:"type"`
	// Status is "True", "False" or "Unknown".
	Status  string `json:"status"`
	Reason  string `json:"reason,omitempty"`
	Message string `json:"message,omitempty"`
}

Condition is one status condition of a package.

type ConditionType

type ConditionType string

ConditionType names a package status condition.

const (
	ConditionRequirementsMet        ConditionType = "RequirementsMet"
	ConditionReadyOnFilesystem      ConditionType = "ReadyOnFilesystem"
	ConditionLoaded                 ConditionType = "Loaded"
	ConditionHooksProcessed         ConditionType = "HooksProcessed"
	ConditionManifestsApplied       ConditionType = "ManifestsApplied"
	ConditionScaled                 ConditionType = "Scaled"
	ConditionConfigured             ConditionType = "Configured"
	ConditionPending                ConditionType = "Pending"
	ConditionCustomResourcesApplied ConditionType = "CustomResourcesApplied"
	ConditionWebhooksEnsured        ConditionType = "WebhooksEnsured"
	// ConditionMaintenanceMode has inverted polarity: True means the resources are
	// no longer reconciled.
	ConditionMaintenanceMode ConditionType = "MaintenanceMode"
)

type Decision

type Decision struct {
	Kind    DecisionKind `json:"kind"`
	Reason  string       `json:"reason,omitempty"`
	Message string       `json:"message,omitempty"`
}

Decision is a rule verdict with the reason to surface when the package ends up disabled.

type DecisionKind

type DecisionKind string

DecisionKind is a rule's opinion about running a package.

const (
	// DecisionUndefined has no opinion.
	DecisionUndefined DecisionKind = "Undefined"
	// DecisionEnable is a soft vote to run the package.
	DecisionEnable DecisionKind = "Enable"
	// DecisionDisable is a soft vote to stop the package.
	DecisionDisable DecisionKind = "Disable"
	// DecisionForbid is a hard veto no other rule overrides.
	DecisionForbid DecisionKind = "Forbid"
)

type Dependency

type Dependency struct {
	// Constraint is the semver constraint; empty when any version will do.
	Constraint string `json:"constraint"`
	// Optional skips the check while the dependency is absent.
	Optional bool `json:"optional"`
}

Dependency is a requirement on another package.

type DisableMessages

type DisableMessages struct {
	Ru string `json:"ru,omitempty"`
	En string `json:"en,omitempty"`
}

DisableMessages are the localized confirmation messages.

type DisableOptions

type DisableOptions struct {
	Confirmation bool            `json:"confirmation"`
	Messages     DisableMessages `json:"messages"`
}

DisableOptions configures how the package may be disabled.

type EditionLicense

type EditionLicense struct {
	Available        bool     `json:"available"`
	EnabledInBundles []string `json:"enabledInBundles"`
}

EditionLicense tells whether a package ships in an edition and which bundles enable it.

type Endpoint

type Endpoint struct {
	Method string
	Path   string
}

Endpoint is one line of GET /endpoints. The pprof subtree is listed as a single "GET /debug/pprof/*" line.

type GlobalModule

type GlobalModule struct {
	Status  PackageStatus  `json:"status"`
	Name    string         `json:"name"`
	Running bool           `json:"running"`
	Path    string         `json:"path"`
	Values  map[string]any `json:"values,omitempty"`
	Hooks   []string       `json:"hooks,omitempty"`
	// Dynamic is the enabled state of modules as global hooks and module config set it.
	Dynamic map[string]bool `json:"dynamic,omitempty"`
}

GlobalModule is the answer of GET /api/v1/packages/global/dump, null until the runtime has initialized the global module.

type Licensing

type Licensing struct {
	Editions map[string]EditionLicense `json:"editions"`
}

Licensing maps an edition to the license of the package in it.

type Module

type Module struct {
	Status  PackageStatus `json:"status"`
	Name    string        `json:"name"`
	Running bool          `json:"running"`
	// Embedded marks a module that ships inside the Deckhouse image.
	Embedded   bool              `json:"embedded"`
	Path       string            `json:"path"`
	Definition ModuleDefinition  `json:"definition"`
	Repository Repository        `json:"repository"`
	Digests    map[string]string `json:"digests"`
	Values     map[string]any    `json:"values,omitempty"`
	Hooks      []string          `json:"hooks,omitempty"`
}

Module is the state of one module package.

type ModuleDefinition

type ModuleDefinition struct {
	Name           string              `json:"name"`
	Version        string              `json:"version"`
	Stage          string              `json:"stage"`
	Critical       bool                `json:"critical,omitempty"`
	Weight         uint32              `json:"weight,omitempty"`
	ExclusiveGroup string              `json:"exclusiveGroup,omitempty"`
	Requirements   PackageRequirements `json:"requirements"`
	Licensing      Licensing           `json:"licensing"`
	DisableOptions DisableOptions      `json:"disableOptions"`
}

ModuleDefinition is the metadata a module declares.

type ModuleGroup

type ModuleGroup struct {
	Name    string            `json:"name"`
	Members map[string]string `json:"members"`
}

ModuleGroup is a named group of module constraints.

type ModulesRequirements

type ModulesRequirements struct {
	// Mandatory modules must be present.
	Mandatory map[string]string `json:"mandatory"`
	// Conditional modules may be absent but must satisfy the constraint when present.
	Conditional map[string]string `json:"conditional"`
	// AnyOf groups each need at least one present member.
	AnyOf []ModuleGroup `json:"anyOf,omitempty"`
	// NoneOf groups forbid their members.
	NoneOf []ModuleGroup `json:"noneOf,omitempty"`
}

ModulesRequirements groups module dependencies by how they gate the package. The map values are semver constraints, empty when any version is acceptable.

type NamedPackage

type NamedPackage struct {
	Application *Application
	Module      *Module
}

NamedPackage is the answer of GET /api/v1/packages/dump?name=: the application or, failing that, the module with that name. The controller answers null when there is neither.

func (*NamedPackage) UnmarshalJSON

func (p *NamedPackage) UnmarshalJSON(data []byte) error

UnmarshalJSON tells the two shapes apart by the namespace field, which only an application carries.

type NodeState

type NodeState string

NodeState is the lifecycle phase of a scheduler node: idle → scheduled → active.

const (
	// NodeStateIdle waits for eligibility and may be (re)scheduled.
	NodeStateIdle NodeState = "idle"
	// NodeStateScheduled passed all checks.
	NodeStateScheduled NodeState = "scheduled"
	// NodeStateActive finished processing; dependents may proceed.
	NodeStateActive NodeState = "active"
)

type Operation

type Operation struct {
	Group     string   `json:"Group"`
	Version   string   `json:"Version"`
	Kind      string   `json:"Kind"`
	Name      string   `json:"name"`
	Namespace string   `json:"namespace"`
	Type      string   `json:"type"`
	Iteration int      `json:"iteration"`
	ID        string   `json:"id"`
	Category  string   `json:"category"`
	Status    string   `json:"status"`
	DependsOn []string `json:"dependsOn"`
}

Operation is one step of a release plan (nelm's progrep.Operation). Group, Version and Kind come from an embedded GroupVersionKind without JSON tags, hence the capitalized keys; meta and release operations leave the object fields empty.

type PackageRequirements

type PackageRequirements struct {
	// Kubernetes and Deckhouse are semver constraints; empty when unset.
	Kubernetes string              `json:"kubernetes"`
	Deckhouse  string              `json:"deckhouse"`
	Modules    ModulesRequirements `json:"modules"`
}

PackageRequirements is what a package needs from the cluster and from other modules.

type PackageStatus

type PackageStatus struct {
	Version    string         `json:"version"`
	Conditions []Condition    `json:"conditions"`
	Tracking   Tracking       `json:"tracking"`
	Settings   map[string]any `json:"settings,omitempty"`
	// URLs are the application endpoints found in the rendered manifests.
	URLs []URL `json:"urls,omitempty"`
}

PackageStatus is the runtime status of a package.

type PackagesDump

type PackagesDump struct {
	// Apps is keyed by "<namespace>.<name>".
	Apps    map[string]Application `json:"apps"`
	Modules map[string]Module      `json:"modules"`
}

PackagesDump is the answer of GET /api/v1/packages/dump.

type ProgressReport

type ProgressReport struct {
	Operations []Operation `json:"operations"`
}

ProgressReport lists every operation of the release plans run so far, in order.

type ProxyTransport

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

ProxyTransport reaches the TCP listener through the pods/proxy subresource. The listener binds the pod IP rather than loopback, so a port-forward, which dials localhost inside the pod's network namespace, cannot reach it, while the API server's proxy dials the pod IP.

The request goes through the bare HTTP client of the REST config: rest.Request drops the body and status of a non-2xx answer it cannot decode, and the controller answers its errors in plain text.

func NewProxyTransport

func NewProxyTransport(config *rest.Config, kubeCl kubernetes.Interface, pod *corev1.Pod) (*ProxyTransport, error)

NewProxyTransport targets the "self" port of the controller container of pod.

func (*ProxyTransport) Get

func (t *ProxyTransport) Get(ctx context.Context, path string, query url.Values) (*Response, error)

Get sends the request through the API server. An answer of the controller is returned whatever its status; an error of the API server itself, such as a refused pods/proxy permission, comes back as an error.

type Queue

type Queue struct {
	Length int    `json:"length"`
	Tasks  []Task `json:"tasks,omitempty"`
}

Queue is a snapshot of one task queue.

type QueuesDump

type QueuesDump struct {
	// Queues maps a queue name to its snapshot. A package queue is named after the
	// package; its hook queues are "<package>/<queue>" and "<package>/<queue>/sync",
	// and a module also has "<package>/crd" and "<package>/webhooks".
	Queues map[string]Queue `json:"queues"`
}

QueuesDump is the answer of GET /api/v1/queues/dump, optionally narrowed to one package with ?name=.

type Readiness

type Readiness struct {
	Ready   bool
	Message string
}

Readiness is the answer of GET /readyz. A leader is ready once its startup converge is done; a standby replica is ready while the leader is.

type Repository

type Repository struct {
	Name         string `json:"name"`
	Repository   string `json:"repository"`
	DockerConfig string `json:"dockercfg"`
	Login        string `json:"login"`
	Password     string `json:"password"`
	Scheme       string `json:"scheme"`
	CA           string `json:"ca"`
}

Repository is the registry a package comes from. The dump carries the credentials as they are.

type RequirementsDump

type RequirementsDump map[string]any

RequirementsDump is the answer of GET /api/v1/requirements/dump: the values hooks store for the release requirement checks, keyed by requirement.

type Response

type Response struct {
	StatusCode int
	Body       []byte
}

Response is an answer of the API, whatever its status.

type SchedulerDump

type SchedulerDump struct {
	Nodes map[string]SchedulerNode `json:"nodes"`
}

SchedulerDump is the answer of GET /api/v1/scheduler/dump.

type SchedulerNode

type SchedulerNode struct {
	Version string `json:"version"`
	// Order is the scheduling priority of the package: lower runs first.
	Order uint `json:"order"`
	// EffectiveOrder is Order raised to the highest order among the dependencies.
	EffectiveOrder uint      `json:"effectiveOrder"`
	State          NodeState `json:"state"`
	ScheduleReason string    `json:"scheduleReason"`
	// Decision is what the scheduler's rules resolved to.
	Decision     Decision              `json:"decision"`
	Dependencies map[string]Dependency `json:"dependencies,omitempty"`
	// Subscriptions are the packages this one follows (modules follow "global"),
	// Subscribers the packages that follow this one.
	Subscriptions []string `json:"subscriptions,omitempty"`
	Subscribers   []string `json:"subscribers,omitempty"`
}

SchedulerNode is the scheduling state of one package. It is also the answer of GET /api/v1/scheduler/dump?name=, which is null for an unknown package.

type SnapshotObject

type SnapshotObject struct {
	Object       map[string]any `json:"object,omitempty"`
	FilterResult any            `json:"filterResult,omitempty"`
}

SnapshotObject is one object of a binding snapshot. Object is missing when the binding keeps only filter results in memory; FilterResult is missing when the binding has no jqFilter.

type SnapshotOperations

type SnapshotOperations struct {
	SinceStart         CachedObjectsInfo `json:"sinceStart"`
	SinceLastExecution CachedObjectsInfo `json:"sinceLastExecution"`
}

SnapshotOperations counts the informer cache operations of a binding.

type Snapshots

type Snapshots map[string]map[string]BindingSnapshot

Snapshots is the answer of GET /api/v1/packages/snapshots/{name}: a hook name to its Kubernetes bindings. A hook without Kubernetes bindings maps to null.

type StatusError

type StatusError struct {
	Path       string
	StatusCode int
	Body       string
}

StatusError is an answer of the API outside 2xx.

func (*StatusError) Error

func (e *StatusError) Error() string

func (*StatusError) Unwrap

func (e *StatusError) Unwrap() error

Unwrap returns the sentinel of the status class, nil for a status without one.

type Task

type Task struct {
	// Index is the 1-based position in the queue.
	Index int    `json:"index"`
	Name  string `json:"name"`
	// Enqueued is how long ago the task was queued, as a Go duration.
	Enqueued string `json:"enqueued"`
	// NextRetry is how long until the next attempt, as a Go duration; it is
	// negative once the attempt is due.
	NextRetry string `json:"next_retry"`
	// Error is the last failure of the task, nil while it has not failed.
	Error *string `json:"error,omitempty"`
}

Task is a task waiting in a queue.

type Tracking

type Tracking struct {
	Completed int            `json:"completed"`
	Remaining int            `json:"remaining"`
	Report    ProgressReport `json:"report"`
}

Tracking is the progress of the package's Helm release.

type Transport

type Transport interface {
	Get(ctx context.Context, path string, query url.Values) (*Response, error)
}

Transport sends a GET request for path with query to the API.

type URL

type URL struct {
	URL         string `json:"url"`
	Description string `json:"description,omitempty"`
}

URL is an application endpoint.

Jump to

Keyboard shortcuts

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