qemu

package
v0.0.0-...-f0e9a35 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2021 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package qemu provides methods and types for launching and managing QEMU instances. Instances can be launched with the LaunchQemu function and managed thereafter via QMPStart and the QMP object that this function returns. To manage a qemu instance after it has been launched you need to pass the -qmp option during launch requesting the qemu instance to create a QMP unix domain manageent socket, e.g., -qmp unix:/tmp/qmp-socket,server,nowait. For more information see the example below.

Example
package main

import (
	"time"

	"context"

	"github.com/kata-containers/govmm/qemu"
)

func main() {
	params := make([]string, 0, 32)

	// Rootfs
	params = append(params, "-drive", "file=/tmp/image.qcow2,if=virtio,aio=threads,format=qcow2")
	// Network
	params = append(params, "-net", "nic,model=virtio", "-net", "user")
	// kvm
	params = append(params, "-enable-kvm", "-cpu", "host")
	// qmp socket
	params = append(params, "-daemonize", "-qmp", "unix:/tmp/qmp-socket,server=on,wait=off")
	// resources
	params = append(params, "-m", "370", "-smp", "cpus=2")

	// LaunchCustomQemu should return as soon as the instance has launched as we
	// are using the --daemonize flag.  It will set up a unix domain socket
	// called /tmp/qmp-socket that we can use to manage the instance.
	_, err := qemu.LaunchCustomQemu(context.Background(), "", params, nil, nil, nil)
	if err != nil {
		panic(err)
	}

	// This channel will be closed when the instance dies.
	disconnectedCh := make(chan struct{})

	// Set up our options.  We don't want any logging or to receive any events.
	cfg := qemu.QMPConfig{}

	// Start monitoring the qemu instance.  This functon will block until we have
	// connect to the QMP socket and received the welcome message.
	q, _, err := qemu.QMPStart(context.Background(), "/tmp/qmp-socket", cfg, disconnectedCh)
	if err != nil {
		panic(err)
	}

	// This has to be the first command executed in a QMP session.
	err = q.ExecuteQMPCapabilities(context.Background())
	if err != nil {
		panic(err)
	}

	// Let's try to shutdown the VM.  If it hasn't shutdown in 10 seconds we'll
	// send a quit message.
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	err = q.ExecuteSystemPowerdown(ctx)
	cancel()
	if err != nil {
		err = q.ExecuteQuit(context.Background())
		if err != nil {
			panic(err)
		}
	}

	q.Shutdown()

	// disconnectedCh is closed when the VM exits. This line blocks until this
	// event occurs.
	<-disconnectedCh
}
Output:

Index

Examples

Constants

View Source
const (
	// MinimalGuestCID is the smallest valid context ID for a guest.
	MinimalGuestCID uint64 = 3

	// MaxGuestCID is the largest valid context ID for a guest.
	MaxGuestCID uint64 = 1<<32 - 1
)
View Source
const (
	// MigrationFD is the migration incoming type based on open file descriptor.
	// Skip default 0 so that it must be set on purpose.
	MigrationFD = 1
	// MigrationExec is the migration incoming type based on commands.
	MigrationExec = 2
	// MigrationDefer is the defer incoming type
	MigrationDefer = 3
)
View Source
const (
	// MachineTypeMicrovm is the QEMU microvm machine type for amd64
	MachineTypeMicrovm string = "microvm"
)
View Source
const (
	// VSOCKGuestCID is the VSOCK guest CID parameter.
	VSOCKGuestCID = "guest-cid"
)

Variables

View Source
var BalloonDeviceTransport = map[VirtioTransport]string{
	TransportPCI:  "virtio-balloon-pci",
	TransportCCW:  "virtio-balloon-ccw",
	TransportMMIO: "virtio-balloon-device",
}

BalloonDeviceTransport is a map of the virtio-balloon device name that corresponds to each transport.

View Source
var RngDeviceTransport = map[VirtioTransport]string{
	TransportPCI:  "virtio-rng-pci",
	TransportCCW:  "virtio-rng-ccw",
	TransportMMIO: "virtio-rng-device",
}

RngDeviceTransport is a map of the virtio-rng device name that corresponds to each transport.

View Source
var SCSIControllerTransport = map[VirtioTransport]string{
	TransportPCI:  "virtio-scsi-pci",
	TransportCCW:  "virtio-scsi-ccw",
	TransportMMIO: "virtio-scsi-device",
}

SCSIControllerTransport is a map of the virtio-scsi device name that corresponds to each transport.

View Source
var VFIODeviceTransport = map[VirtioTransport]string{
	TransportPCI:  "vfio-pci",
	TransportCCW:  "vfio-ccw",
	TransportMMIO: "vfio-device",
}

VFIODeviceTransport is a map of the vfio device name that corresponds to each transport.

View Source
var VSOCKDeviceTransport = map[VirtioTransport]string{
	TransportPCI:  "vhost-vsock-pci",
	TransportCCW:  "vhost-vsock-ccw",
	TransportMMIO: "vhost-vsock-device",
}

VSOCKDeviceTransport is a map of the vhost-vsock device name that corresponds to each transport.

View Source
var VhostUserBlkTransport = map[VirtioTransport]string{
	TransportPCI:  "vhost-user-blk-pci",
	TransportCCW:  "vhost-user-blk-ccw",
	TransportMMIO: "vhost-user-blk-device",
}

VhostUserBlkTransport is a map of the vhost-user-blk device name that corresponds to each transport.

View Source
var VhostUserFSTransport = map[VirtioTransport]string{
	TransportPCI:  "vhost-user-fs-pci",
	TransportCCW:  "vhost-user-fs-ccw",
	TransportMMIO: "vhost-user-fs-device",
}

VhostUserFSTransport is a map of the vhost-user-fs device name that corresponds to each transport.

View Source
var VhostUserNetTransport = map[VirtioTransport]string{
	TransportPCI:  "virtio-net-pci",
	TransportCCW:  "virtio-net-ccw",
	TransportMMIO: "virtio-net-device",
}

VhostUserNetTransport is a map of the virtio-net device name that corresponds to each transport.

View Source
var VhostUserSCSITransport = map[VirtioTransport]string{
	TransportPCI:  "vhost-user-scsi-pci",
	TransportCCW:  "vhost-user-scsi-ccw",
	TransportMMIO: "vhost-user-scsi-device",
}

VhostUserSCSITransport is a map of the vhost-user-scsi device name that corresponds to each transport.

View Source
var Virtio9PTransport = map[VirtioTransport]string{
	TransportPCI:  "virtio-9p-pci",
	TransportCCW:  "virtio-9p-ccw",
	TransportMMIO: "virtio-9p-device",
}

Virtio9PTransport is a map of the virtio-9p device name that corresponds to each transport.

View Source
var VirtioBlockTransport = map[VirtioTransport]string{
	TransportPCI:  "virtio-blk-pci",
	TransportCCW:  "virtio-blk-ccw",
	TransportMMIO: "virtio-blk-device",
}

VirtioBlockTransport is a map of the virtio-blk device name that corresponds to each transport.

View Source
var VirtioNetTransport = map[VirtioTransport]string{
	TransportPCI:  "virtio-net-pci",
	TransportCCW:  "virtio-net-ccw",
	TransportMMIO: "virtio-net-device",
}

VirtioNetTransport is a map of the virtio-net device name that corresponds to each transport.

View Source
var VirtioSerialTransport = map[VirtioTransport]string{
	TransportPCI:  "virtio-serial-pci",
	TransportCCW:  "virtio-serial-ccw",
	TransportMMIO: "virtio-serial-device",
}

VirtioSerialTransport is a map of the virtio-serial device name that corresponds to each transport.

Functions

func CreateCloudInitISO

func CreateCloudInitISO(ctx context.Context, scratchDir, isoPath string,
	userData, metaData []byte, attr *syscall.SysProcAttr) error

CreateCloudInitISO creates a cloud-init ConfigDrive ISO image. This is useful for configuring newly booted VMs. Before it can create the ISO image it needs to create a file tree with the various files that will make up the image. This directory is created under scratchDir and is deleted when when the function returns, successfully or otherwise. ctx is a context that can be used to timeout or cancel the image creation. isoPath contains the desired path of the ISO image to be created. The userdata and metadata parameters are byte slices that contain the ConfigDrive userdata and metadata that will be stored with the ISO image. The attrs parameter can be used to control aspects of the newly created qemu process, such as the user and group under which it runs. It may be nil.

func LaunchCustomQemu

func LaunchCustomQemu(ctx context.Context, path string, params []string, fds []*os.File,
	attr *syscall.SysProcAttr, logger QMPLog) (string, error)

LaunchCustomQemu can be used to launch a new qemu instance.

The path parameter is used to pass the qemu executable path.

params is a slice of options to pass to qemu-system-x86_64 and fds is a list of open file descriptors that are to be passed to the spawned qemu process. The attrs parameter can be used to control aspects of the newly created qemu process, such as the user and group under which it runs. It may be nil.

This function writes its log output via logger parameter.

The function will block until the launched qemu process exits. "", nil will be returned if the launch succeeds. Otherwise a string containing the contents of stderr + a Go error object will be returned.

func LaunchQemu

func LaunchQemu(config Config, logger QMPLog) (string, error)

LaunchQemu can be used to launch a new qemu instance.

The Config parameter contains a set of qemu parameters and settings.

This function writes its log output via logger parameter.

The function will block until the launched qemu process exits. "", nil will be returned if the launch succeeds. Otherwise a string containing the contents of stderr + a Go error object will be returned.

func QMPStart

func QMPStart(ctx context.Context, socket string, cfg QMPConfig, disconnectedCh chan struct{}) (*QMP, *QMPVersion, error)

QMPStart connects to a unix domain socket maintained by a QMP instance. It waits to receive the QMP welcome message via the socket and spawns some go routines to manage the socket. The function returns a *QMP which can be used by callers to send commands to the QEMU instance or to close the socket and all the go routines that have been spawned to monitor it. A *QMPVersion is also returned. This structure contains the version and capabilities information returned by the QEMU instance in its welcome message.

socket contains the path to the domain socket. cfg contains some options that can be specified by the caller, namely where the qemu package should send logs and QMP events. disconnectedCh is a channel that must be supplied by the caller. It is closed when an error occurs openning or writing to or reading from the unix domain socket. This implies that the QEMU instance that opened the socket has closed.

If this function returns without error, callers should call QMP.Shutdown when they wish to stop monitoring the QMP instance. This is not strictly necessary if the QEMU instance exits and the disconnectedCh is closed, but doing so will not cause any problems.

Commands can be sent to the QEMU instance via the QMP.Execute methods. These commands are executed serially, even if the QMP.Execute methods are called from different go routines. The QMP.Execute methods will block until they have received a success or failure message from QMP, i.e., {"return": {}} or {"error":{}}, and in some cases certain events are received.

QEMU currently requires that the "qmp_capabilties" command is sent before any other command. Therefore you must call qmp.ExecuteQMPCapabilities() before you execute any other command.

Types

type BalloonDevice

type BalloonDevice struct {
	DeflateOnOOM  bool
	DisableModern bool
	ID            string

	// ROMFile specifies the ROM file being used for this device.
	ROMFile string

	// DevNo identifies the ccw devices for s390x architecture
	DevNo string

	// Transport is the virtio transport for this device.
	Transport VirtioTransport
}

BalloonDevice represents a memory balloon device.

func (BalloonDevice) QemuParams

func (b BalloonDevice) QemuParams(config *Config) []string

QemuParams returns the qemu parameters built out of the BalloonDevice.

func (BalloonDevice) Valid

func (b BalloonDevice) Valid() bool

Valid returns true if the balloonDevice structure is valid and complete.

type BlockDevice

type BlockDevice struct {
	Driver    DeviceDriver
	ID        string
	File      string
	Interface BlockDeviceInterface
	AIO       BlockDeviceAIO
	Format    BlockDeviceFormat
	SCSI      bool
	WCE       bool

	// DisableModern prevents qemu from relying on fast MMIO.
	DisableModern bool

	// ROMFile specifies the ROM file being used for this device.
	ROMFile string

	// DevNo identifies the ccw devices for s390x architecture
	DevNo string

	// ShareRW enables multiple qemu instances to share the File
	ShareRW bool

	// ReadOnly sets the block device in readonly mode
	ReadOnly bool

	// Transport is the virtio transport for this device.
	Transport VirtioTransport
}

BlockDevice represents a qemu block device.

func (BlockDevice) QemuParams

func (blkdev BlockDevice) QemuParams(config *Config) []string

QemuParams returns the qemu parameters built out of this block device.

func (BlockDevice) Valid

func (blkdev BlockDevice) Valid() bool

Valid returns true if the BlockDevice structure is valid and complete.

type BlockDeviceAIO

type BlockDeviceAIO string

BlockDeviceAIO defines the type of asynchronous I/O the block device should use.

const (
	// Threads is the pthread asynchronous I/O implementation.
	Threads BlockDeviceAIO = "threads"

	// Native is the pthread asynchronous I/O implementation.
	Native BlockDeviceAIO = "native"
)

type BlockDeviceFormat

type BlockDeviceFormat string

BlockDeviceFormat defines the image format used on a block device.

const (
	// QCOW2 is the Qemu Copy On Write v2 image format.
	QCOW2 BlockDeviceFormat = "qcow2"
)

type BlockDeviceInterface

type BlockDeviceInterface string

BlockDeviceInterface defines the type of interface the device is connected to.

const (
	// NoInterface for block devices with no interfaces.
	NoInterface BlockDeviceInterface = "none"

	// SCSI represents a SCSI block device interface.
	SCSI BlockDeviceInterface = "scsi"
)

type BridgeDevice

type BridgeDevice struct {
	// Type of the bridge
	Type BridgeType

	// Bus number where the bridge is plugged, typically pci.0 or pcie.0
	Bus string

	// ID is used to identify the bridge in qemu
	ID string

	// Chassis number
	Chassis int

	// SHPC is used to enable or disable the standard hot plug controller
	SHPC bool

	// PCI Slot
	Addr string

	// ROMFile specifies the ROM file being used for this device.
	ROMFile string
}

BridgeDevice represents a qemu bridge device like pci-bridge, pxb, etc.

func (BridgeDevice) QemuParams

func (bridgeDev BridgeDevice) QemuParams(config *Config) []string

QemuParams returns the qemu parameters built out of this bridge device.

func (BridgeDevice) Valid

func (bridgeDev BridgeDevice) Valid() bool

Valid returns true if the BridgeDevice structure is valid and complete.

type BridgeType

type BridgeType uint

BridgeType is the type of the bridge

const (
	// PCIBridge is a pci bridge
	PCIBridge BridgeType = iota

	// PCIEBridge is a pcie bridge
	PCIEBridge
)

type CPUInfo

type CPUInfo struct {
	CPU      int           `json:"CPU"`
	Current  bool          `json:"current"`
	Halted   bool          `json:"halted"`
	QomPath  string        `json:"qom_path"`
	Arch     string        `json:"arch"`
	Pc       int           `json:"pc"`
	ThreadID int           `json:"thread_id"`
	Props    CPUProperties `json:"props"`
}

CPUInfo represents information about each virtual CPU

type CPUInfoFast

type CPUInfoFast struct {
	CPUIndex int           `json:"cpu-index"`
	QomPath  string        `json:"qom-path"`
	Arch     string        `json:"arch"`
	ThreadID int           `json:"thread-id"`
	Target   string        `json:"target"`
	Props    CPUProperties `json:"props"`
}

CPUInfoFast represents information about each virtual CPU

type CPUProperties

type CPUProperties struct {
	Node   int `json:"node-id"`
	Socket int `json:"socket-id"`
	Die    int `json:"die-id"`
	Core   int `json:"core-id"`
	Thread int `json:"thread-id"`
}

CPUProperties contains the properties of a CPU instance

type CharDevice

type CharDevice struct {
	Backend CharDeviceBackend

	// Driver is the qemu device driver
	Driver DeviceDriver

	// Bus is the serial bus associated to this device.
	Bus string

	// DeviceID is the user defined device ID.
	DeviceID string

	ID   string
	Path string
	Name string

	// DisableModern prevents qemu from relying on fast MMIO.
	DisableModern bool

	// ROMFile specifies the ROM file being used for this device.
	ROMFile string

	// DevNo identifies the ccw devices for s390x architecture
	DevNo string

	// Transport is the virtio transport for this device.
	Transport VirtioTransport
}

CharDevice represents a qemu character device.

func (CharDevice) QemuParams

func (cdev CharDevice) QemuParams(config *Config) []string

QemuParams returns the qemu parameters built out of this character device.

func (CharDevice) Valid

func (cdev CharDevice) Valid() bool

Valid returns true if the CharDevice structure is valid and complete.

type CharDeviceBackend

type CharDeviceBackend string

CharDeviceBackend is the character device backend for qemu

const (
	// Pipe creates a 2 way connection to the guest.
	Pipe CharDeviceBackend = "pipe"

	// Socket creates a 2 way stream socket (TCP or Unix).
	Socket CharDeviceBackend = "socket"

	// CharConsole sends traffic from the guest to QEMU's standard output.
	CharConsole CharDeviceBackend = "console"

	// Serial sends traffic from the guest to a serial device on the host.
	Serial CharDeviceBackend = "serial"

	// TTY is an alias for Serial.
	TTY CharDeviceBackend = "tty"

	// PTY creates a new pseudo-terminal on the host and connect to it.
	PTY CharDeviceBackend = "pty"
)

type Config

type Config struct {
	// Path is the qemu binary path.
	Path string

	// Ctx is the context used when launching qemu.
	Ctx context.Context

	// Name is the qemu guest name
	Name string

	// UUID is the qemu process UUID.
	UUID string

	// CPUModel is the CPU model to be used by qemu.
	CPUModel string

	// Machine
	Machine Machine

	// QMPSockets is a slice of QMP socket description.
	QMPSockets []QMPSocket

	// Devices is a list of devices for qemu to create and drive.
	Devices []Device

	// RTC is the qemu Real Time Clock configuration
	RTC RTC

	// VGA is the qemu VGA mode.
	VGA string

	// Kernel is the guest kernel configuration.
	Kernel Kernel

	// Memory is the guest memory configuration.
	Memory Memory

	// SMP is the quest multi processors configuration.
	SMP SMP

	// GlobalParam is the -global parameter.
	GlobalParam string

	// Knobs is a set of qemu boolean settings.
	Knobs Knobs

	// Bios is the -bios parameter
	Bios string

	// PFlash specifies the parallel flash images (-pflash parameter)
	PFlash []string

	// Incoming controls migration source preparation
	Incoming Incoming

	// FwCfg is the -fw_cfg parameter
	FwCfg []FwCfg

	IOThreads []IOThread

	// PidFile is the -pidfile parameter
	PidFile string

	// LogFile is the -D parameter
	LogFile string
	// contains filtered or unexported fields
}

Config is the qemu configuration structure. It allows for passing custom settings and parameters to the qemu API.

type Device

type Device interface {
	Valid() bool
	QemuParams(config *Config) []string
}

Device is the qemu device interface.

type DeviceDriver

type DeviceDriver string

DeviceDriver is the device driver string.

const (
	// NVDIMM is the Non Volatile DIMM device driver.
	NVDIMM DeviceDriver = "nvdimm"

	// VirtioNet is the virtio networking device driver.
	VirtioNet DeviceDriver = "virtio-net"

	// VirtioNetPCI is the virt-io pci networking device driver.
	VirtioNetPCI DeviceDriver = "virtio-net-pci"

	// VirtioNetCCW is the virt-io ccw networking device driver.
	VirtioNetCCW DeviceDriver = "virtio-net-ccw"

	// VirtioBlock is the block device driver.
	VirtioBlock DeviceDriver = "virtio-blk"

	// Console is the console device driver.
	Console DeviceDriver = "virtconsole"

	// Virtio9P is the 9pfs device driver.
	Virtio9P DeviceDriver = "virtio-9p"

	// VirtioSerial is the serial device driver.
	VirtioSerial DeviceDriver = "virtio-serial"

	// VirtioSerialPort is the serial port device driver.
	VirtioSerialPort DeviceDriver = "virtserialport"

	// VirtioRng is the paravirtualized RNG device driver.
	VirtioRng DeviceDriver = "virtio-rng"

	// VirtioBalloon is the memory balloon device driver.
	VirtioBalloon DeviceDriver = "virtio-balloon"

	//VhostUserSCSI represents a SCSI vhostuser device type.
	VhostUserSCSI DeviceDriver = "vhost-user-scsi"

	//VhostUserNet represents a net vhostuser device type.
	VhostUserNet DeviceDriver = "virtio-net"

	//VhostUserBlk represents a block vhostuser device type.
	VhostUserBlk DeviceDriver = "vhost-user-blk"

	//VhostUserFS represents a virtio-fs vhostuser device type
	VhostUserFS DeviceDriver = "vhost-user-fs"

	// PCIBridgeDriver represents a PCI bridge device type.
	PCIBridgeDriver DeviceDriver = "pci-bridge"

	// PCIePCIBridgeDriver represents a PCIe to PCI bridge device type.
	PCIePCIBridgeDriver DeviceDriver = "pcie-pci-bridge"

	// VfioPCI is the vfio driver with PCI transport.
	VfioPCI DeviceDriver = "vfio-pci"

	// VfioCCW is the vfio driver with CCW transport.
	VfioCCW DeviceDriver = "vfio-ccw"

	// VfioAP is the vfio driver with AP transport.
	VfioAP DeviceDriver = "vfio-ap"

	// VHostVSockPCI is a generic Vsock vhost device with PCI transport.
	VHostVSockPCI DeviceDriver = "vhost-vsock-pci"

	// PCIeRootPort is a PCIe Root Port, the PCIe device should be hotplugged to this port.
	PCIeRootPort DeviceDriver = "pcie-root-port"

	// Loader is the Loader device driver.
	Loader DeviceDriver = "loader"
)

type FSDevice

type FSDevice struct {
	// Driver is the qemu device driver
	Driver DeviceDriver

	// FSDriver is the filesystem driver backend.
	FSDriver FSDriver

	// ID is the filesystem identifier.
	ID string

	// Path is the host root path for this filesystem.
	Path string

	// MountTag is the device filesystem mount point tag.
	MountTag string

	// SecurityModel is the security model for this filesystem device.
	SecurityModel SecurityModelType

	// DisableModern prevents qemu from relying on fast MMIO.
	DisableModern bool

	// ROMFile specifies the ROM file being used for this device.
	ROMFile string

	// DevNo identifies the ccw devices for s390x architecture
	DevNo string

	// Transport is the virtio transport for this device.
	Transport VirtioTransport

	// Multidev is the filesystem behaviour to deal
	// with multiple devices being shared with a 9p export
	Multidev Virtio9PMultidev
}

FSDevice represents a qemu filesystem configuration.

func (FSDevice) QemuParams

func (fsdev FSDevice) QemuParams(config *Config) []string

QemuParams returns the qemu parameters built out of this filesystem device.

func (FSDevice) Valid

func (fsdev FSDevice) Valid() bool

Valid returns true if the FSDevice structure is valid and complete.

type FSDriver

type FSDriver string

FSDriver represents a qemu filesystem driver.

const (
	// Local is the local qemu filesystem driver.
	Local FSDriver = "local"

	// Handle is the handle qemu filesystem driver.
	Handle FSDriver = "handle"

	// Proxy is the proxy qemu filesystem driver.
	Proxy FSDriver = "proxy"
)

type FwCfg

type FwCfg struct {
	Name string
	File string
	Str  string
}

FwCfg allows QEMU to pass entries to the guest File and Str are mutually exclusive

func (FwCfg) QemuParams

func (fwcfg FwCfg) QemuParams(config *Config) []string

QemuParams returns the qemu parameters built out of the FwCfg object

func (FwCfg) Valid

func (fwcfg FwCfg) Valid() bool

Valid returns true if the FwCfg structure is valid and complete.

type HotpluggableCPU

type HotpluggableCPU struct {
	Type       string        `json:"type"`
	VcpusCount int           `json:"vcpus-count"`
	Properties CPUProperties `json:"props"`
	QOMPath    string        `json:"qom-path"`
}

HotpluggableCPU represents a hotpluggable CPU

type IOThread

type IOThread struct {
	ID string
}

IOThread allows IO to be performed on a separate thread.

type Incoming

type Incoming struct {
	// Possible values are MigrationFD, MigrationExec
	MigrationType int
	// Only valid if MigrationType == MigrationFD
	FD *os.File
	// Only valid if MigrationType == MigrationExec
	Exec string
}

Incoming controls migration source preparation

type IommuDev

type IommuDev struct {
	Intremap    bool
	DeviceIotlb bool
	CachingMode bool
}

IommuDev represents a Intel IOMMU Device

func (IommuDev) QemuParams

func (dev IommuDev) QemuParams(_ *Config) []string

QemuParams returns the qemu parameters built out of the IommuDev.

func (IommuDev) Valid

func (dev IommuDev) Valid() bool

Valid returns true if the IommuDev is valid

type Kernel

type Kernel struct {
	// Path is the guest kernel path on the host filesystem.
	Path string

	// InitrdPath is the guest initrd path on the host filesystem.
	InitrdPath string

	// Params is the kernel parameters string.
	Params string
}

Kernel is the guest kernel configuration structure.

type Knobs

type Knobs struct {
	// NoUserConfig prevents qemu from loading user config files.
	NoUserConfig bool

	// NoDefaults prevents qemu from creating default devices.
	NoDefaults bool

	// NoGraphic completely disables graphic output.
	NoGraphic bool

	// Daemonize will turn the qemu process into a daemon
	Daemonize bool

	// Both HugePages and MemPrealloc require the Memory.Size of the VM
	// to be set, as they need to reserve the memory upfront in order
	// for the VM to boot without errors.
	//
	// HugePages always results in memory pre-allocation.
	// However the setup is different from normal pre-allocation.
	// Hence HugePages has precedence over MemPrealloc
	// HugePages will pre-allocate all the RAM from huge pages
	HugePages bool

	// MemPrealloc will allocate all the RAM upfront
	MemPrealloc bool

	// FileBackedMem requires Memory.Size and Memory.Path of the VM to
	// be set.
	FileBackedMem bool

	// MemShared will set the memory device as shared.
	MemShared bool

	// Mlock will control locking of memory
	// Only active when Realtime is set to true
	Mlock bool

	// Stopped will not start guest CPU at startup
	Stopped bool

	// Realtime will enable realtime QEMU
	Realtime bool

	// Exit instead of rebooting
	NoReboot bool

	// IOMMUPlatform will enable IOMMU for supported devices
	IOMMUPlatform bool
}

Knobs regroups a set of qemu boolean settings

type LoaderDevice

type LoaderDevice struct {
	File string
	ID   string
}

LoaderDevice represents a qemu loader device.

func (LoaderDevice) QemuParams

func (dev LoaderDevice) QemuParams(config *Config) []string

QemuParams returns the qemu parameters built out of this loader device.

func (LoaderDevice) Valid

func (dev LoaderDevice) Valid() bool

Valid returns true if there is a valid structure defined for LoaderDevice

type Machine

type Machine struct {
	// Type is the machine type to be used by qemu.
	Type string

	// Acceleration are the machine acceleration options to be used by qemu.
	Acceleration string

	// Options are options for the machine type
	// For example gic-version=host and usb=off
	Options string
}

Machine describes the machine type qemu will emulate.

type Memory

type Memory struct {
	// Size is the amount of memory made available to the guest.
	// It should be suffixed with M or G for sizes in megabytes or
	// gigabytes respectively.
	Size string

	// Slots is the amount of memory slots made available to the guest.
	Slots uint8

	// MaxMem is the maximum amount of memory that can be made available
	// to the guest through e.g. hot pluggable memory.
	MaxMem string

	// Path is the file path of the memory device. It points to a local
	// file path used by FileBackedMem.
	Path string
}

Memory is the guest memory configuration structure.

type MemoryDevices

type MemoryDevices struct {
	Data MemoryDevicesData `json:"data"`
	Type string            `json:"type"`
}

MemoryDevices represents memory devices of vm

type MemoryDevicesData

type MemoryDevicesData struct {
	Slot         int    `json:"slot"`
	Node         int    `json:"node"`
	Addr         uint64 `json:"addr"`
	Memdev       string `json:"memdev"`
	ID           string `json:"id"`
	Hotpluggable bool   `json:"hotpluggable"`
	Hotplugged   bool   `json:"hotplugged"`
	Size         uint64 `json:"size"`
}

MemoryDevicesData cotains the data describes a memory device

type MigrationDisk

type MigrationDisk struct {
	Total       int64 `json:"total"`
	Remaining   int64 `json:"remaining"`
	Transferred int64 `json:"transferred"`
}

MigrationDisk represents migration disk status

type MigrationRAM

type MigrationRAM struct {
	Total            int64 `json:"total"`
	Remaining        int64 `json:"remaining"`
	Transferred      int64 `json:"transferred"`
	TotalTime        int64 `json:"total-time"`
	SetupTime        int64 `json:"setup-time"`
	ExpectedDowntime int64 `json:"expected-downtime"`
	Duplicate        int64 `json:"duplicate"`
	Normal           int64 `json:"normal"`
	NormalBytes      int64 `json:"normal-bytes"`
	DirtySyncCount   int64 `json:"dirty-sync-count"`
}

MigrationRAM represents migration ram status

type MigrationStatus

type MigrationStatus struct {
	Status       string                   `json:"status"`
	Capabilities []map[string]interface{} `json:"capabilities,omitempty"`
	RAM          MigrationRAM             `json:"ram,omitempty"`
	Disk         MigrationDisk            `json:"disk,omitempty"`
	XbzrleCache  MigrationXbzrleCache     `json:"xbzrle-cache,omitempty"`
}

MigrationStatus represents migration status of a vm

type MigrationXbzrleCache

type MigrationXbzrleCache struct {
	CacheSize     int64 `json:"cache-size"`
	Bytes         int64 `json:"bytes"`
	Pages         int64 `json:"pages"`
	CacheMiss     int64 `json:"cache-miss"`
	CacheMissRate int64 `json:"cache-miss-rate"`
	Overflow      int64 `json:"overflow"`
}

MigrationXbzrleCache represents migration XbzrleCache status

type NetDevice

type NetDevice struct {
	// Type is the netdev type (e.g. tap).
	Type NetDeviceType

	// Driver is the qemu device driver
	Driver DeviceDriver

	// ID is the netdevice identifier.
	ID string

	// IfName is the interface name,
	IFName string

	// Bus is the bus path name of a PCI device.
	Bus string

	// Addr is the address offset of a PCI device.
	Addr string

	// DownScript is the tap interface deconfiguration script.
	DownScript string

	// Script is the tap interface configuration script.
	Script string

	// FDs represents the list of already existing file descriptors to be used.
	// This is mostly useful for mq support.
	FDs      []*os.File
	VhostFDs []*os.File

	// VHost enables virtio device emulation from the host kernel instead of from qemu.
	VHost bool

	// MACAddress is the networking device interface MAC address.
	MACAddress string

	// DisableModern prevents qemu from relying on fast MMIO.
	DisableModern bool

	// ROMFile specifies the ROM file being used for this device.
	ROMFile string

	// DevNo identifies the ccw devices for s390x architecture
	DevNo string

	// Transport is the virtio transport for this device.
	Transport VirtioTransport
}

NetDevice represents a guest networking device

func (NetDevice) QemuDeviceParams

func (netdev NetDevice) QemuDeviceParams(config *Config) []string

QemuDeviceParams returns the -device parameters for this network device

func (NetDevice) QemuNetdevParams

func (netdev NetDevice) QemuNetdevParams(config *Config) []string

QemuNetdevParams returns the -netdev parameters for this network device

func (NetDevice) QemuParams

func (netdev NetDevice) QemuParams(config *Config) []string

QemuParams returns the qemu parameters built out of this network device.

func (NetDevice) Valid

func (netdev NetDevice) Valid() bool

Valid returns true if the NetDevice structure is valid and complete.

type NetDeviceType

type NetDeviceType string

NetDeviceType is a qemu networking device type.

const (
	// TAP is a TAP networking device type.
	TAP NetDeviceType = "tap"

	// MACVTAP is a macvtap networking device type.
	MACVTAP NetDeviceType = "macvtap"

	// IPVTAP is a ipvtap virtual networking device type.
	IPVTAP NetDeviceType = "ipvtap"

	// VETHTAP is a veth-tap virtual networking device type.
	VETHTAP NetDeviceType = "vethtap"

	// VFIO is a direct assigned PCI device or PCI VF
	VFIO NetDeviceType = "VFIO"

	// VHOSTUSER is a vhost-user port (socket)
	VHOSTUSER NetDeviceType = "vhostuser"
)

func (NetDeviceType) QemuDeviceParam

func (n NetDeviceType) QemuDeviceParam(netdev *NetDevice, config *Config) DeviceDriver

QemuDeviceParam converts to the QEMU -device parameter notation

func (NetDeviceType) QemuNetdevParam

func (n NetDeviceType) QemuNetdevParam(netdev *NetDevice, config *Config) string

QemuNetdevParam converts to the QEMU -netdev parameter notation

type Object

type Object struct {
	// Driver is the qemu device driver
	Driver DeviceDriver

	// Type is the qemu object type.
	Type ObjectType

	// ID is the user defined object ID.
	ID string

	// DeviceID is the user defined device ID.
	DeviceID string

	// MemPath is the object's memory path.
	// This is only relevant for memory objects
	MemPath string

	// Size is the object size in bytes
	Size uint64

	// Debug this is a debug object
	Debug bool

	// File is the device file
	File string
}

Object is a qemu object representation.

func (Object) QemuParams

func (object Object) QemuParams(config *Config) []string

QemuParams returns the qemu parameters built out of this Object device.

func (Object) Valid

func (object Object) Valid() bool

Valid returns true if the Object structure is valid and complete.

type ObjectType

type ObjectType string

ObjectType is a string representing a qemu object type.

const (
	// MemoryBackendFile represents a guest memory mapped file.
	MemoryBackendFile ObjectType = "memory-backend-file"

	// TDXGuest represents a TDX object
	TDXGuest ObjectType = "tdx-guest"
)

type PCIeRootPortDevice

type PCIeRootPortDevice struct {
	ID string // format: rp{n}, n>=0

	Bus     string // default is pcie.0
	Chassis string // (slot, chassis) pair is mandatory and must be unique for each pcie-root-port, >=0, default is 0x00
	Slot    string // >=0, default is 0x00

	Multifunction bool   // true => "on", false => "off", default is off
	Addr          string // >=0, default is 0x00

	// The PCIE-PCI bridge can be hot-plugged only into pcie-root-port that has 'bus-reserve' property value to
	// provide secondary bus for the hot-plugged bridge.
	BusReserve    string
	Pref64Reserve string // reserve prefetched MMIO aperture, 64-bit
	Pref32Reserve string // reserve prefetched MMIO aperture, 32-bit
	MemReserve    string // reserve non-prefetched MMIO aperture, 32-bit *only*
	IOReserve     string // IO reservation

	ROMFile string // ROMFile specifies the ROM file being used for this device.

	// Transport is the virtio transport for this device.
	Transport VirtioTransport
}

PCIeRootPortDevice represents a memory balloon device.

func (PCIeRootPortDevice) QemuParams

func (b PCIeRootPortDevice) QemuParams(config *Config) []string

QemuParams returns the qemu parameters built out of the PCIeRootPortDevice.

func (PCIeRootPortDevice) Valid

func (b PCIeRootPortDevice) Valid() bool

Valid returns true if the PCIeRootPortDevice structure is valid and complete.

type PVPanicDevice

type PVPanicDevice struct {
	NoShutdown bool
}

PVPanicDevice represents a qemu pvpanic device.

func (PVPanicDevice) QemuParams

func (dev PVPanicDevice) QemuParams(config *Config) []string

QemuParams returns the qemu parameters built out of this serial device.

func (PVPanicDevice) Valid

func (dev PVPanicDevice) Valid() bool

Valid always returns true for pvpanic device

type QMP

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

QMP is a structure that contains the internal state used by startQMPLoop and the go routines it spwans. All the contents of this structure are private.

func (*QMP) ExecHotplugMemory

func (q *QMP) ExecHotplugMemory(ctx context.Context, qomtype, id, mempath string, size int, share bool) error

ExecHotplugMemory adds size of MiB memory to the guest

func (*QMP) ExecMemdevAdd

func (q *QMP) ExecMemdevAdd(ctx context.Context, qomtype, id, mempath string, size int, share bool, driver, driverID string) error

ExecMemdevAdd adds size of MiB memory device to the guest

func (*QMP) ExecQomGet

func (q *QMP) ExecQomGet(ctx context.Context, path, property string) (interface{}, error)

ExecQomGet qom-get path property

func (*QMP) ExecQomSet

func (q *QMP) ExecQomSet(ctx context.Context, path, property string, value uint64) error

ExecQomSet qom-set path property value

func (*QMP) ExecQueryCpus

func (q *QMP) ExecQueryCpus(ctx context.Context) ([]CPUInfo, error)

ExecQueryCpus returns a slice with the list of `CpuInfo` Since qemu 2.12, we have `query-cpus-fast` as a better choice in production we can still choose `ExecQueryCpus` for compatibility though not recommended.

func (*QMP) ExecQueryCpusFast

func (q *QMP) ExecQueryCpusFast(ctx context.Context) ([]CPUInfoFast, error)

ExecQueryCpusFast returns a slice with the list of `CpuInfoFast` This is introduced since 2.12, it does not incur a performance penalty and should be used in production instead of query-cpus.

func (*QMP) ExecQueryMemoryDevices

func (q *QMP) ExecQueryMemoryDevices(ctx context.Context) ([]MemoryDevices, error)

ExecQueryMemoryDevices returns a slice with the list of memory devices

func (*QMP) ExecQueryQmpSchema

func (q *QMP) ExecQueryQmpSchema(ctx context.Context) ([]SchemaInfo, error)

ExecQueryQmpSchema query all QMP wire ABI and returns a slice

func (*QMP) ExecSetMigrateArguments

func (q *QMP) ExecSetMigrateArguments(ctx context.Context, url string) error

ExecSetMigrateArguments sets the command line used for migration

func (*QMP) ExecSetMigrationCaps

func (q *QMP) ExecSetMigrationCaps(ctx context.Context, caps []map[string]interface{}) error

ExecSetMigrationCaps sets migration capabilities

func (*QMP) ExecuteAPVFIOMediatedDeviceAdd

func (q *QMP) ExecuteAPVFIOMediatedDeviceAdd(ctx context.Context, sysfsdev string) error

ExecuteAPVFIOMediatedDeviceAdd adds a VFIO mediated AP device to a QEMU instance using the device_add command.

func (*QMP) ExecuteBalloon

func (q *QMP) ExecuteBalloon(ctx context.Context, bytes uint64) error

ExecuteBalloon sets the size of the balloon, hence updates the memory allocated for the VM.

func (*QMP) ExecuteBlockdevAdd

func (q *QMP) ExecuteBlockdevAdd(ctx context.Context, device, blockdevID string, ro bool) error

ExecuteBlockdevAdd sends a blockdev-add to the QEMU instance. device is the path of the device to add, e.g., /dev/rdb0, and blockdevID is an identifier used to name the device. As this identifier will be passed directly to QMP, it must obey QMP's naming rules, e,g., it must start with a letter.

func (*QMP) ExecuteBlockdevAddWithCache

func (q *QMP) ExecuteBlockdevAddWithCache(ctx context.Context, device, blockdevID string, direct, noFlush, ro bool) error

ExecuteBlockdevAddWithCache has two more parameters direct and noFlush than ExecuteBlockdevAdd. They are cache-related options for block devices that are described in https://github.com/qemu/qemu/blob/master/qapi/block-core.json. direct denotes whether use of O_DIRECT (bypass the host page cache) is enabled. noFlush denotes whether flush requests for the device are ignored.

func (*QMP) ExecuteBlockdevDel

func (q *QMP) ExecuteBlockdevDel(ctx context.Context, blockdevID string) error

ExecuteBlockdevDel deletes a block device by sending a x-blockdev-del command for qemu versions < 2.9. It sends the updated blockdev-del command for qemu>=2.9. blockdevID is the id of the block device to be deleted. Typically, this will match the id passed to ExecuteBlockdevAdd. It must be a valid QMP id.

func (*QMP) ExecuteCPUDeviceAdd

func (q *QMP) ExecuteCPUDeviceAdd(ctx context.Context, driver, cpuID, socketID, dieID, coreID, threadID, romfile string) error

ExecuteCPUDeviceAdd adds a CPU to a QEMU instance using the device_add command. driver is the CPU model, cpuID must be a unique ID to identify the CPU, socketID is the socket number within node/board the CPU belongs to, coreID is the core number within socket the CPU belongs to, threadID is the thread number within core the CPU belongs to. Note that socketID and threadID are not a requirement for architecures like ppc64le.

func (*QMP) ExecuteCharDevUnixSocketAdd

func (q *QMP) ExecuteCharDevUnixSocketAdd(ctx context.Context, id, path string, wait, server bool) error

ExecuteCharDevUnixSocketAdd adds a character device using as backend a unix socket, id is an identifier for the device, path specifies the local path of the unix socket, wait is to block waiting for a client to connect, server specifies that the socket is a listening socket.

func (*QMP) ExecuteChardevDel

func (q *QMP) ExecuteChardevDel(ctx context.Context, chardevID string) error

ExecuteChardevDel deletes a char device by sending a chardev-remove command. chardevID is the id of the char device to be deleted. Typically, this will match the id passed to ExecuteCharDevUnixSocketAdd. It must be a valid QMP id.

func (*QMP) ExecuteCont

func (q *QMP) ExecuteCont(ctx context.Context) error

ExecuteCont sends the cont command to the instance.

func (*QMP) ExecuteDeviceAdd

func (q *QMP) ExecuteDeviceAdd(ctx context.Context, blockdevID, devID, driver, bus, romfile string, shared, disableModern bool) error

ExecuteDeviceAdd adds the guest portion of a device to a QEMU instance using the device_add command. blockdevID should match the blockdevID passed to a previous call to ExecuteBlockdevAdd. devID is the id of the device to add. Both strings must be valid QMP identifiers. driver is the name of the driver,e.g., virtio-blk-pci, and bus is the name of the bus. bus is optional. shared denotes if the drive can be shared allowing it to be passed more than once. disableModern indicates if virtio version 1.0 should be replaced by the former version 0.9, as there is a KVM bug that occurs when using virtio 1.0 in nested environments.

func (*QMP) ExecuteDeviceDel

func (q *QMP) ExecuteDeviceDel(ctx context.Context, devID string) error

ExecuteDeviceDel deletes guest portion of a QEMU device by sending a device_del command. devId is the identifier of the device to delete. Typically it would match the devID parameter passed to an earlier call to ExecuteDeviceAdd. It must be a valid QMP identidier.

This method blocks until a DEVICE_DELETED event is received for devID.

func (*QMP) ExecuteDumpGuestMemory

func (q *QMP) ExecuteDumpGuestMemory(ctx context.Context, protocol string, paging bool, format string) error

ExecuteDumpGuestMemory dump guest memory to host

func (*QMP) ExecuteGetFD

func (q *QMP) ExecuteGetFD(ctx context.Context, fdname string, fd *os.File) error

ExecuteGetFD sends a file descriptor via SCM rights and assigns it a name

func (*QMP) ExecuteMigrationIncoming

func (q *QMP) ExecuteMigrationIncoming(ctx context.Context, uri string) error

ExecuteMigrationIncoming start migration from incoming uri.

func (*QMP) ExecuteNVDIMMDeviceAdd

func (q *QMP) ExecuteNVDIMMDeviceAdd(ctx context.Context, id, mempath string, size int64, pmem *bool) error

ExecuteNVDIMMDeviceAdd adds a block device to a QEMU instance using a NVDIMM driver with the device_add command. id is the id of the device to add. It must be a valid QMP identifier. mempath is the path of the device to add, e.g., /dev/rdb0. size is the data size of the device. pmem is to guarantee the persistence of QEMU writes to the vNVDIMM backend.

func (*QMP) ExecuteNetCCWDeviceAdd

func (q *QMP) ExecuteNetCCWDeviceAdd(ctx context.Context, netdevID, devID, macAddr, bus string, queues int) error

ExecuteNetCCWDeviceAdd adds a Net CCW device to a QEMU instance using the device_add command. devID is the id of the device to add. Must be valid QMP identifier. netdevID is the id of nic added by previous netdev_add. queues is the number of queues of a nic.

func (*QMP) ExecuteNetPCIDeviceAdd

func (q *QMP) ExecuteNetPCIDeviceAdd(ctx context.Context, netdevID, devID, macAddr, addr, bus, romfile string, queues int, disableModern bool) error

ExecuteNetPCIDeviceAdd adds a Net PCI device to a QEMU instance using the device_add command. devID is the id of the device to add. Must be valid QMP identifier. netdevID is the id of nic added by previous netdev_add. queues is the number of queues of a nic. disableModern indicates if virtio version 1.0 should be replaced by the former version 0.9, as there is a KVM bug that occurs when using virtio 1.0 in nested environments.

func (*QMP) ExecuteNetdevAdd

func (q *QMP) ExecuteNetdevAdd(ctx context.Context, netdevType, netdevID, ifname, downscript, script string, queues int) error

ExecuteNetdevAdd adds a Net device to a QEMU instance using the netdev_add command. netdevID is the id of the device to add. Must be valid QMP identifier.

func (*QMP) ExecuteNetdevAddByFds

func (q *QMP) ExecuteNetdevAddByFds(ctx context.Context, netdevType, netdevID string, fdNames, vhostFdNames []string) error

ExecuteNetdevAddByFds adds a Net device to a QEMU instance using the netdev_add command by fds and vhostfds. netdevID is the id of the device to add. Must be valid QMP identifier.

func (*QMP) ExecuteNetdevChardevAdd

func (q *QMP) ExecuteNetdevChardevAdd(ctx context.Context, netdevType, netdevID, chardev string, queues int) error

ExecuteNetdevChardevAdd adds a Net device to a QEMU instance using the netdev_add command. netdevID is the id of the device to add. Must be valid QMP identifier.

func (*QMP) ExecuteNetdevDel

func (q *QMP) ExecuteNetdevDel(ctx context.Context, netdevID string) error

ExecuteNetdevDel deletes a Net device from a QEMU instance using the netdev_del command. netdevID is the id of the device to delete.

func (*QMP) ExecutePCIDeviceAdd

func (q *QMP) ExecutePCIDeviceAdd(ctx context.Context, blockdevID, devID, driver, addr, bus, romfile string, queues int, shared, disableModern bool) error

ExecutePCIDeviceAdd is the PCI version of ExecuteDeviceAdd. This function can be used to hot plug PCI devices on PCI(E) bridges, unlike ExecuteDeviceAdd this function receive the device address on its parent bus. bus is optional. queues specifies the number of queues of a block device. shared denotes if the drive can be shared allowing it to be passed more than once. disableModern indicates if virtio version 1.0 should be replaced by the former version 0.9, as there is a KVM bug that occurs when using virtio 1.0 in nested environments.

func (*QMP) ExecutePCIVFIODeviceAdd

func (q *QMP) ExecutePCIVFIODeviceAdd(ctx context.Context, devID, bdf, addr, bus, romfile string) error

ExecutePCIVFIODeviceAdd adds a VFIO device to a QEMU instance using the device_add command. This function can be used to hot plug VFIO devices on PCI(E) bridges, unlike ExecuteVFIODeviceAdd this function receives the bus and the device address on its parent bus. bus is optional. devID is the id of the device to add.Must be valid QMP identifier. bdf is the PCI bus-device-function of the pci device.

func (*QMP) ExecutePCIVFIOMediatedDeviceAdd

func (q *QMP) ExecutePCIVFIOMediatedDeviceAdd(ctx context.Context, devID, sysfsdev, addr, bus, romfile string) error

ExecutePCIVFIOMediatedDeviceAdd adds a VFIO mediated device to a QEMU instance using the device_add command. This function can be used to hot plug VFIO mediated devices on PCI(E) bridges or root bus, unlike ExecuteVFIODeviceAdd this function receives the bus and the device address on its parent bus. devID is the id of the device to add. Must be valid QMP identifier. sysfsdev is the VFIO mediated device. Both bus and addr are optional. If they are both set to be empty, the system will pick up an empty slot on root bus.

func (*QMP) ExecutePCIVSockAdd

func (q *QMP) ExecutePCIVSockAdd(ctx context.Context, id, guestCID, vhostfd, addr, bus, romfile string, disableModern bool) error

ExecutePCIVSockAdd adds a vhost-vsock-pci bus disableModern indicates if virtio version 1.0 should be replaced by the former version 0.9, as there is a KVM bug that occurs when using virtio 1.0 in nested environments.

func (*QMP) ExecutePCIVhostUserDevAdd

func (q *QMP) ExecutePCIVhostUserDevAdd(ctx context.Context, driver, devID, chardevID, addr, bus string) error

ExecutePCIVhostUserDevAdd adds a vhost-user device to a QEMU instance using the device_add command. This function can be used to hot plug vhost-user devices on PCI(E) bridges. It receives the bus and the device address on its parent bus. bus is optional. devID is the id of the device to add.Must be valid QMP identifier. chardevID is the QMP identifier of character device using a unix socket as backend. driver is the name of vhost-user driver, like vhost-user-blk-pci.

func (*QMP) ExecuteQMPCapabilities

func (q *QMP) ExecuteQMPCapabilities(ctx context.Context) error

ExecuteQMPCapabilities executes the qmp_capabilities command on the instance.

func (*QMP) ExecuteQueryHotpluggableCPUs

func (q *QMP) ExecuteQueryHotpluggableCPUs(ctx context.Context) ([]HotpluggableCPU, error)

ExecuteQueryHotpluggableCPUs returns a slice with the list of hotpluggable CPUs

func (*QMP) ExecuteQueryMigration

func (q *QMP) ExecuteQueryMigration(ctx context.Context) (MigrationStatus, error)

ExecuteQueryMigration queries migration progress.

func (*QMP) ExecuteQueryStatus

func (q *QMP) ExecuteQueryStatus(ctx context.Context) (StatusInfo, error)

ExecuteQueryStatus queries guest status

func (*QMP) ExecuteQuit

func (q *QMP) ExecuteQuit(ctx context.Context) error

ExecuteQuit sends the quit command to the instance, terminating the QMP instance immediately.

func (*QMP) ExecuteSCSIDeviceAdd

func (q *QMP) ExecuteSCSIDeviceAdd(ctx context.Context, blockdevID, devID, driver, bus, romfile string, scsiID, lun int, shared, disableModern bool) error

ExecuteSCSIDeviceAdd adds the guest portion of a block device to a QEMU instance using a SCSI driver with the device_add command. blockdevID should match the blockdevID passed to a previous call to ExecuteBlockdevAdd. devID is the id of the device to add. Both strings must be valid QMP identifiers. driver is the name of the scsi driver,e.g., scsi-hd, and bus is the name of a SCSI controller bus. scsiID is the SCSI id, lun is logical unit number. scsiID and lun are optional, a negative value for scsiID and lun is ignored. shared denotes if the drive can be shared allowing it to be passed more than once. disableModern indicates if virtio version 1.0 should be replaced by the former version 0.9, as there is a KVM bug that occurs when using virtio 1.0 in nested environments.

func (*QMP) ExecuteStop

func (q *QMP) ExecuteStop(ctx context.Context) error

ExecuteStop sends the stop command to the instance.

func (*QMP) ExecuteSystemPowerdown

func (q *QMP) ExecuteSystemPowerdown(ctx context.Context) error

ExecuteSystemPowerdown sends the system_powerdown command to the instance. This function will block until the SHUTDOWN event is received.

func (*QMP) ExecuteVFIODeviceAdd

func (q *QMP) ExecuteVFIODeviceAdd(ctx context.Context, devID, bdf, bus, romfile string) error

ExecuteVFIODeviceAdd adds a VFIO device to a QEMU instance using the device_add command. devID is the id of the device to add. Must be valid QMP identifier. bdf is the PCI bus-device-function of the pci device. bus is optional. When hot plugging a PCIe device, the bus can be the ID of the pcie-root-port.

func (*QMP) ExecuteVirtSerialPortAdd

func (q *QMP) ExecuteVirtSerialPortAdd(ctx context.Context, id, name, chardev string) error

ExecuteVirtSerialPortAdd adds a virtserialport. id is an identifier for the virtserialport, name is a name for the virtserialport and it will be visible in the VM, chardev is the character device id previously added.

func (*QMP) Shutdown

func (q *QMP) Shutdown()

Shutdown closes the domain socket used to monitor a QEMU instance and terminates all the go routines spawned by QMPStart to manage that instance. QMP.Shutdown does not shut down the running instance. Calling QMP.Shutdown will result in the disconnectedCh channel being closed, indicating that we have lost connection to the QMP instance. In this case it does not indicate that the instance has quit.

QMP.Shutdown should not be called concurrently with other QMP methods. It should not be called twice on the same QMP instance.

Calling QMP.Shutdown after the disconnectedCh channel is closed is permitted but will not have any effect.

type QMPConfig

type QMPConfig struct {
	// eventCh can be specified by clients who wish to receive QMP
	// events.
	EventCh chan<- QMPEvent

	// logger is used by the qmpStart function and all the go routines
	// it spawns to log information.
	Logger QMPLog

	// specify the capacity of buffer used by receive QMP response.
	MaxCapacity int
}

QMPConfig is a configuration structure that can be used to specify a logger and a channel to which logs and QMP events are to be sent. If neither of these fields are specified, or are set to nil, no logs will be written and no QMP events will be reported to the client.

type QMPEvent

type QMPEvent struct {
	// The name of the event, e.g., DEVICE_DELETED
	Name string

	// The data associated with the event.  The contents of this map are
	// unprocessed by the qemu package.  It is simply the result of
	// unmarshalling the QMP json event.  Here's an example map
	// map[string]interface{}{
	//	"driver": "virtio-blk-pci",
	//	"drive":  "drive_3437843748734873483",
	// }
	Data map[string]interface{}

	// The event's timestamp converted to a time.Time object.
	Timestamp time.Time
}

QMPEvent contains a single QMP event, sent on the QMPConfig.EventCh channel.

type QMPLog

type QMPLog interface {
	// V returns true if the given argument is less than or equal
	// to the implementation's defined verbosity level.
	V(int32) bool

	// Infof writes informational output to the log.  A newline will be
	// added to the output if one is not provided.
	Infof(string, ...interface{})

	// Warningf writes warning output to the log.  A newline will be
	// added to the output if one is not provided.
	Warningf(string, ...interface{})

	// Errorf writes error output to the log.  A newline will be
	// added to the output if one is not provided.
	Errorf(string, ...interface{})
}

QMPLog is a logging interface used by the qemu package to log various interesting pieces of information. Rather than introduce a dependency on a given logging package, qemu presents this interface that allows clients to provide their own logging type which they can use to seamlessly integrate qemu's logs into their own logs. A QMPLog implementation can be specified in the QMPConfig structure.

type QMPSocket

type QMPSocket struct {
	// Type is the socket type (e.g. "unix").
	Type QMPSocketType

	// Name is the socket name.
	Name string

	// Server tells if this is a server socket.
	Server bool

	// NoWait tells if qemu should block waiting for a client to connect.
	NoWait bool
}

QMPSocket represents a qemu QMP socket configuration.

func (QMPSocket) Valid

func (qmp QMPSocket) Valid() bool

Valid returns true if the QMPSocket structure is valid and complete.

type QMPSocketType

type QMPSocketType string

QMPSocketType is the type of socket used for QMP communication.

const (
	// Unix socket for QMP.
	Unix QMPSocketType = "unix"
)

type QMPVersion

type QMPVersion struct {
	Major        int
	Minor        int
	Micro        int
	Capabilities []string
}

QMPVersion contains the version number and the capabailities of a QEMU instance, as reported in the QMP greeting message.

type RTC

type RTC struct {
	// Base is the RTC start time.
	Base RTCBaseType

	// Clock is the is the RTC clock driver.
	Clock RTCClock

	// DriftFix is the drift fixing mechanism.
	DriftFix RTCDriftFix
}

RTC represents a qemu Real Time Clock configuration.

func (RTC) Valid

func (rtc RTC) Valid() bool

Valid returns true if the RTC structure is valid and complete.

type RTCBaseType

type RTCBaseType string

RTCBaseType is the qemu RTC base time type.

const (
	// UTC is the UTC base time for qemu RTC.
	UTC RTCBaseType = "utc"

	// LocalTime is the local base time for qemu RTC.
	LocalTime RTCBaseType = "localtime"
)

type RTCClock

type RTCClock string

RTCClock is the qemu RTC clock type.

const (
	// Host is for using the host clock as a reference.
	Host RTCClock = "host"

	// RT is for using the host monotonic clock as a reference.
	RT RTCClock = "rt"

	// VM is for using the guest clock as a reference
	VM RTCClock = "vm"
)

type RTCDriftFix

type RTCDriftFix string

RTCDriftFix is the qemu RTC drift fix type.

const (
	// Slew is the qemu RTC Drift fix mechanism.
	Slew RTCDriftFix = "slew"

	// NoDriftFix means we don't want/need to fix qemu's RTC drift.
	NoDriftFix RTCDriftFix = "none"
)

type RngDevice

type RngDevice struct {
	// ID is the device ID
	ID string
	// Filename is entropy source on the host
	Filename string
	// MaxBytes is the bytes allowed to guest to get from the host’s entropy per period
	MaxBytes uint
	// Period is duration of a read period in seconds
	Period uint
	// ROMFile specifies the ROM file being used for this device.
	ROMFile string
	// DevNo identifies the ccw devices for s390x architecture
	DevNo string
	// Transport is the virtio transport for this device.
	Transport VirtioTransport
}

RngDevice represents a random number generator device.

func (RngDevice) QemuParams

func (v RngDevice) QemuParams(config *Config) []string

QemuParams returns the qemu parameters built out of the RngDevice.

func (RngDevice) Valid

func (v RngDevice) Valid() bool

Valid returns true if the RngDevice structure is valid and complete.

type SCSIController

type SCSIController struct {
	ID string

	// Bus on which the SCSI controller is attached, this is optional
	Bus string

	// Addr is the PCI address offset, this is optional
	Addr string

	// DisableModern prevents qemu from relying on fast MMIO.
	DisableModern bool

	// IOThread is the IO thread on which IO will be handled
	IOThread string

	// ROMFile specifies the ROM file being used for this device.
	ROMFile string

	// DevNo identifies the ccw devices for s390x architecture
	DevNo string

	// Transport is the virtio transport for this device.
	Transport VirtioTransport
}

SCSIController represents a SCSI controller device.

func (SCSIController) QemuParams

func (scsiCon SCSIController) QemuParams(config *Config) []string

QemuParams returns the qemu parameters built out of this SCSIController device.

func (SCSIController) Valid

func (scsiCon SCSIController) Valid() bool

Valid returns true if the SCSIController structure is valid and complete.

type SMP

type SMP struct {
	// CPUs is the number of VCPUs made available to qemu.
	CPUs uint32

	// Cores is the number of cores made available to qemu.
	Cores uint32

	// Threads is the number of threads made available to qemu.
	Threads uint32

	// Sockets is the number of sockets made available to qemu.
	Sockets uint32

	// MaxCPUs is the maximum number of VCPUs that a VM can have.
	// This value, if non-zero, MUST BE equal to or greater than CPUs
	MaxCPUs uint32
}

SMP is the multi processors configuration structure.

type SchemaInfo

type SchemaInfo struct {
	MetaType string `json:"meta-type"`
	Name     string `json:"name"`
}

SchemaInfo represents all QMP wire ABI

type SecurityModelType

type SecurityModelType string

SecurityModelType is a qemu filesystem security model type.

const (
	// None is like passthrough without failure reports.
	None SecurityModelType = "none"

	// PassThrough uses the same credentials on both the host and guest.
	PassThrough SecurityModelType = "passthrough"

	// MappedXattr stores some files attributes as extended attributes.
	MappedXattr SecurityModelType = "mapped-xattr"

	// MappedFile stores some files attributes in the .virtfs directory.
	MappedFile SecurityModelType = "mapped-file"
)

type SerialDevice

type SerialDevice struct {
	// Driver is the qemu device driver
	Driver DeviceDriver

	// ID is the serial device identifier.
	ID string

	// DisableModern prevents qemu from relying on fast MMIO.
	DisableModern bool

	// ROMFile specifies the ROM file being used for this device.
	ROMFile string

	// DevNo identifies the ccw devices for s390x architecture
	DevNo string

	// Transport is the virtio transport for this device.
	Transport VirtioTransport

	// MaxPorts is the maximum number of ports for this device.
	MaxPorts uint
}

SerialDevice represents a qemu serial device.

func (SerialDevice) QemuParams

func (dev SerialDevice) QemuParams(config *Config) []string

QemuParams returns the qemu parameters built out of this serial device.

func (SerialDevice) Valid

func (dev SerialDevice) Valid() bool

Valid returns true if the SerialDevice structure is valid and complete.

type StatusInfo

type StatusInfo struct {
	Running    bool   `json:"running"`
	SingleStep bool   `json:"singlestep"`
	Status     string `json:"status"`
}

StatusInfo represents guest running status

type VFIODevice

type VFIODevice struct {
	// Bus-Device-Function of device
	BDF string

	// ROMFile specifies the ROM file being used for this device.
	ROMFile string

	// DevNo identifies the ccw devices for s390x architecture
	DevNo string

	// VendorID specifies vendor id
	VendorID string

	// DeviceID specifies device id
	DeviceID string

	// Bus specifies device bus
	Bus string

	// Transport is the virtio transport for this device.
	Transport VirtioTransport
}

VFIODevice represents a qemu vfio device meant for direct access by guest OS.

func (VFIODevice) QemuParams

func (vfioDev VFIODevice) QemuParams(config *Config) []string

QemuParams returns the qemu parameters built out of this vfio device.

func (VFIODevice) Valid

func (vfioDev VFIODevice) Valid() bool

Valid returns true if the VFIODevice structure is valid and complete.

type VSOCKDevice

type VSOCKDevice struct {
	ID string

	ContextID uint64

	// VHostFD vhost file descriptor that holds the ContextID
	VHostFD *os.File

	// DisableModern prevents qemu from relying on fast MMIO.
	DisableModern bool

	// ROMFile specifies the ROM file being used for this device.
	ROMFile string

	// DevNo identifies the ccw devices for s390x architecture
	DevNo string

	// Transport is the virtio transport for this device.
	Transport VirtioTransport
}

VSOCKDevice represents a AF_VSOCK socket.

func (VSOCKDevice) QemuParams

func (vsock VSOCKDevice) QemuParams(config *Config) []string

QemuParams returns the qemu parameters built out of the VSOCK device.

func (VSOCKDevice) Valid

func (vsock VSOCKDevice) Valid() bool

Valid returns true if the VSOCKDevice structure is valid and complete.

type VhostUserDevice

type VhostUserDevice struct {
	SocketPath     string //path to vhostuser socket on host
	CharDevID      string
	TypeDevID      string //variable QEMU parameter based on value of VhostUserType
	Address        string //used for MAC address in net case
	Tag            string //virtio-fs volume id for mounting inside guest
	CacheSize      uint32 //virtio-fs DAX cache size in MiB
	SharedVersions bool   //enable virtio-fs shared version metadata
	VhostUserType  DeviceDriver

	// ROMFile specifies the ROM file being used for this device.
	ROMFile string

	// DevNo identifies the CCW device for s390x.
	DevNo string

	// Transport is the virtio transport for this device.
	Transport VirtioTransport
}

VhostUserDevice represents a qemu vhost-user device meant to be passed in to the guest

func (VhostUserDevice) QemuBlkParams

func (vhostuserDev VhostUserDevice) QemuBlkParams(config *Config) []string

QemuBlkParams builds QEMU device parameters for a VhostUserBlk device

func (VhostUserDevice) QemuFSParams

func (vhostuserDev VhostUserDevice) QemuFSParams(config *Config) []string

QemuFSParams builds QEMU device parameters for a VhostUserFS device

func (VhostUserDevice) QemuNetParams

func (vhostuserDev VhostUserDevice) QemuNetParams(config *Config) []string

QemuNetParams builds QEMU netdev and device parameters for a VhostUserNet device

func (VhostUserDevice) QemuParams

func (vhostuserDev VhostUserDevice) QemuParams(config *Config) []string

QemuParams returns the qemu parameters built out of this vhostuser device.

func (VhostUserDevice) QemuSCSIParams

func (vhostuserDev VhostUserDevice) QemuSCSIParams(config *Config) []string

QemuSCSIParams builds QEMU device parameters for a VhostUserSCSI device

func (VhostUserDevice) Valid

func (vhostuserDev VhostUserDevice) Valid() bool

Valid returns true if there is a valid structure defined for VhostUserDevice

type Virtio9PMultidev

type Virtio9PMultidev string

Virtio9PMultidev filesystem behaviour to deal with multiple devices being shared with a 9p export.

const (
	// Remap shares multiple devices with only one export.
	Remap Virtio9PMultidev = "remap"

	// Warn assumes that only one device is shared by the same export.
	// Only a warning message is logged (once) by qemu on host side.
	// This is the default behaviour.
	Warn Virtio9PMultidev = "warn"

	// Forbid like "warn" but also deny access to additional devices on guest.
	Forbid Virtio9PMultidev = "forbid"
)

type VirtioTransport

type VirtioTransport string

VirtioTransport is the transport in use for a virtio device.

const (
	// TransportPCI is the PCI transport for virtio device.
	TransportPCI VirtioTransport = "pci"

	// TransportCCW is the CCW transport for virtio devices.
	TransportCCW VirtioTransport = "ccw"

	// TransportMMIO is the MMIO transport for virtio devices.
	TransportMMIO VirtioTransport = "mmio"
)

Jump to

Keyboard shortcuts

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