Documentation
¶
Overview ¶
Package instance runs instances as virtual machines and manages their lifecycle: it starts, stops, pauses and deletes them, puts them on standby, and snapshots and forks them.
Operations are synchronous, and one that fails undoes what it acquired. Every host resource an instance holds is named after its ID, so recovery after an unclean shutdown needs no journal. See recover.go.
Index ¶
- Constants
- func MetricDescriptions() []metric.Description
- type Capacity
- type Config
- type Exit
- type FrozenGuest
- type HeldResources
- type Images
- type Initrds
- type Instance
- type Kernels
- type LogOptions
- type LogSource
- type Manager
- func (m *Manager) CheckResources(r Resources) error
- func (m *Manager) Close()
- func (m *Manager) Collect(ch chan<- prometheus.Metric)
- func (m *Manager) Create(ctx context.Context, instance Spec, pull image.PullPolicy) error
- func (m *Manager) CreateSnapshot(ctx context.Context, nameOrID, name string) (_ Snapshot, err error)
- func (m *Manager) Delete(ctx context.Context, nameOrID string, force bool) (err error)
- func (m *Manager) DeleteSnapshot(ctx context.Context, nameOrID string) (err error)
- func (m *Manager) Describe(ch chan<- *prometheus.Desc)
- func (m *Manager) DialAgent(ctx context.Context, nameOrID string) (*agentclient.Client, error)
- func (m *Manager) ForkInstance(ctx context.Context, sourceNameOrID string, instance Spec) (err error)
- func (m *Manager) ForkSnapshot(ctx context.Context, nameOrID string, instance Spec) (err error)
- func (m *Manager) Health(nameOrID string) (health.Check, health.Health, bool)
- func (m *Manager) ImagesInUse() (image.InUse, error)
- func (m *Manager) Instance(nameOrID string) (Spec, error)
- func (m *Manager) Instances() []Spec
- func (m *Manager) LookupAddr(network string, addr netip.Addr) []string
- func (m *Manager) LookupHost(network, name string) []netip.Addr
- func (m *Manager) Pause(ctx context.Context, nameOrID string) error
- func (m *Manager) Recover(ctx context.Context)
- func (m *Manager) Rename(ctx context.Context, nameOrID, newName string) (Spec, error)
- func (m *Manager) Resize(ctx context.Context, nameOrID string, want Resources) (err error)
- func (m *Manager) RestoreSnapshot(ctx context.Context, nameOrID string) (_ Spec, err error)
- func (m *Manager) Resume(ctx context.Context, nameOrID string) error
- func (m *Manager) Snapshot(nameOrID string) (Snapshot, error)
- func (m *Manager) Snapshots() []Snapshot
- func (m *Manager) Standby(ctx context.Context, nameOrID string) error
- func (m *Manager) StandbyIdle(ctx context.Context)
- func (m *Manager) Start(ctx context.Context, nameOrID string) error
- func (m *Manager) StartOnBoot(ctx context.Context)
- func (m *Manager) Stats() []Stats
- func (m *Manager) Status(nameOrID string) (Status, error)
- func (m *Manager) Stop(ctx context.Context, nameOrID string) (err error)
- func (m *Manager) StreamLogs(ctx context.Context, nameOrID string, opts LogOptions, w io.Writer) error
- func (m *Manager) Update(ctx context.Context, updated Spec) error
- func (m *Manager) Usage() Usage
- func (m *Manager) Waiter(nameOrID string, opts WaitOptions) (*Waiter, error)
- func (m *Manager) WarnDeprecatedHypervisorVersions(ctx context.Context)
- type Mount
- type MountType
- type Networks
- type Recorder
- type Resources
- type RestartMode
- type RestartPolicy
- type Shares
- type Snapshot
- type SnapshotKind
- type Spec
- func (s Spec) EffectiveHypervisorType() hypervisor.Type
- func (s Spec) HasDirectoryMount() bool
- func (s Spec) MaxResources() Resources
- func (s Spec) PinnedImageRef() (string, error)
- func (s Spec) Resources() Resources
- func (s Spec) Validate() error
- func (s Spec) VolumeMount(name string) (Mount, bool)
- type State
- type Stats
- type Status
- type Store
- type Usage
- type Volumes
- type WaitCondition
- type WaitOptions
- type Waiter
Constants ¶
const MaxFileMountBytes = 1 << 20
MaxFileMountBytes is how much an instance's file mounts can hold between them. Their contents travel in requests and in the instance's definition, so anything larger belongs in a volume or the image.
const MaxVolumeMounts = 'z' - 'e' + 1
MaxVolumeMounts is how many volumes an instance can mount: /dev/vde to /dev/vdz.
const MinStandbyAfter = time.Minute
MinStandbyAfter is the shortest Spec.StandbyAfter. Idleness is judged a minute at a time.
Variables ¶
This section is empty.
Functions ¶
func MetricDescriptions ¶
func MetricDescriptions() []metric.Description
MetricDescriptions returns the descriptions of every metric the instance manager serves, for the reference.
Types ¶
type Capacity ¶
type Capacity struct {
// Host is what the host has: its logical CPUs and its memory.
Host Resources `json:"host"`
// ReservedMemoryBytes is withheld from instances altogether.
ReservedMemoryBytes int64 `json:"reserved_memory_bytes"`
// CPUOvercommit scales the host's CPUs into the vCPUs instances may be
// given: 4 lets four vCPUs share each CPU.
CPUOvercommit float64 `json:"cpu_overcommit"`
// MemoryOvercommit scales the host's memory, less ReservedMemoryBytes,
// into the memory instances may be given.
MemoryOvercommit float64 `json:"memory_overcommit"`
}
Capacity is how much of the host instances may be given.
func (Capacity) Allocatable ¶
Allocatable returns what instances may be given in total.
type Config ¶
type Config struct {
// Store keeps the definitions of instances and snapshots.
Store Store
// Networks defines the networks and attaches instances to them.
Networks Networks
// RunDir holds ephemeral runtime state. Empty is defaults.RunDir.
RunDir string
// Images provides the images instances boot from.
Images Images
// Kernels looks up the kernels instances boot.
Kernels Kernels
// Volumes looks up the volumes instances mount.
Volumes Volumes
// Initrds provides the initramfs guests boot from.
Initrds Initrds
// Starters launch VMMs, one for each hypervisor version the daemon
// carries, by type. The first of each type is its default version.
Starters map[hypervisor.Type][]hypervisor.Starter
// an instance that mounts one cannot start.
Shares Shares
// AllowedDirectories are the host directories instances may mount. An
// instance that mounts any other cannot start.
AllowedDirectories hostfs.AllowedDirectories
// Capacity limits the CPU and memory instances may be given. The zero
// value is unlimited.
Capacity Capacity
// Events records what happens to instances. Nil records nothing.
Events Recorder
// Logger is where the Manager logs. Nil is slog.Default().
Logger *slog.Logger
}
Config holds the dependencies for a Manager.
type Exit ¶
type Exit struct {
// Code is the exit code the guest reported, if it reported one. A clean
// end always has one.
Code *int
// Failure is why the end was not clean, or nil if it was.
Failure error
}
Exit is how an instance's guest ended. An end is clean only if the guest reported exit code 0; anything else is a failure.
type FrozenGuest ¶
type FrozenGuest struct {
// Instance is the definition of the instance the guest belonged to, as
// it was when the guest was frozen.
Instance Spec `yaml:"instance" json:"instance"`
// IP is the guest's address on its network, which it keeps.
IP string `yaml:"ip,omitempty" json:"ip,omitempty"`
// MAC is the hardware address of the guest's network interface.
MAC string `yaml:"mac,omitempty" json:"mac,omitempty"`
// HypervisorType is the hypervisor that froze the guest. Only it can
// resume the guest.
HypervisorType hypervisor.Type `yaml:"hypervisor_type,omitempty" json:"hypervisor_type,omitempty"`
// HypervisorVersion is the version of that hypervisor, which must match
// as well.
HypervisorVersion string `yaml:"hypervisor_version,omitempty" json:"hypervisor_version,omitempty"`
// VCPUs is how many vCPUs the guest ran with, which a resume is admitted
// on. It can differ from Instance's after a resize.
VCPUs int `yaml:"vcpus,omitempty" json:"vcpus,omitempty"`
// MemoryBytes is how much memory the guest ran with, as VCPUs is.
MemoryBytes int64 `yaml:"memory_bytes,omitempty" json:"memory_bytes,omitempty"`
// ImageDigest is the image the guest booted from, which a resume pulls
// if the host no longer has it.
ImageDigest string `yaml:"image_digest,omitempty" json:"image_digest,omitempty"`
}
FrozenGuest is what a guest frozen to disk ran with, which resuming it needs: a memory snapshot's guest, or an instance's on standby.
type HeldResources ¶
type HeldResources struct {
// Name is the instance's name.
Name string `json:"name"`
// State is the instance's state: starting, running or paused.
State State `json:"state"`
// Resources is what the instance holds.
Resources Resources `json:"resources"`
}
HeldResources is what one instance holds of the host.
type Images ¶
type Images interface {
Ensure(ctx context.Context, ref string, policy image.PullPolicy) (*image.Image, error)
}
Images provides the bootable disk for an image reference.
type Instance ¶
type Instance struct {
// Spec is the instance's definition.
Spec Spec `json:"spec"`
// Status is what was last observed of the instance.
Status Status `json:"status"`
}
Instance is a virtual machine. Spec is the desired state, persisted across reboots. Status is the observed state, kept in the runtime directory and empty after a reboot.
type Kernels ¶
type Kernels interface {
Kernel(nameOrID string) (kernel.Kernel, error)
Path(k kernel.Kernel) (string, error)
}
Kernels looks up kernels and finds their binaries on the host.
type LogOptions ¶
type LogOptions struct {
// Source is which log. Empty is the guest's console.
Source LogSource
// TailLines limits the output to the last lines. Zero means all of it.
TailLines int
// Follow keeps writing new output until the instance stops or the
// context is cancelled.
Follow bool
}
LogOptions says which of an instance's logs to read, and how much.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager drives instance lifecycle operations and owns the status that describes them.
func (*Manager) CheckResources ¶
CheckResources returns an invalid argument error unless an instance asking for r could ever start on this host. An instance may not have more vCPUs than the host has CPUs.
func (*Manager) Close ¶
func (m *Manager) Close()
Close stops watching VMMs and restarting instances, and waits for work under way. The VMMs keep running for the next daemon to adopt.
func (*Manager) Collect ¶
func (m *Manager) Collect(ch chan<- prometheus.Metric)
Collect implements prometheus.Collector: the counters the Manager keeps, then the instances' usage and each one's stats as they are now.
func (*Manager) Create ¶
Create records a new instance's definition, first pulling its image as pull says, and pins it to the digest its image reference resolves to. It refuses an invalid definition, a name already taken, and one that could never start, before pulling anything. It boots nothing: see Start. Nothing is recorded if the image cannot be had.
func (*Manager) CreateSnapshot ¶
func (m *Manager) CreateSnapshot(ctx context.Context, nameOrID, name string) (_ Snapshot, err error)
CreateSnapshot freezes an instance to disk as a snapshot called name, or, if name is empty, after the instance and the time. See writeSnapshot for what it holds.
func (*Manager) Delete ¶
Delete removes an instance and everything it owns: its VM, its network allocation and the devices on the host it is attached by, its status and its directory. Volumes and snapshots are kept. An active instance is refused unless force is set.
func (*Manager) DeleteSnapshot ¶
DeleteSnapshot removes a snapshot and its files.
func (*Manager) Describe ¶
func (m *Manager) Describe(ch chan<- *prometheus.Desc)
Describe implements prometheus.Collector.
func (*Manager) DialAgent ¶
DialAgent connects to a running instance's guest agent. If the guest is still booting, it waits up to agentReadyTimeout for the agent to answer. It returns an ErrUnavailable error if the agent does not answer in time, and an ErrInvalidState one if the instance is not running or stops. Close releases the client.
func (*Manager) ForkInstance ¶
func (m *Manager) ForkInstance(ctx context.Context, sourceNameOrID string, instance Spec) (err error)
ForkInstance creates instance as a copy of source. It is ForkSnapshot of a snapshot of source taken now, except that the snapshot is not kept. The caller defines instance from source. See writeSnapshot for the states source can be forked in.
func (*Manager) ForkSnapshot ¶
ForkSnapshot creates instance as a copy of the one snapshot was taken of, under an identity of its own: the caller defines it from snapshot.Instance with its own ID, name and address. From a memory snapshot the copy runs, resumed where the snapshot's guest was and then given that identity; from a disk snapshot it is stopped, to boot from the snapshot's disk. A fork that fails leaves no instance behind.
func (*Manager) Health ¶
Health returns an instance's check and its findings, or false if it is not being monitored.
func (*Manager) ImagesInUse ¶
ImagesInUse returns the images that must be kept, each with what uses it: those instances are defined to boot from, those active guests booted from, those guests on standby booted from, and those memory snapshots' guests booted from.
func (*Manager) LookupAddr ¶
LookupAddr returns the name of the instance on a network that holds addr, and its hostname if it is another, if the instance holds resources as LookupHost finds them.
func (*Manager) LookupHost ¶
LookupHost returns the addresses of the instances on a network whose name or hostname is name, compared without regard to case. Only instances that hold resources, starting, running or paused, are found: a stopped one's address answers nothing.
func (*Manager) Recover ¶
Recover reconciles recorded instance status with what is running on the host. It runs once at startup, before the API is served. For each instance:
- Running or Paused, VMM alive: adopt it.
- Running or Paused, VMM gone: handle it as an unexpected end.
- Starting or Stopping: kill the VMM, release resources, mark Failed.
- Restarting: schedule the restart again.
- Stopped, Failed or Standby: nothing.
func (*Manager) Rename ¶
Rename changes a Stopped or Failed instance's name and returns the renamed instance. Its persistent directory moves; everything keyed by ID stays.
func (*Manager) Resize ¶
Resize gives a running instance want's vCPUs and memory without restarting it, within its maximums, and records them in its definition so that it keeps them when it next starts. Growing needs room on the host (ErrResourceExhausted otherwise).
The larger of what the instance held and want is reserved first. A size the hypervisor refuses changes nothing. If the hypervisor or the guest fails a resize it took, the instance holds the larger of the two until it next starts, and then starts with want.
func (*Manager) RestoreSnapshot ¶
RestoreSnapshot puts the instance snapshot was taken from back as it was then, discarding whatever it has written to its disk since, and returns the instance. The instance must be stopped: one on standby is refused, since its frozen guest would be lost. A memory snapshot resumes its guest where it was; a disk snapshot leaves it stopped, to boot from the disk at its next start.
func (*Manager) Snapshot ¶
Snapshot returns a snapshot by name or ID, or an errdefs.ErrNotFound error if there is none.
func (*Manager) Standby ¶
Standby freezes a running or paused instance to disk and ends its VMM, so that it holds no CPU or memory. Start resumes it where it was; Stop discards what was frozen. Its disk stays where it is, and its network allocation, host ports and writable volumes stay its own.
func (*Manager) StandbyIdle ¶
StandbyIdle puts on standby each running instance that has been idle for its StandbyAfter, sampling them every idleSampleInterval until ctx is done.
func (*Manager) Start ¶
Start boots a defined instance, or resumes one on standby where it was. It cancels any pending restart, resets the restart count and clears StoppedByUser. It returns once the guest's agent answers, or once its workload has ended, however it ended. If the guest does not boot, it returns an ErrInvalidState error that says why, quoting the console. If the manager closes before the guest boots, it returns an ErrUnavailable error.
func (*Manager) StartOnBoot ¶
StartOnBoot starts every Stopped or Failed instance whose restart policy starts it on boot. It runs after Recover.
func (*Manager) Stats ¶
Stats returns what the VMM of each running or paused instance uses of the host now, in name order. An instance whose VMM cannot be read is left out.
func (*Manager) Status ¶
Status returns an instance's status, with its address. An instance with no status file is Stopped.
func (*Manager) Stop ¶
Stop shuts down an instance and releases its host resources, keeping its definition, disk and network allocation. An instance on standby is stopped by discarding what it has frozen, so that it boots afresh. It cancels any pending restart and sets StoppedByUser. Stopping a stopped instance is not an error.
func (*Manager) StreamLogs ¶
func (m *Manager) StreamLogs(ctx context.Context, nameOrID string, opts LogOptions, w io.Writer) error
StreamLogs writes an instance's log to w. With opts.Follow it keeps writing until the instance stops or ctx is done.
func (*Manager) Update ¶
Update replaces the definition of a Stopped or Failed instance. A change to its restart policy or standby_after alone is accepted in any state. Changing the network or static IP releases the instance's network allocation. A larger disk_bytes grows the overlay disk at the next start; a smaller one than the overlay disk is refused.
func (*Manager) Usage ¶
Usage returns what the instances on this host hold now. An instance whose status cannot be read counts as Failed.
func (*Manager) Waiter ¶
func (m *Manager) Waiter(nameOrID string, opts WaitOptions) (*Waiter, error)
Waiter returns a waiter for an instance, which the caller must Close. An instance that does not exist, or no longer has opts.ID, is an errdefs.ErrNotFound error.
func (*Manager) WarnDeprecatedHypervisorVersions ¶
WarnDeprecatedHypervisorVersions logs a warning for everything that still uses a deprecated hypervisor version: an instance that names one, a guest running or frozen on one, and a memory snapshot taken with one. Each must move off the version before a release of Dicer removes it. The daemon calls this once, after Recover.
type Mount ¶
type Mount struct {
// Type is what the mount attaches.
Type MountType `yaml:"type" json:"type"`
// Source is the volume's name for a volume, and the host directory's
// absolute path for a directory. A file and a tmpfs have none.
Source string `yaml:"source,omitempty" json:"source,omitempty"`
// Target is the absolute path the mount appears at in the guest.
Target string `yaml:"target" json:"target"`
// ReadOnly stops the guest writing to the mount. A volume that every
// instance attaching it mounts read-only can be shared between them.
ReadOnly bool `yaml:"read_only,omitempty" json:"read_only,omitempty"`
// Content is a file's contents. Only a file has them.
Content []byte `yaml:"content,omitempty" json:"content,omitempty"`
// Mode is a file's permission bits in the guest, where root owns it.
// Zero is 0644.
Mode uint32 `yaml:"mode,omitempty" json:"mode,omitempty"`
}
Mount attaches a volume, a file, a host directory or a tmpfs at Target in the guest.
func (Mount) Equal ¶
Equal reports whether m and other attach the same thing at the same place, a file with the same contents.
type MountType ¶
type MountType string
MountType is what a Mount attaches.
const ( // MountTypeVolume attaches a named volume: persistent storage that outlives // the instance, as a disk of its own. MountTypeVolume MountType = "volume" // MountTypeFile puts a file into the guest, with the contents the client // gave. It is written afresh at each start, so whatever the guest writes // to its copy is lost at its next start. MountTypeFile MountType = "file" // MountTypeTmpfs is an empty in-memory filesystem, lost when the guest stops. MountTypeTmpfs MountType = "tmpfs" // MountTypeDirectory shares a host directory with the guest while it // runs, over virtio-fs: what either side changes, the other sees. Only // Cloud Hypervisor has virtio-fs. MountTypeDirectory MountType = "directory" )
type Networks ¶
type Networks interface {
Network(nameOrID string) (network.Network, error)
Networks() []network.Network
AttachInstance(
ctx context.Context, n network.Network, instanceID string, opts network.AttachOptions,
) (network.Attachment, error)
ConnectInstance(ctx context.Context, n network.Network, instanceID string) error
DetachInstance(ctx context.Context, n network.Network, instanceID string)
Allocation(networkName, instanceID string) (network.Allocation, error)
InstanceAt(networkName, ip string) (instanceID string, ok bool)
Release(networkName, instanceID string) error
Reconcile(networks []string, live map[string]struct{}) (int, error)
}
Networks defines the networks, attaches instances to them, and keeps their addresses.
type Resources ¶
type Resources struct {
// VCPUs is a number of vCPUs.
VCPUs int `json:"vcpus"`
// MemoryBytes is an amount of guest memory.
MemoryBytes int64 `json:"memory_bytes"`
}
Resources is an amount of the host's CPU and memory.
type RestartMode ¶
type RestartMode string
RestartMode is when an instance is started again without being asked.
const ( // RestartModeNo leaves an instance that ended as it is. RestartModeNo RestartMode = "no" // RestartModeOnFailure restarts an instance whose end was not clean. RestartModeOnFailure RestartMode = "on-failure" // RestartModeUnlessStopped restarts an instance however it ended, and // starts it when the daemon starts, unless it was last stopped by a // user. RestartModeUnlessStopped RestartMode = "unless-stopped" // RestartModeAlways restarts an instance however it ended, and starts it // when the daemon starts, even if it was last stopped by a user. RestartModeAlways RestartMode = "always" )
The restart modes, as Docker names them.
type RestartPolicy ¶
type RestartPolicy struct {
// Mode is when the instance is restarted. Empty is RestartModeNo.
Mode RestartMode `yaml:"mode,omitempty" json:"mode,omitempty"`
// MaxRetries is how many times in a row an on-failure instance is
// restarted before it is left Failed. Zero means no limit.
MaxRetries int `yaml:"max_retries,omitempty" json:"max_retries,omitempty"`
}
RestartPolicy is what the daemon does when an instance ends without being asked to. Restarts use exponential backoff.
func (RestartPolicy) Restarts ¶
func (p RestartPolicy) Restarts() bool
Restarts reports whether the policy ever starts an instance again.
func (RestartPolicy) StartsOnBoot ¶
func (p RestartPolicy) StartsOnBoot(stoppedByUser bool) bool
StartsOnBoot reports whether an instance with this policy is started when the daemon starts.
func (RestartPolicy) String ¶
func (p RestartPolicy) String() string
String is the policy as the CLI and API take it: "on-failure:5".
func (RestartPolicy) Validate ¶
func (p RestartPolicy) Validate() error
Validate returns an invalid argument error if the daemon cannot follow the policy.
type Shares ¶
type Shares interface {
}
Shares shares host directories with guests: it starts virtiofsd for a share, on a socket the VMM connects to. The process ends when the VMM does.
type Snapshot ¶
type Snapshot struct {
// ID identifies the snapshot for as long as it exists.
ID string `yaml:"id" json:"id"`
// Name is what people call the snapshot. No two on a host share one.
Name string `yaml:"name" json:"name"`
// Kind says whether the snapshot holds a guest, or a disk alone.
Kind SnapshotKind `yaml:"kind" json:"kind"`
// FrozenGuest is what the snapshot's guest ran with. A disk snapshot
// has its Instance alone.
FrozenGuest `yaml:",inline"`
// CreatedAt is when the snapshot was taken.
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
// SizeBytes is the space the snapshot occupies, measured when read.
SizeBytes int64 `yaml:"-" json:"-"`
}
Snapshot is an instance frozen to disk. It is a resource of its own: it outlives the instance it was taken from, which may since have been renamed, changed or deleted. It never holds the instance's volumes.
type SnapshotKind ¶
type SnapshotKind string
SnapshotKind is what a Snapshot holds.
const ( // SnapshotKindMemory is a running or paused guest frozen to disk: its // memory and device state, with its overlay disk as it was at the same // moment. Restoring it resumes the guest where it was. SnapshotKindMemory SnapshotKind = "memory" // SnapshotKindDisk is a stopped instance's overlay disk alone. Restoring // it rolls the disk back, and the guest boots from it afresh. SnapshotKindDisk SnapshotKind = "disk" )
type Spec ¶
type Spec struct {
// ID identifies the instance for as long as it is defined. What the
// host holds for the instance is named after it.
ID string `yaml:"id" json:"id"`
// Name is what people call the instance. No two instances on a host
// share one.
Name string `yaml:"name" json:"name"`
// Hostname is the guest's hostname. Empty is the instance's name.
Hostname string `yaml:"hostname,omitempty" json:"hostname,omitempty"`
// ImageRef is the image the instance was created from, as it was
// given.
ImageRef string `yaml:"image_ref" json:"image_ref"`
// ImageDigest is the digest ImageRef resolved to when the instance was
// created. The instance always boots that image: pulling ImageRef again
// does not change it.
ImageDigest string `yaml:"image_digest" json:"image_digest"`
// HypervisorType is the hypervisor the instance runs on. Empty is
// hypervisor.DefaultType.
HypervisorType hypervisor.Type `yaml:"hypervisor_type,omitempty" json:"hypervisor_type,omitempty"`
// HypervisorVersion is the version of that hypervisor. Empty is the
// daemon's default version of it.
HypervisorVersion string `yaml:"hypervisor_version,omitempty" json:"hypervisor_version,omitempty"`
// KernelName is the kernel the guest boots.
KernelName string `yaml:"kernel_name" json:"kernel_name"`
// KernelArgs is the kernel's command line. Empty is the hypervisor's
// default.
KernelArgs string `yaml:"kernel_args,omitempty" json:"kernel_args,omitempty"`
// VCPUs is how many vCPUs the guest boots with.
VCPUs int `yaml:"vcpus" json:"vcpus"`
// MemoryBytes is how much memory the guest boots with.
MemoryBytes int64 `yaml:"memory_bytes" json:"memory_bytes"`
// DiskBytes is the size of the overlay disk the guest writes to.
DiskBytes int64 `yaml:"disk_bytes" json:"disk_bytes"`
// NetworkName is the network the instance is attached to.
NetworkName string `yaml:"network_name" json:"network_name"`
// StaticIP is the address the instance takes on its network. Empty
// takes a free one.
StaticIP string `yaml:"static_ip,omitempty" json:"static_ip,omitempty"`
// MaxVCPUs is the most vCPUs the instance can be resized to while it
// runs: it boots with room for them. Zero leaves no room.
MaxVCPUs int `yaml:"max_vcpus,omitempty" json:"max_vcpus,omitempty"`
// MaxMemoryBytes is the most memory the instance can be resized to
// while it runs, as MaxVCPUs is for vCPUs.
MaxMemoryBytes int64 `yaml:"max_memory_bytes,omitempty" json:"max_memory_bytes,omitempty"`
// DiskBytesPerSecond limits the bytes per second each of the instance's
// disks is read and written at. Zero is unlimited.
DiskBytesPerSecond int64 `yaml:"disk_bytes_per_second,omitempty" json:"disk_bytes_per_second,omitempty"`
// DiskIOPS limits the operations per second each of the instance's
// disks is read and written at. Zero is unlimited.
DiskIOPS int64 `yaml:"disk_iops,omitempty" json:"disk_iops,omitempty"`
// UploadBytesPerSecond limits the bytes per second the guest sends.
// Zero is unlimited.
UploadBytesPerSecond int64 `yaml:"upload_bytes_per_second,omitempty" json:"upload_bytes_per_second,omitempty"`
// DownloadBytesPerSecond limits the bytes per second the guest
// receives. Zero is unlimited.
DownloadBytesPerSecond int64 `yaml:"download_bytes_per_second,omitempty" json:"download_bytes_per_second,omitempty"`
// StandbyAfter is how long the instance may be idle, running but doing
// next to nothing, before it is put on standby. Zero is never.
StandbyAfter time.Duration `yaml:"standby_after,omitempty" json:"standby_after,omitempty"`
// Ports are the guest's ports published on the host.
Ports []network.PortMapping `yaml:"ports,omitempty" json:"ports,omitempty"`
// Mounts are what the guest mounts: volumes, files, host directories
// and tmpfs.
Mounts []Mount `yaml:"mounts,omitempty" json:"mounts,omitempty"`
// Env is the workload's environment, over the image's.
Env map[string]string `yaml:"env,omitempty" json:"env,omitempty"`
// Cmd is the command the workload runs, in place of the image's
// entrypoint and command. Empty is the image's.
Cmd []string `yaml:"cmd,omitempty" json:"cmd,omitempty"`
// InitMode is how the guest starts the command: auto, exec or systemd.
// Empty is auto: systemd if the command is systemd, else exec.
InitMode guest.InitMode `yaml:"init_mode,omitempty" json:"init_mode,omitempty"`
// User is who the workload runs as in the exec init mode: user, uid,
// user:group or uid:gid, looked up in the guest's /etc/passwd and
// /etc/group. Empty is the image's USER, or root if it has none.
User string `yaml:"user,omitempty" json:"user,omitempty"`
// Labels are for people and tools to find the instance by. Dicer does
// not read them.
Labels map[string]string `yaml:"labels,omitempty" json:"labels,omitempty"`
// Restart says what happens when the instance ends without being asked
// to.
Restart RestartPolicy `yaml:"restart,omitempty" json:"restart,omitzero"`
// HealthCheck is how the instance's health is checked, overriding its
// image's; a Disabled one switches the image's off. Nil means the
// image's, if it declares one.
HealthCheck *health.Check `yaml:"healthcheck,omitempty" json:"health_check,omitempty"`
// CreatedAt is when the instance was defined.
CreatedAt time.Time `yaml:"created_at" json:"created_at,omitzero"`
// UpdatedAt is when its definition last changed.
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at,omitzero"`
// RemoveOnExit deletes the instance once it stops, unless its restart
// policy will start it again.
RemoveOnExit bool `yaml:"remove_on_exit,omitempty" json:"remove_on_exit,omitempty"`
// StoppedByUser records that a user stopped the instance and has not
// started it since. An unless-stopped instance is not started at boot
// while it is set.
StoppedByUser bool `yaml:"stopped_by_user,omitempty" json:"stopped_by_user,omitempty"`
}
Spec is the persistent definition of a virtual machine. Referenced kernels, networks and mounts are resolved at each start.
func (Spec) EffectiveHypervisorType ¶
func (s Spec) EffectiveHypervisorType() hypervisor.Type
EffectiveHypervisorType returns the hypervisor the instance runs on, filling in the default for a spec that names none.
func (Spec) HasDirectoryMount ¶
HasDirectoryMount reports whether the instance shares a host directory, which only Cloud Hypervisor can, and which stops it being snapshotted.
func (Spec) MaxResources ¶
MaxResources returns the most the instance can hold: its maximums where set, otherwise what it asks for.
func (Spec) PinnedImageRef ¶
PinnedImageRef returns the reference the instance boots its image by: the repository ImageRef names, at ImageDigest.
type State ¶
type State string
State is the lifecycle state of an instance.
const ( // StateStopped means the instance is defined but not running. A freshly // created instance starts here. StateStopped State = "Stopped" // StateStarting means a start is in progress. An instance found in this // state at daemon boot crashed mid-start and is cleaned up. StateStarting State = "Starting" // StateRunning means the VM is executing. StateRunning State = "Running" // StatePaused means the vCPUs are halted but the VM is resident. StatePaused State = "Paused" // StateStandby means the guest is frozen to disk, its VMM ended: // it holds no CPU or memory, but keeps its network allocation, host // ports and writable volumes, and a start resumes it where it was. StateStandby State = "Standby" // StateStopping means a shutdown is in progress. StateStopping State = "Stopping" // StateRestarting means the instance ended without being asked to, and // its restart policy will start it again at // Status.NextRestartAt. It holds nothing in the meantime. StateRestarting State = "Restarting" // StateFailed means the last operation failed; see // Status.StateError. StateFailed State = "Failed" )
func States ¶
func States() []State
States returns every lifecycle state, in the order an instance normally moves through them.
func (State) CanTransitionTo ¶
CanTransitionTo reports whether a transition to target is allowed.
func (State) HoldsReservations ¶
HoldsReservations reports whether an instance in the state keeps its published host ports and writable volumes to itself: one that holds resources, is stopping, or is on standby, to resume with them.
func (State) HoldsResources ¶
HoldsResources reports whether an instance in the state holds the CPU and memory it was admitted with: starting, running or paused.
type Stats ¶
type Stats struct {
// InstanceID is the ID of the instance the stats are of.
InstanceID string `json:"instance_id"`
// Name is the instance's name when they were read.
Name string `json:"name"`
// StartedAt is when the VMM was started. Totals read with another
// StartedAt are of another VMM, and cannot be compared.
StartedAt time.Time `json:"started_at"`
// ReadAt is when the stats were read.
ReadAt time.Time `json:"read_at"`
// Held is the vCPUs and guest memory the instance holds.
Held Resources `json:"held"`
// CPUTime is the CPU time the VMM has used, user and system.
CPUTime time.Duration `json:"cpu_time"`
// ResidentMemoryBytes is the VMM's resident host memory: the guest
// memory backed so far and its own. Memory a guest frees stays resident.
ResidentMemoryBytes int64 `json:"resident_memory_bytes"`
// DiskReadBytes is what the VMM process read from storage: the guest's
// disks, and the VMM's own files, such as the console log and a
// snapshot's memory. Reads served from the page cache are not counted.
DiskReadBytes int64 `json:"disk_read_bytes"`
// DiskWrittenBytes is what the VMM process wrote to storage, counted as
// it writes, before the data reaches the disk.
DiskWrittenBytes int64 `json:"disk_written_bytes"`
// NetworkReceiveBytes is what the guest received on its network
// interface.
NetworkReceiveBytes int64 `json:"network_receive_bytes"`
// NetworkTransmitBytes is what the guest transmitted on it.
NetworkTransmitBytes int64 `json:"network_transmit_bytes"`
// NetworkReceivePackets is the packets the guest received.
NetworkReceivePackets int64 `json:"network_receive_packets"`
// NetworkTransmitPackets is the packets the guest transmitted.
NetworkTransmitPackets int64 `json:"network_transmit_packets"`
// NetworkReceiveDrops is the packets dropped on their way to the guest,
// which mostly means it does not take them as fast as they come.
NetworkReceiveDrops int64 `json:"network_receive_drops"`
// NetworkTransmitDrops is the packets dropped on their way from the
// guest.
NetworkTransmitDrops int64 `json:"network_transmit_drops"`
// NetworkReceiveErrors is the packets to the guest that failed with an
// error.
NetworkReceiveErrors int64 `json:"network_receive_errors"`
// NetworkTransmitErrors is the packets from the guest that failed with
// an error.
NetworkTransmitErrors int64 `json:"network_transmit_errors"`
}
Stats is what an instance's VMM process uses of the host, read from the host at one moment. Its vCPUs and the threads emulating its devices are counted together; totals are since the VMM started.
type Status ¶
type Status struct {
// InstanceID is the ID of the instance the status is of.
InstanceID string `json:"instance_id,omitempty"`
// State is where the instance is in its lifecycle.
State State `json:"state"`
// StateError is why the instance is Failed, or what ended it when it is
// Restarting.
StateError string `json:"state_error,omitempty"`
// VMMPID is the process ID of the instance's VMM, or nil without one.
VMMPID *int `json:"hypervisor_pid,omitempty"`
// HypervisorSocketPath is the VMM's control socket.
HypervisorSocketPath string `json:"hypervisor_socket_path,omitempty"`
// HypervisorVersion is the version of the hypervisor the guest runs on.
HypervisorVersion string `json:"hypervisor_version,omitempty"`
// VsockCID is the guest's vsock context ID.
VsockCID int64 `json:"vsock_cid,omitempty"`
// VsockPath is the VMM's socket for the guest's vsock device, which the
// guest agent is reached through.
VsockPath string `json:"vsock_path,omitempty"`
// VCPUs is how many vCPUs the instance was admitted with. The spec may
// have been edited since.
VCPUs int `json:"vcpus,omitempty"`
// MemoryBytes is how much memory the instance was admitted with, as
// VCPUs is.
MemoryBytes int64 `json:"memory_bytes,omitempty"`
// ImageDigest is the image the guest booted from.
ImageDigest string `json:"image_digest,omitempty"`
// IP is the instance's address on its network, held while it is
// defined. It is filled in by Status and not stored, and is empty while
// the instance holds no network allocation.
IP string `json:"-"`
// MAC is the hardware address of the guest's network interface, as IP
// is filled in.
MAC string `json:"-"`
// HealthCheck is the check this run was started with, or nil for none.
HealthCheck *health.Check `json:"health_check,omitempty"`
// Health is what that check has found, or nil if there is none.
Health *health.Health `json:"health,omitempty"`
// StartedAt is when the instance's VMM started, for an instance that
// has one.
StartedAt time.Time `json:"started_at,omitzero"`
// UpdatedAt is when the status was last written.
UpdatedAt time.Time `json:"updated_at,omitzero"`
// ExitCode is the exit code the guest reported when it last ended on
// its own, if it reported one.
ExitCode *int `json:"exit_code,omitempty"`
// FinishedAt is when the guest last ended without being asked to.
FinishedAt time.Time `json:"finished_at,omitzero"`
// RestartCount is how many times in a row the restart policy has
// started the instance again. A start a user asks for resets it.
RestartCount int `json:"restart_count,omitempty"`
// NextRestartAt is when a Restarting instance is due to start again.
NextRestartAt time.Time `json:"next_restart_at,omitzero"`
}
Status is the observed state of an instance. It lives under the runtime directory, so a host reboot discards it.
type Store ¶
type Store interface {
CreateInstance(instance Spec) error
Instance(nameOrID string) (Spec, error)
Instances() []Spec
MatchingInstances(match func(Spec) bool) []Spec
UpdateInstance(instance Spec) error
RenameInstance(nameOrID string, renamed Spec) error
DeleteInstance(nameOrID string) error
// InstanceDir is the persistent directory holding an instance's
// definition and overlay disk.
InstanceDir(name string) string
// StageSnapshot returns an empty directory to write a snapshot's files
// in, which CreateSnapshot moves into place.
StageSnapshot() (string, error)
CreateSnapshot(snapshot Snapshot, staged string) error
Snapshot(nameOrID string) (Snapshot, error)
Snapshots() []Snapshot
DeleteSnapshot(nameOrID string) error
// SnapshotDir is the directory holding a snapshot's files.
SnapshotDir(name string) string
}
Store keeps the definitions of instances and snapshots.
type Usage ¶
type Usage struct {
// ByState counts instances per state, and names every state even when
// no instance is in it.
ByState map[State]int `json:"by_state"`
// ByHealth counts checked instances per health status, and names every
// status even when no instance has it.
ByHealth map[health.Status]int `json:"by_health"`
// Capacity is what instances may be given, and how that was arrived at.
Capacity Capacity `json:"capacity"`
// Held is what the instances listed in Instances hold between them.
Held Resources `json:"held"`
// Instances are the instances holding resources, in name order.
Instances []HeldResources `json:"instances"`
}
Usage is what the instances on a host hold of it. It is computed on demand from instance status.
type Volumes ¶
type Volumes interface {
Volume(nameOrID string) (volume.Volume, error)
Path(v volume.Volume) string
}
Volumes looks up volumes and locates the disks backing them.
type WaitCondition ¶
type WaitCondition int
WaitCondition is what a Waiter waits for an instance to do.
const ( // WaitConditionStopped waits for the instance to stop. WaitConditionStopped WaitCondition = iota // WaitConditionHealthy waits for the running instance's health check to // pass. WaitConditionHealthy )
The wait conditions.
type WaitOptions ¶
type WaitOptions struct {
// ID, if set, is the instance to wait for, which tells it apart from a
// later one given the same name.
ID string
// Condition is what to wait for. The zero value waits for a stop.
Condition WaitCondition
// NextStop waits for the instance's next stop, even if it is stopped
// now: for a caller about to start it.
NextStop bool
}
WaitOptions say what a Waiter waits for.
type Waiter ¶
type Waiter struct {
// contains filtered or unexported fields
}
Waiter waits for an instance to stop, or to be healthy. It hears every stop and every passing health check from the moment it is made, so one made before the instance is started cannot miss how it ends, even if the instance is deleted as it stops.
func (*Waiter) Close ¶
func (w *Waiter) Close()
Close stops the waiter hearing the instance's stops and health.
Source Files
¶
- admission.go
- agent.go
- boot_watch.go
- create.go
- delete.go
- deprecated_hypervisor_version.go
- dns.go
- doc.go
- events.go
- exit.go
- fork.go
- frozen_guest.go
- guest_config.go
- health.go
- hypervisor.go
- idle.go
- images.go
- logs.go
- manager.go
- metrics.go
- mount.go
- network.go
- overlay_disk.go
- paths.go
- pause.go
- recover.go
- rename.go
- resize.go
- resources.go
- restart.go
- snapshot.go
- spec.go
- standby.go
- start.go
- state.go
- stats.go
- status.go
- stop.go
- supervise.go
- update.go
- usage.go
- wait.go
- wake.go