iclient

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Overview

Package iclient is a fork of github.com/lxc/incus/v7/client (Apache-2.0).

It exists because the upstream client races on state shared between the connection, its event listeners and the operations running on it, so a single InstanceServer cannot be used from several goroutines.

The configuration read path is forked from github.com/lxc/incus/v7/shared/cliconfig. Nothing is mutated after ReadConfig returns, so a *Config is safe to share.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrConfigRemoteNotFound is returned for a remote the configuration
	// does not name.
	ErrConfigRemoteNotFound = errors.New("remote not found")

	// ErrConnectionNoAddress is returned for a remote with nothing to dial.
	ErrConnectionNoAddress = errors.New("remote has no address")

	// ErrConnectionUnsupported is returned by a Connection asked for an
	// operation its remote cannot serve, e.g. an instance call on a
	// simplestreams remote.
	ErrConnectionUnsupported = errors.New("operation not supported by this connection")

	// ErrInstanceBusy is returned when another operation holds the instance's
	// lock. Wait it out with Connection.WaitInstanceBusy.
	ErrInstanceBusy = errors.New("instance is busy")
)

The package's sentinels, matched with errors.Is.

View Source
var ConfigDefaultRemotes = map[string]ConfigRemote{
	"images": ConfigImagesRemote,
	"local":  ConfigLocalRemote,
}

ConfigDefaultRemotes is the set used when there is no configuration file.

View Source
var ConfigImagesRemote = ConfigRemote{
	Addrs:    []string{"https://images.linuxcontainers.org"},
	Public:   true,
	Protocol: "simplestreams",
}

ConfigImagesRemote is the community image server.

View Source
var ConfigLocalRemote = ConfigRemote{
	Addrs:    []string{"unix://"},
	Static:   true,
	Public:   false,
	Protocol: "incus",
}

ConfigLocalRemote is the unix socket remote, which cannot be removed.

Functions

func LifecycleEvent

func LifecycleEvent(raw api.Event) (api.EventLifecycle, error)

LifecycleEvent decodes lifecycle metadata, backfilling Name and Project from Source: only instance events carry them as fields.

func WaitOperation

func WaitOperation(ctx context.Context, updates <-chan api.Operation) (api.Operation, error)

WaitOperation reads an operation to its end and returns the outcome. The last value is the result, so a failure comes back as an error here.

Never call it on a token operation, which waits to be used rather than finishing.

Types

type Config

type Config struct {
	DefaultRemote string                  `yaml:"default-remote"`
	Remotes       map[string]ConfigRemote `yaml:"remotes"`

	// ConfigDir is where the configuration was read from; the certificate
	// paths hang off it.
	ConfigDir string `yaml:"-"`

	// ProjectOverride beats a remote's own Project.
	ProjectOverride string `yaml:"-"`

	// UserAgent is sent with every request.
	UserAgent string `yaml:"-"`
}

Config is the parsed Incus CLI configuration.

func ConfigDefaultConfig

func ConfigDefaultConfig() *Config

ConfigDefaultConfig returns the configuration used when no file exists.

func ReadConfig

func ReadConfig(path string) (*Config, error)

ReadConfig reads the CLI configuration at path, falling back to the default location when path is empty and to the built-in defaults when no file exists.

func (*Config) Path

func (c *Config) Path(paths ...string) string

Path joins the configuration directory with the given elements.

func (*Config) RemoteInfos

func (c *Config) RemoteInfos(remote string) (*ConfigRemoteInfo, error)

RemoteInfos resolves a remote into what it takes to connect to it. An empty name means the default remote.

func (*Config) ServerCertPath

func (c *Config) ServerCertPath(remote string) string

ServerCertPath returns where the remote's pinned server certificate lives.

type ConfigRemote

type ConfigRemote struct {
	Addrs           []string         `yaml:"-"`
	LastWorkingAddr string           `yaml:"last_working_address,omitempty"`
	AuthType        string           `yaml:"auth_type,omitempty"`
	KeepAlive       int              `yaml:"keepalive,omitempty"`
	Project         string           `yaml:"project,omitempty"`
	Protocol        string           `yaml:"protocol,omitempty"`
	CredHelper      string           `yaml:"credentials_helper,omitempty"`
	Public          bool             `yaml:"public"`
	Global          bool             `yaml:"-"`
	Static          bool             `yaml:"-"`
	TLS             *ConfigRemoteTLS `yaml:"-"`
}

ConfigRemote holds the details for communicating with one Incus daemon.

func (*ConfigRemote) UnmarshalYAML

func (r *ConfigRemote) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML reads `addr` as a comma-separated list into Addrs.

type ConfigRemoteInfo

type ConfigRemoteInfo struct {
	Name string

	// Addrs starts at the remote's last known working address.
	Addrs    []string
	Protocol string
	AuthType string

	// Project is the remote's own, unless ProjectOverride is set.
	Project string

	Public    bool
	KeepAlive int
	UserAgent string

	// InsecureSkipVerify accepts any server certificate, for registering
	// against one whose certificate is not known yet.
	InsecureSkipVerify bool

	// TLS material, all empty for a unix-socket-only remote.
	ServerCert string
	ClientCert string
	ClientKey  string
	ClientCA   string
}

ConfigRemoteInfo is everything needed to dial one remote, read off disk once.

func (*ConfigRemoteInfo) Unix

func (i *ConfigRemoteInfo) Unix() bool

Unix reports whether every address is the local unix socket.

type ConfigRemoteTLS

type ConfigRemoteTLS struct {
	Certificate string `json:"certificate"`
	Key         string `json:"key"`
	CA          string `json:"ca"`
}

ConfigRemoteTLS holds inline TLS material for a remote.

type Connection

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

Connection talks the Incus REST API to one project of one daemon.

func NewConnection

func NewConnection(info *ConfigRemoteInfo) (*Connection, error)

NewConnection dials an Incus daemon, over its unix socket or over TLS.

func (*Connection) CancelOperation

func (c *Connection) CancelOperation(ctx context.Context, op api.Operation) error

CancelOperation asks the server to cancel an operation.

func (*Connection) ConsoleInstance

func (c *Connection) ConsoleInstance(ctx context.Context, name string, console api.InstanceConsolePost, args *InstanceConsoleArgs) (<-chan api.Operation, error)

ConsoleInstance attaches to an instance's console and copies it to args.Output until the context is done or the operation ends. Canceling the context detaches, which ends the operation server-side.

func (*Connection) CopyImage

func (c *Connection) CopyImage(ctx context.Context, source *Connection, fingerprint string, args *ImageCopyArgs) (<-chan api.Operation, error)

CopyImage copies an image from another incus connection into this one.

func (*Connection) CreateCertificate

func (c *Connection) CreateCertificate(ctx context.Context, certificate api.CertificatesPost) error

CreateCertificate adds a certificate to the trust store.

With certificate.TrustToken set this is the registration call, the one request a client makes before it is trusted.

func (*Connection) CreateCertificateToken

func (c *Connection) CreateCertificateToken(ctx context.Context, certificate api.CertificatesPost) (<-chan api.Operation, error)

CreateCertificateToken mints a trust token for someone else to register with.

This is a token operation: it never reaches a terminal state. Read the first value, whose Metadata carries the secret, and cancel the context.

func (*Connection) CreateImage

func (c *Connection) CreateImage(ctx context.Context, image api.ImagesPost, args *ImageCreateArgs) (<-chan api.Operation, error)

CreateImage adds an image, and is also how one is copied in: give image.Source a server, a protocol and an alias and incusd fetches it.

With args the tarballs are uploaded instead, and image carries only the aliases and properties to record.

func (*Connection) CreateImageSecret

func (c *Connection) CreateImageSecret(ctx context.Context, fingerprint string) (<-chan api.Operation, error)

CreateImageSecret mints a one-time token for fetching a non-public image.

This is a token operation: it never reaches a terminal state. Read the first value, whose Metadata carries the secret, and cancel the context.

func (*Connection) CreateInstance

func (c *Connection) CreateInstance(ctx context.Context, instance api.InstancesPost) (<-chan api.Operation, error)

CreateInstance creates an instance and follows the operation.

func (*Connection) CreateNetwork

func (c *Connection) CreateNetwork(ctx context.Context, network api.NetworksPost) error

CreateNetwork adds a managed network.

func (*Connection) CreateProfile

func (c *Connection) CreateProfile(ctx context.Context, profile api.ProfilesPost) error

CreateProfile adds a profile.

func (*Connection) CreateProject

func (c *Connection) CreateProject(ctx context.Context, project api.ProjectsPost) error

CreateProject adds a project.

func (*Connection) CreateStoragePoolVolume

func (c *Connection) CreateStoragePoolVolume(ctx context.Context, pool string, volume api.StorageVolumesPost) error

CreateStoragePoolVolume adds a volume to a pool.

func (*Connection) DeleteCertificate

func (c *Connection) DeleteCertificate(ctx context.Context, fingerprint string) error

DeleteCertificate removes a certificate from the trust store.

func (*Connection) DeleteImage

func (c *Connection) DeleteImage(ctx context.Context, fingerprint string) (<-chan api.Operation, error)

DeleteImage removes an image and follows the operation.

func (*Connection) DeleteInstance

func (c *Connection) DeleteInstance(ctx context.Context, name string) (<-chan api.Operation, error)

DeleteInstance removes an instance and follows the operation.

func (*Connection) DeleteNetwork

func (c *Connection) DeleteNetwork(ctx context.Context, name string) error

DeleteNetwork removes a managed network.

func (*Connection) DeleteProfile

func (c *Connection) DeleteProfile(ctx context.Context, name string) error

DeleteProfile removes a profile.

func (*Connection) DeleteProject

func (c *Connection) DeleteProject(ctx context.Context, name string, args *DeleteProjectArgs) error

DeleteProject removes a project, which Incus refuses while it holds anything unless args.Force says to take that with it.

func (*Connection) DeleteStoragePoolVolume

func (c *Connection) DeleteStoragePoolVolume(ctx context.Context, pool string, volType string, name string) error

DeleteStoragePoolVolume removes a volume from a pool.

func (*Connection) ExecInstance

func (c *Connection) ExecInstance(ctx context.Context, name string, exec api.InstanceExecPost, args *InstanceExecArgs) (<-chan api.Operation, error)

ExecInstance runs a command in an instance and streams its output.

The channel closes once the output has drained and the operation has finished, so ranging over it to the end is enough.

func (*Connection) GetCertificates

func (c *Connection) GetCertificates(ctx context.Context) ([]api.Certificate, error)

GetCertificates returns the server's trust store.

func (*Connection) GetConnectionInfo

func (c *Connection) GetConnectionInfo(ctx context.Context) (*ConnectionInfo, error)

GetConnectionInfo describes how this connection reaches the server.

func (*Connection) GetImage

func (c *Connection) GetImage(ctx context.Context, fingerprint string, args *GetImageArgs) (*api.Image, string, error)

GetImage returns one image and its ETag.

func (*Connection) GetImageAlias

func (c *Connection) GetImageAlias(ctx context.Context, name string, args *GetImageAliasArgs) (*api.ImageAliasesEntry, string, error)

GetImageAlias resolves an alias to the image behind it.

func (*Connection) GetInstance

func (c *Connection) GetInstance(ctx context.Context, name string, args *GetInstanceArgs) (*api.InstanceFull, string, error)

GetInstance returns one instance and its ETag. Without args.Full the state, snapshots and backups are zero.

func (*Connection) GetInstanceConsoleLog

func (c *Connection) GetInstanceConsoleLog(ctx context.Context, name string) (io.ReadCloser, error)

GetInstanceConsoleLog returns the console ring buffer Incus keeps for an instance, which is what `incus console --show-log` prints. The caller closes it.

func (*Connection) GetInstanceFileSFTP

func (c *Connection) GetInstanceFileSFTP(ctx context.Context, instanceName string) (*sftp.Client, error)

GetInstanceFileSFTP returns an SFTP connection to an instance's filesystem. The caller closes it; holding one open keeps the forkfile process alive.

func (*Connection) GetInstanceNames

func (c *Connection) GetInstanceNames(ctx context.Context, args *GetInstancesArgs) ([]string, error)

GetInstanceNames returns the names of the instances the arguments select. AllProjects is refused, a bare name not being unique across projects.

func (*Connection) GetInstanceState

func (c *Connection) GetInstanceState(ctx context.Context, name string) (*api.InstanceState, string, error)

GetInstanceState returns the runtime state of one instance.

func (*Connection) GetInstances

func (c *Connection) GetInstances(ctx context.Context, args *GetInstancesArgs) ([]api.InstanceFull, error)

GetInstances returns the instances the arguments select.

func (*Connection) GetNetwork

func (c *Connection) GetNetwork(ctx context.Context, name string) (*api.Network, string, error)

GetNetwork returns one network and its ETag.

func (*Connection) GetNetworkNames

func (c *Connection) GetNetworkNames(ctx context.Context) ([]string, error)

GetNetworkNames returns the names of every network.

func (*Connection) GetNetworks

func (c *Connection) GetNetworks(ctx context.Context) ([]api.Network, error)

GetNetworks returns every network, each one whole.

func (*Connection) GetOperations

func (c *Connection) GetOperations(ctx context.Context) ([]api.Operation, error)

GetOperations returns the operations running on the server.

func (*Connection) GetProfile

func (c *Connection) GetProfile(ctx context.Context, name string) (*api.Profile, string, error)

GetProfile returns one profile and its ETag.

func (*Connection) GetProject

func (c *Connection) GetProject(ctx context.Context, name string) (*api.Project, string, error)

GetProject returns one project and its ETag.

func (*Connection) GetProjects

func (c *Connection) GetProjects(ctx context.Context) ([]api.Project, error)

GetProjects returns every project the certificate may see.

func (*Connection) GetServer

func (c *Connection) GetServer(ctx context.Context) (*api.Server, string, error)

GetServer returns the server's own description and its ETag.

func (*Connection) GetStoragePoolNames

func (c *Connection) GetStoragePoolNames(ctx context.Context) ([]string, error)

GetStoragePoolNames returns the names of every storage pool.

func (*Connection) GetStoragePoolVolume

func (c *Connection) GetStoragePoolVolume(ctx context.Context, pool string, volType string, name string, args *GetStoragePoolVolumeArgs) (*api.StorageVolumeFull, string, error)

GetStoragePoolVolume returns one custom volume and its ETag. Without args.Full the snapshots and backups are zero.

func (*Connection) GetStoragePoolVolumeFileSFTP

func (c *Connection) GetStoragePoolVolumeFileSFTP(ctx context.Context, pool string, volType string, volName string) (*sftp.Client, error)

GetStoragePoolVolumeFileSFTP returns an SFTP connection to a custom volume. The caller closes it; holding one open keeps the volume mounted, and deleting the volume does not wait for that.

func (*Connection) HasExtension

func (c *Connection) HasExtension(ctx context.Context, extension string) (bool, error)

HasExtension reports whether the server carries an API extension. It asks every time: a memo would be the one piece of mutable state on the connection.

func (*Connection) ListenEvents

func (c *Connection) ListenEvents(ctx context.Context, types []string, allProjects bool) (<-chan api.Event, error)

ListenEvents opens an event socket of this connection's own and returns the events it carries. Closing ctx closes the channel.

With allProjects the connection's project is not sent at all, and the server answers with every project the certificate is allowed to see.

func (*Connection) ListenOperation

func (c *Connection) ListenOperation(ctx context.Context, op api.Operation) (<-chan api.Operation, error)

ListenOperation follows an operation this connection did not start. It cannot subscribe before the operation exists, so it reads the operation once after subscribing.

func (*Connection) PatchInstanceConfig

func (c *Connection) PatchInstanceConfig(ctx context.Context, name string, config map[string]string) error

PatchInstanceConfig merges keys into an instance's config, leaving the rest of the instance alone. No cluster target is sent; instance config is cluster-wide state.

func (*Connection) RawQuery

func (c *Connection) RawQuery(ctx context.Context, method string, path string, data any, queryETag string) (*api.Response, string, error)

RawQuery sends a request to a path the caller built in full: the path is used verbatim, with no /1.0 prefix and no project.

func (*Connection) RenameProject

func (c *Connection) RenameProject(ctx context.Context, name string, project api.ProjectPost) (<-chan api.Operation, error)

RenameProject renames a project and follows the operation.

func (*Connection) UpdateImage

func (c *Connection) UpdateImage(ctx context.Context, fingerprint string, image api.ImagePut, etag string) error

UpdateImage replaces an image's configuration.

func (*Connection) UpdateInstanceState

func (c *Connection) UpdateInstanceState(ctx context.Context, name string, state api.InstanceStatePut, etag string) (<-chan api.Operation, error)

UpdateInstanceState starts, stops or restarts an instance and follows the operation.

func (*Connection) UpdateNetwork

func (c *Connection) UpdateNetwork(ctx context.Context, name string, network api.NetworkPut, etag string) error

UpdateNetwork replaces a network's configuration.

func (*Connection) UpdateProfile

func (c *Connection) UpdateProfile(ctx context.Context, name string, profile api.ProfilePut, etag string) error

UpdateProfile replaces a profile's configuration.

func (*Connection) UpdateProject

func (c *Connection) UpdateProject(ctx context.Context, name string, project api.ProjectPut, etag string) error

UpdateProject replaces a project's configuration.

func (*Connection) WaitInstanceBusy

func (c *Connection) WaitInstanceBusy(ctx context.Context, name string) error

WaitInstanceBusy blocks until no queryable operation holds the instance's operation lock.

Incus takes that lock in the driver, inside the operation, so a write issued while it is held is accepted and then fails from the operation.

func (*Connection) WaitOperationID

func (c *Connection) WaitOperationID(ctx context.Context, id string) (*api.Operation, error)

WaitOperationID blocks until the operation ends and returns how it ended.

The server holds the request open, so unlike ListenOperation this costs one request rather than an event socket.

func (*Connection) WithMaxIdleConns

func (c *Connection) WithMaxIdleConns(conns int, perHost int) *Connection

WithMaxIdleConns returns a copy that keeps at most conns idle connections, perHost of them to any one host. The copy starts with a pool of its own, because resizing a live one under in-flight requests is a race.

func (*Connection) WithProject

func (c *Connection) WithProject(project string) *Connection

WithProject returns a copy scoped to another project, sharing the transport and therefore its connection pool and TLS session cache.

Nothing has to be handed back. A Connection is not a resource with a lifetime of its own: what it holds is a transport, and an abandoned one closes its idle sockets after incusIdleConnTimeout and is then collected. Callers drop connections; they do not close them.

type ConnectionInfo

type ConnectionInfo struct {
	// Addresses the server says it can be reached on, plus the one dialed.
	Addresses []string

	// Certificate is the server certificate pinned for this remote, if any.
	Certificate string

	Protocol string
	URL      string

	// SocketPath is empty for anything but a unix remote.
	SocketPath string

	Project string
	Target  string
}

ConnectionInfo describes how a Connection reaches its server.

type DeleteProjectArgs

type DeleteProjectArgs struct {
	// Force deletes the instances, volumes and images in the project too.
	// Without it Incus refuses to remove a project that holds anything.
	Force bool
}

DeleteProjectArgs widens a project delete. A nil one is the zero value.

type GetImageAliasArgs

type GetImageAliasArgs struct {
	// Type picks between the container and the virtual-machine image behind
	// one alias. Empty takes whichever the server returns first.
	Type string
}

GetImageAliasArgs narrows an alias read. A nil one is the zero value.

type GetImageArgs

type GetImageArgs struct {
	// Secret reads an image the server has not made public, using the token
	// from CreateImageSecret.
	Secret string
}

GetImageArgs narrows an image read. A nil one is the zero value.

type GetInstanceArgs

type GetInstanceArgs struct {
	// Full also fetches state, snapshots and backups. Without it those
	// fields of the returned InstanceFull are zero.
	Full bool
}

GetInstanceArgs narrows a single instance read. A nil one is the zero value.

type GetInstancesArgs

type GetInstancesArgs struct {
	// Type limits the listing to containers or to virtual machines.
	Type api.InstanceType

	// Full also fetches state, snapshots and backups.
	Full bool

	// AllProjects lists every project the certificate may see. Instance
	// names are not unique across projects, so GetInstanceNames refuses it.
	AllProjects bool

	// Filters are server-side selectors written as "key=value", e.g.
	// "status=Running". They need the api_filtering extension.
	Filters []string
}

GetInstancesArgs narrows a listing. A nil one, like the zero value, lists the connection's own project.

type GetStoragePoolVolumeArgs

type GetStoragePoolVolumeArgs struct {
	// Full also fetches snapshots and backups. Without it those fields of
	// the returned StorageVolumeFull are zero.
	Full bool
}

GetStoragePoolVolumeArgs narrows a volume read. A nil one is the zero value.

type ImageCopyArgs

type ImageCopyArgs struct {
	// Aliases to add to the copy.
	Aliases []api.ImageAlias

	// AutoUpdate has the server keep the copy in step with its source.
	AutoUpdate bool

	// Public makes the copy readable without a token.
	Public bool

	// Type is the image type to resolve to.
	Type string

	// Mode is the transfer direction: pull (the default), push or relay.
	Mode string

	// Profiles to apply on the target.
	Profiles []string
}

ImageCopyArgs narrows a copy between two connections.

type ImageCreateArgs

type ImageCreateArgs struct {
	MetaFile io.Reader
	MetaName string

	RootfsFile io.Reader
	RootfsName string

	// Type is the image type, container or virtual-machine.
	Type string
}

ImageCreateArgs uploads an image body directly, rather than having the server fetch it from somewhere.

A nil RootfsFile means MetaFile is a unified image carrying both.

type InstanceConsoleArgs

type InstanceConsoleArgs struct {
	// Output receives the console stream. Input is never forwarded: this
	// attaches to watch a console, not to drive one.
	Output io.Writer
}

InstanceConsoleArgs is where a console attach sends what it reads.

type InstanceExecArgs

type InstanceExecArgs struct {
	Stdout io.Writer
	Stderr io.Writer
}

InstanceExecArgs is where a non-interactive exec sends its output. A nil writer discards that stream.

The exit code is on the terminal operation, in Metadata["return"].

Jump to

Keyboard shortcuts

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