Documentation ¶
Overview ¶
Package virtualbox implements wrappers to interact with VirtualBox.
VirtualBox Machine State Transition ¶
A VirtualBox machine can be in one of the following states:
poweroff: The VM is powered off and no previous running state saved. running: The VM is running. paused: The VM is paused, but its state is not saved to disk. If you quit VirtualBox, the state will be lost. saved: The VM is powered off, and the previous state is saved on disk. aborted: The VM process crashed. This should happen very rarely.
VBoxManage supports the following transitions between states:
startvm <VM>: poweroff|saved --> running controlvm <VM> pause: running --> paused controlvm <VM> resume: paused --> running controlvm <VM> savestate: running -> saved controlvm <VM> acpipowerbutton: running --> poweroff controlvm <VM> poweroff: running --> poweroff (unsafe) controlvm <VM> reset: running --> poweroff --> running (unsafe)
Poweroff and reset are unsafe because they will lose state and might corrupt the disk image.
To make things simpler, the following transitions are used instead:
start: poweroff|saved|paused|aborted --> running stop: [paused|saved -->] running --> poweroff save: [paused -->] running --> saved restart: [paused|saved -->] running --> poweroff --> running poweroff: [paused|saved -->] running --> poweroff (unsafe) reset: [paused|saved -->] running --> poweroff --> running (unsafe)
The takeaway is we try our best to transit the virtual machine into the state you want it to be, and you only need to watch out for the potentially unsafe poweroff and reset.
Guest Properties Management ¶
This part of the APIworks both on the host and the guest.
The API enables to set & get specific properties, plus waiting on properties patterns (both blocking and non-blocking).
Package virtualbox is a generated GoMock package.
Index ¶
- Constants
- Variables
- func AddHostonlyDHCP(ifname string, d DHCP) error
- func AddInternalDHCP(netname string, d DHCP) error
- func CloneHD(input, output string) error
- func CloneMachine(baseImageName string, newImageName string, register bool) error
- func DHCPs() (map[string]*DHCP, error)
- func DelExtra(name, key string) error
- func DeleteGuestProperty(vm string, prop string) error
- func GetGuestProperty(vm string, prop string) (string, error)
- func HostonlyNets() (map[string]*HostonlyNet, error)
- func ImportOV(path string) error
- func MakeDiskImage(dest string, size uint, r io.Reader) error
- func NATNets() (map[string]NATNet, error)
- func ParseIPv4Mask(s string) net.IPMask
- func Run(_ context.Context, args ...string) (string, string, error)
- func SetExtra(name, key, val string) error
- func SetGuestProperty(vm string, prop string, val string) error
- func WaitGuestProperties(vm string, propPattern string, done chan bool, wg *sync.WaitGroup) chan GuestProperty
- func WaitGuestProperty(vm string, prop string) (string, string, error)
- func ZeroFill(w io.Writer, n int64) error
- type Command
- type DHCP
- type DriveType
- type Flag
- type GuestProperty
- type HostonlyNet
- type LogFunc
- type Machine
- func (m *Machine) AddNATPF(n int, name string, rule PFRule) error
- func (m *Machine) AddStorageCtl(name string, ctl StorageController) error
- func (m *Machine) AttachStorage(ctlName string, medium StorageMedium) error
- func (m *Machine) DelNATPF(n int, name string) error
- func (m *Machine) DelStorageCtl(name string) error
- func (m *Machine) Delete() error
- func (m *Machine) DeleteExtraData(key string) error
- func (m *Machine) DisconnectSerialPort(portNumber int) error
- func (m *Machine) GetExtraData(key string) (*string, error)
- func (m *Machine) Modify() error
- func (m *Machine) Pause() error
- func (m *Machine) Poweroff() error
- func (m *Machine) Refresh() error
- func (m *Machine) Reset() error
- func (m *Machine) Restart() error
- func (m *Machine) Save() error
- func (m *Machine) SetExtraData(key, val string) error
- func (m *Machine) SetNIC(n int, nic NIC) error
- func (m *Machine) Start() error
- func (m *Machine) Stop() error
- type MachineManager
- type MachineState
- type Manager
- type MockCommand
- type MockCommandMockRecorder
- type NATNet
- type NIC
- type NICHardware
- type NICNetwork
- type Option
- type PFProto
- type PFRule
- type StorageController
- type StorageControllerChipset
- type StorageMedium
- type SystemBus
- type Virtualbox
Examples ¶
Constants ¶
const ( // Poweroff is a MachineState value. Poweroff = MachineState("poweroff") // Running is a MachineState value. Running = MachineState("running") // Paused is a MachineState value. Paused = MachineState("paused") // Saved is a MachineState value. Saved = MachineState("saved") // Aborted is a MachineState value. Aborted = MachineState("aborted") )
const ( // NICNetAbsent when there is no NIC. NICNetAbsent = NICNetwork("none") // NICNetDisconnected when the NIC is disconnected NICNetDisconnected = NICNetwork("null") // NICNetNAT when the NIC is NAT-ed to access the external network. NICNetNAT = NICNetwork("nat") // NICNetBridged when the NIC is the bridge to the external network. NICNetBridged = NICNetwork("bridged") // NICNetInternal when the NIC does not have access to the external network. NICNetInternal = NICNetwork("intnet") // NICNetHostonly when the NIC can only access one host-only network. NICNetHostonly = NICNetwork("hostonly") // NICNetGeneric when the NIC behaves like a standard physical one. NICNetGeneric = NICNetwork("generic") )
const ( // AMDPCNetPCIII when the NIC emulates a Am79C970A hardware. AMDPCNetPCIII = NICHardware("Am79C970A") // AMDPCNetFASTIII when the NIC emulates a Am79C973 hardware. AMDPCNetFASTIII = NICHardware("Am79C973") // IntelPro1000MTDesktop when the NIC emulates a 82540EM hardware. IntelPro1000MTDesktop = NICHardware("82540EM") // IntelPro1000TServer when the NIC emulates a 82543GC hardware. IntelPro1000TServer = NICHardware("82543GC") // IntelPro1000MTServer when the NIC emulates a 82545EM hardware. IntelPro1000MTServer = NICHardware("82545EM") // VirtIO when the NIC emulates a virtio. VirtIO = NICHardware("virtio") )
const ( // PFTCP when forwarding a TCP port. PFTCP = PFProto("tcp") // PFUDP when forwarding an UDP port. PFUDP = PFProto("udp") )
const ( // SysBusIDE when the storage controller provides an IDE bus. SysBusIDE = SystemBus("ide") // SysBusSATA when the storage controller provides a SATA bus. SysBusSATA = SystemBus("sata") // SysBusSCSI when the storage controller provides an SCSI bus. SysBusSCSI = SystemBus("scsi") // SysBusFloppy when the storage controller provides access to Floppy drives. SysBusFloppy = SystemBus("floppy") // SysBusSAS storage controller provides a SAS bus. SysBusSAS = SystemBus("sas") // SysBusUSB storage controller proveds an USB bus. SysBusUSB = SystemBus("usb") // SysBusPCIE storage controller proveds a PCIe bus. SysBusPCIE = SystemBus("pcie") // SysBusVirtio storage controller proveds a Virtio bus. SysBusVirtio = SystemBus("virtio") )
const ( // CtrlLSILogic when the storage controller emulates LSILogic hardware. CtrlLSILogic = StorageControllerChipset("LSILogic") // CtrlLSILogicSAS when the storage controller emulates LSILogicSAS hardware. CtrlLSILogicSAS = StorageControllerChipset("LSILogicSAS") // CtrlBusLogic when the storage controller emulates BusLogic hardware. CtrlBusLogic = StorageControllerChipset("BusLogic") // CtrlIntelAHCI when the storage controller emulates IntelAHCI hardware. CtrlIntelAHCI = StorageControllerChipset("IntelAHCI") // CtrlPIIX3 when the storage controller emulates PIIX3 hardware. CtrlPIIX3 = StorageControllerChipset("PIIX3") // CtrlPIIX4 when the storage controller emulates PIIX4 hardware. CtrlPIIX4 = StorageControllerChipset("PIIX4") // CtrlICH6 when the storage controller emulates ICH6 hardware. CtrlICH6 = StorageControllerChipset("ICH6") // CtrlI82078 when the storage controller emulates I82078 hardware. CtrlI82078 = StorageControllerChipset("I82078") // CtrlUSB storage controller emulates USB hardware. CtrlUSB = StorageControllerChipset("USB") // CtrlNVME storage controller emulates NVME hardware. CtrlNVME = StorageControllerChipset("NVMe") // CtrlVirtIO storage controller emulates VirtIO hardware. CtrlVirtIO = StorageControllerChipset("VirtIO") )
const ( // DriveDVD when the drive is a DVD reader/writer. DriveDVD = DriveType("dvddrive") // DriveHDD when the drive is a hard disk or SSD. DriveHDD = DriveType("hdd") // DriveFDD when the drive is a floppy. DriveFDD = DriveType("fdd") )
Variables ¶
var ( // Verbose toggles the library in verbose execution mode. Verbose bool // ErrMachineExist holds the error message when the machine already exists. ErrMachineExist = errors.New("machine already exists") // ErrMachineNotExist holds the error message when the machine does not exist. ErrMachineNotExist = errors.New("machine does not exist") // ErrCommandNotFound holds the error message when the VBoxManage commands was not found. ErrCommandNotFound = errors.New("command not found") )
var ( // ErrHostonlyInterfaceCreation is the error message created when VBoxManaged failed to create a new hostonly interface. ErrHostonlyInterfaceCreation = errors.New("failed to create hostonly interface") )
Functions ¶
func AddHostonlyDHCP ¶
AddHostonlyDHCP adds a DHCP server to a host-only network.
func AddInternalDHCP ¶
AddInternalDHCP adds a DHCP server to an internal network.
func CloneMachine ¶
CloneMachine clones the given machine name into a new one.
func DeleteGuestProperty ¶
DeleteGuestProperty deletes a VirtualBox guestproperty.
Example ¶
package main import ( virtualbox "github.com/monsterroot/go-virtualbox" ) var VM = "MyVM" func main() { err := virtualbox.SetGuestProperty(VM, "test_name", "test_val") if err != nil { panic(err) } err = virtualbox.DeleteGuestProperty(VM, "test_name") if err != nil { panic(err) } }
Output:
func GetGuestProperty ¶
GetGuestProperty reads a VirtualBox guestproperty.
Example ¶
package main import ( "log" virtualbox "github.com/monsterroot/go-virtualbox" ) var VM = "MyVM" func main() { err := virtualbox.SetGuestProperty(VM, "test_name", "test_val") if err != nil { panic(err) } val, err := virtualbox.GetGuestProperty(VM, "test_name") if err != nil { panic(err) } log.Println("val:", val) }
Output:
func HostonlyNets ¶
func HostonlyNets() (map[string]*HostonlyNet, error)
HostonlyNets gets all host-only networks in a map keyed by HostonlyNet.NetworkName.
func MakeDiskImage ¶
MakeDiskImage makes a disk image at dest with the given size in MB. If r is not nil, it will be read as a raw disk image to convert from.
func ParseIPv4Mask ¶
ParseIPv4Mask parses IPv4 netmask written in IP form (e.g. 255.255.255.0). This function should really belong to the net package.
func Run ¶
Run is a helper method used to execute the commands using the configured VBoxManage path. The command should be omitted and only the arguments should be passed. It will return the stdout, stderr and error if one occured during command execution.
func SetGuestProperty ¶
SetGuestProperty writes a VirtualBox guestproperty to the given value.
Example ¶
package main import ( virtualbox "github.com/monsterroot/go-virtualbox" ) var VM = "MyVM" func main() { err := virtualbox.SetGuestProperty(VM, "test_name", "test_val") if err != nil { panic(err) } }
Output:
func WaitGuestProperties ¶
func WaitGuestProperties(vm string, propPattern string, done chan bool, wg *sync.WaitGroup) chan GuestProperty
WaitGuestProperties wait for changes in GuestProperties
WaitGetProperties wait for changes in the VirtualBox GuestProperties matching the given propsPattern, for the given VM. The given bool channel indicates caller-required closure. The optional sync.WaitGroup enabke the caller program to wait for Go routine completion.
It returns a channel of GuestProperty objects (name-values pairs) populated as they change.
If the bool channel is never closed, the Waiter Go routine never ends, but on VBoxManage error.
Each GuestProperty change must be read from thwe channel before the waiter Go routine resumes waiting for the next matching change.
Example ¶
package main import ( "log" "sync" "time" virtualbox "github.com/monsterroot/go-virtualbox" ) var VM = "MyVM" func main() { go func() { second := time.Second time.Sleep(1 * second) _ = virtualbox.SetGuestProperty(VM, "test_name", "test_val1") time.Sleep(1 * second) _ = virtualbox.SetGuestProperty(VM, "test_name", "test_val2") time.Sleep(1 * second) _ = virtualbox.SetGuestProperty(VM, "test_name", "test_val1") }() wg := new(sync.WaitGroup) done := make(chan bool) propsPattern := "test_*" props := virtualbox.WaitGuestProperties(VM, propsPattern, done, wg) ok := true left := 3 for ; ok && left > 0; left-- { var prop virtualbox.GuestProperty prop, ok = <-props log.Println("name:", prop.Name, ", value:", prop.Value) } close(done) // close channel wg.Wait() // wait for gorouting }
Output:
func WaitGuestProperty ¶
WaitGuestProperty blocks until a VirtualBox guestproperty is changed
The key to wait for can be a fully defined key or a key wild-card (glob-pattern). The first returned value is the property name that was changed. The second returned value is the new property value, Deletion of the guestproperty causes WaitGuestProperty to return the string.
Example ¶
package main import ( "log" "time" virtualbox "github.com/monsterroot/go-virtualbox" ) var VM = "MyVM" func main() { go func() { second := time.Second time.Sleep(1 * second) _ = virtualbox.SetGuestProperty(VM, "test_name", "test_val") }() name, val, err := virtualbox.WaitGuestProperty(VM, "test_*") if err != nil { panic(err) } log.Println("name:", name, ", value:", val) }
Output:
Types ¶
type Command ¶
type Command interface {
// contains filtered or unexported methods
}
Command is the mock-able interface to run VirtualBox commands such as VBoxManage (host side) or VBoxControl (guest side)
type Flag ¶
type Flag int
Flag is an active VM configuration toggle
type GuestProperty ¶
GuestProperty holds key, value and associated flags.
type HostonlyNet ¶
type HostonlyNet struct { Name string GUID string DHCP bool IPv4 net.IPNet IPv6 net.IPNet HwAddr net.HardwareAddr Medium string Status string NetworkName string // referenced in DHCP.NetworkName }
HostonlyNet defines each host-only network.
func CreateHostonlyNet ¶
func CreateHostonlyNet() (*HostonlyNet, error)
CreateHostonlyNet creates a new host-only network.
func (*HostonlyNet) Config ¶
func (n *HostonlyNet) Config() error
Config changes the configuration of the host-only network.
type LogFunc ¶
type LogFunc func(string, ...interface{})
LogFunc is the signature to log traces.
var Debug LogFunc = noLog
Debug is the Logger currently in use.
type Machine ¶
type Machine struct { Name string Firmware string UUID string State MachineState CPUs uint Memory uint // main memory (in MB) VRAM uint // video memory (in MB) CfgFile string BaseFolder string OSType string Flag Flag BootOrder []string // max 4 slots, each in {none|floppy|dvd|disk|net} NICs []NIC }
Machine information.
func CreateMachine ¶
CreateMachine creates a new machine. If basefolder is empty, use default.
func GetMachine ¶
GetMachine finds a machine by its name or UUID. DEPRECATED: Use (*Manager).Machine
func ListMachines ¶
ListMachines lists all registered machines. DEPRECATED: Use (*Manager).ListMachines
func (*Machine) AddNATPF ¶
AddNATPF adds a NAT port forarding rule to the n-th NIC with the given name.
func (*Machine) AddStorageCtl ¶
func (m *Machine) AddStorageCtl(name string, ctl StorageController) error
AddStorageCtl adds a storage controller with the given name.
func (*Machine) AttachStorage ¶
func (m *Machine) AttachStorage(ctlName string, medium StorageMedium) error
AttachStorage attaches a storage medium to the named storage controller.
func (*Machine) DelNATPF ¶
DelNATPF deletes the NAT port forwarding rule with the given name from the n-th NIC.
func (*Machine) DelStorageCtl ¶
DelStorageCtl deletes the storage controller with the given name.
func (*Machine) DeleteExtraData ¶
DeleteExtraData removes custom string from the VM.
func (*Machine) DisconnectSerialPort ¶
DisconnectSerialPort sets given serial port to disconnected.
func (*Machine) GetExtraData ¶
GetExtraData retrieves custom string from the VM.
func (*Machine) Modify ¶
Modify changes the settings of the machine. DEPRECATED: Use (*Manager).ModifyMachine
func (*Machine) Poweroff ¶
Poweroff forcefully stops the machine. State is lost and might corrupt the disk image.
func (*Machine) Reset ¶
Reset forcefully restarts the machine. State is lost and might corrupt the disk image.
func (*Machine) SetExtraData ¶
SetExtraData attaches custom string to the VM.
type MachineManager ¶
type MachineManager interface { // Machine gets a machine name based on its name or UUID Machine(context.Context, string) (*Machine, error) // ListMachines returns a list of all machines ListMachines(context.Context) ([]*Machine, error) // ModifyMachine allows to update the machine. ModifyMachine(context.Context, *Machine) error // CreateMachine based on the provided information CreateMachine(context.Context, *Machine) error // Start the machine with the given name StartMachine(context.Context, string) error // DeleteMachine deletes a machine by its name or UUID DeleteMachine(context.Context, string) error }
MachineManager defines the actions that can be performed to manage machines
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager of the virtualbox instance.
func NewManager ¶
NewManager returns a manager capable of managing everything in virtualbox.
func (*Manager) ListMachines ¶
ListMachines returns the list of the machines
func (*Manager) Machine ¶
Machine returns the information about existing virtualbox machine identified by either its UUID or name.
func (*Manager) ModifyMachine ¶
ModifyMachine modifies the data of the machine
type MockCommand ¶
type MockCommand struct {
// contains filtered or unexported fields
}
MockCommand is a mock of Command interface.
func NewMockCommand ¶
func NewMockCommand(ctrl *gomock.Controller) *MockCommand
NewMockCommand creates a new mock instance.
func (*MockCommand) EXPECT ¶
func (m *MockCommand) EXPECT() *MockCommandMockRecorder
EXPECT returns an object that allows the caller to indicate expected use.
type MockCommandMockRecorder ¶
type MockCommandMockRecorder struct {
// contains filtered or unexported fields
}
MockCommandMockRecorder is the mock recorder for MockCommand.
type NIC ¶
type NIC struct { Network NICNetwork Hardware NICHardware HostInterface string // The host interface name to bind to in 'hostonly' and 'bridged' mode MacAddr string }
NIC represents a virtualized network interface card.
type PFRule ¶
type PFRule struct { Proto PFProto HostIP net.IP // can be nil to match any host interface GuestIP net.IP // can be nil if guest IP is leased from built-in DHCP HostPort uint16 GuestPort uint16 }
PFRule represents a port forwarding rule.
type StorageController ¶
type StorageController struct { SysBus SystemBus Ports uint // SATA port count 1--30 Chipset StorageControllerChipset HostIOCache bool Bootable bool }
StorageController represents a virtualized storage controller.
type StorageControllerChipset ¶
type StorageControllerChipset string
StorageControllerChipset represents the hardware of a storage controller.
type StorageMedium ¶
type StorageMedium struct { Port uint Device uint DriveType DriveType Medium string // none|emptydrive|<uuid>|<filename|host:<drive>|iscsi }
StorageMedium represents the storage medium attached to a storage controller.
type Virtualbox ¶
type Virtualbox interface { MachineManager }
Virtualbox interface defines all the actions which can be performed by the Manager. This is mostly a utility interface designed for the customers of the package.