virtualbox

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2020 License: Apache-2.0 Imports: 17 Imported by: 5

README

go-virtualbox

This is a wrapper package for Golang to interact with VirtualBox. The API is experimental at the moment and you should expect frequent changes.

Table of Contents

  1. Status
  2. Usage
    1. Library
    2. Commands
    3. Documentation
  3. Building
  4. Testing
    1. Preparation
    2. Run tests
    3. Re-generate mock
  5. Caveats

Status

Project Status Notes
Github Actions Continuous Integration
Go Report Card Go Report Card scan code with gofmt, go vet, gocyclo, golint, ineffassign, license and misspell.
GoDoc Go Doc
Release Release

Usage

Library

The part of the library that manages guest properties can run both from the Host and the Guest.

    err := virtualbox.SetGuestProperty("MyVM", "test_key", "test_val")
    val, err := GetGuestProperty(VM, "test_key")

See GoDoc for full details.

Commands

The vbhostd commands waits on the vbhostd/* guest-properties pattern.

  • When the guest writes a value on the vbhostd/open, it causes the host to open the given location:
    • Write http://www.hp.com will open the default browser as the given URL
    • Write mailto:foo@bar.com?Cc=bar@foo.com opens the default mailer pre-filling the recipient and carbon-copy recipient fields
Documentation

For the released version, see GoDoc:terra-farm/go-virtualbox. To see the local documentation, run godoc -http=:6060 & and then open http://localhost:6060/pkg/github.com/terra-farm/go-virtualbox/.

Building

First install dependencies

  • GoLang
  • GNU Make (Windows: via `choco install -y gnuwin32-make.portable)

Get Go dependencies: make deps or:

$ go get -v github.com/golang/dep/cmd/dep
$ dep ensure -v

Then build: make build or:

$ go build -v ./...
  • default run everything in order
  • deps install dependencies (dep and others)
  • build run go build ./...
  • test run go test ./...
  • lint only run gometalinter linter

Testing

Preparation

Tests run using mocked interfaces, unless the TEST_VM environment variable is set, in order to test against real VirtualBox. You either need to have a pre-provisioned VirtualBox VM and to set its name using the TEST_VM environment variable, or use Vagrant.

$ vagrant box add bento/ubuntu-16.04
# select virtualbox as provider

$ vagrant up

Then run the tests

$ export TEST_VM=go-virtualbox
$ go test

...or (on Windows):

> set TEST_VM=go-virtualbox
> go test

Once you are done with testing, run vagrant halt to same resources.

Run tests

As usual, run go test, or go test -v. To run one test in particular, run go test --run TestGuestProperty.

Re-generate mock
mockgen -source=vbcmd.go -destination=mockvbcmd_test.go -package=virtualbox -mock_names=Command=MockCommand

Using local changes with your own project

If you have a project which depends on this library, you probably want to test your local changes of go-virtualbox in your project. See this article on how to set up your environment to do this.

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).

Index

Examples

Constants

View Source
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")
)
View Source
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")
)
View Source
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")
)
View Source
const (
	// PFTCP when forwarding a TCP port.
	PFTCP = PFProto("tcp")
	// PFUDP when forwarding an UDP port.
	PFUDP = PFProto("udp")
)
View Source
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")
)
View Source
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")
)
View Source
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

View Source
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")
)
View Source
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

func AddHostonlyDHCP(ifname string, d DHCP) error

AddHostonlyDHCP adds a DHCP server to a host-only network.

func AddInternalDHCP

func AddInternalDHCP(netname string, d DHCP) error

AddInternalDHCP adds a DHCP server to an internal network.

func CloneHD

func CloneHD(input, output string) error

CloneHD virtual harddrive

func CloneMachine added in v0.0.2

func CloneMachine(baseImageName string, newImageName string, register bool) error

CloneMachine clones the given machine name into a new one.

func DHCPs

func DHCPs() (map[string]*DHCP, error)

DHCPs gets all DHCP server settings in a map keyed by DHCP.NetworkName.

func DelExtra

func DelExtra(name, key string) error

DelExtra deletes extra data. Name could be "global"|<uuid>|<vmname>

func DeleteGuestProperty added in v0.0.2

func DeleteGuestProperty(vm string, prop string) error

DeleteGuestProperty deletes a VirtualBox guestproperty.

Example
package main

import (
	virtualbox "github.com/terra-farm/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 added in v0.0.2

func GetGuestProperty(vm string, prop string) (string, error)

GetGuestProperty reads a VirtualBox guestproperty.

Example
package main

import (
	"log"

	virtualbox "github.com/terra-farm/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 ImportOV added in v0.0.2

func ImportOV(path string) error

ImportOV imports ova or ovf from the given path

func MakeDiskImage

func MakeDiskImage(dest string, size uint, r io.Reader) error

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 NATNets

func NATNets() (map[string]NATNet, error)

NATNets gets all NAT networks in a map keyed by NATNet.Name.

func ParseIPv4Mask

func ParseIPv4Mask(s string) net.IPMask

ParseIPv4Mask parses IPv4 netmask written in IP form (e.g. 255.255.255.0). This function should really belong to the net package.

func SetExtra

func SetExtra(name, key, val string) error

SetExtra sets extra data. Name could be "global"|<uuid>|<vmname>

func SetGuestProperty added in v0.0.2

func SetGuestProperty(vm string, prop string, val string) error

SetGuestProperty writes a VirtualBox guestproperty to the given value.

Example
package main

import (
	virtualbox "github.com/terra-farm/go-virtualbox"
)

var VM = "MyVM"

func main() {
	err := virtualbox.SetGuestProperty(VM, "test_name", "test_val")
	if err != nil {
		panic(err)
	}
}
Output:

func WaitGuestProperties added in v0.0.2

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/terra-farm/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 added in v0.0.2

func WaitGuestProperty(vm string, prop string) (string, string, error)

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/terra-farm/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:

func ZeroFill

func ZeroFill(w io.Writer, n int64) error

ZeroFill writes n zero bytes into w.

Types

type Command added in v0.0.2

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)

func Manage added in v0.0.2

func Manage() Command

Manage returns the Command to run VBoxManage/VBoxControl.

type DHCP

type DHCP struct {
	NetworkName string
	IPv4        net.IPNet
	LowerIP     net.IP
	UpperIP     net.IP
	Enabled     bool
}

DHCP server info.

type DriveType

type DriveType string

DriveType represents the hardware type of a drive.

type Flag

type Flag int

Flag is an active VM configuration toggle

const (
	ACPI Flag = 1 << iota
	IOAPIC
	RTCUSEUTC
	CPUHOTPLUG
	PAE
	LONGMODE
	SYNTHCPU
	HPET
	HWVIRTEX
	TRIPLEFAULTRESET
	NESTEDPAGING
	LARGEPAGES
	VTXVPID
	VTXUX
	ACCELERATE3D
)

Flag names in lowercases to be consistent with VBoxManage options.

func (Flag) Get

func (f Flag) Get(o Flag) string

Get tests if flag is set. Return "on" or "off".

type GuestProperty added in v0.0.2

type GuestProperty struct {
	Name  string
	Value string
}

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 added in v0.0.2

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
	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

func CreateMachine(name, basefolder string) (*Machine, error)

CreateMachine creates a new machine. If basefolder is empty, use default.

func GetMachine

func GetMachine(id string) (*Machine, error)

GetMachine finds a machine by its name or UUID.

func ListMachines

func ListMachines() ([]*Machine, error)

ListMachines lists all registered machines.

func New

func New() *Machine

New creates a new machine.

func (*Machine) AddNATPF

func (m *Machine) AddNATPF(n int, name string, rule PFRule) error

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

func (m *Machine) DelNATPF(n int, name string) error

DelNATPF deletes the NAT port forwarding rule with the given name from the n-th NIC.

func (*Machine) DelStorageCtl

func (m *Machine) DelStorageCtl(name string) error

DelStorageCtl deletes the storage controller with the given name.

func (*Machine) Delete

func (m *Machine) Delete() error

Delete deletes the machine and associated disk images.

func (*Machine) DeleteExtraData

func (m *Machine) DeleteExtraData(key string) error

DeleteExtraData removes custom string from the VM.

func (*Machine) DisconnectSerialPort added in v0.0.2

func (m *Machine) DisconnectSerialPort(portNumber int) error

DisconnectSerialPort sets given serial port to disconnected.

func (*Machine) GetExtraData

func (m *Machine) GetExtraData(key string) (*string, error)

GetExtraData retrieves custom string from the VM.

func (*Machine) Modify

func (m *Machine) Modify() error

Modify changes the settings of the machine.

func (*Machine) Pause

func (m *Machine) Pause() error

Pause pauses the execution of the machine.

func (*Machine) Poweroff

func (m *Machine) Poweroff() error

Poweroff forcefully stops the machine. State is lost and might corrupt the disk image.

func (*Machine) Refresh

func (m *Machine) Refresh() error

Refresh reloads the machine information.

func (*Machine) Reset

func (m *Machine) Reset() error

Reset forcefully restarts the machine. State is lost and might corrupt the disk image.

func (*Machine) Restart

func (m *Machine) Restart() error

Restart gracefully restarts the machine.

func (*Machine) Save

func (m *Machine) Save() error

Save suspends the machine and saves its state to disk.

func (*Machine) SetExtraData

func (m *Machine) SetExtraData(key, val string) error

SetExtraData attaches custom string to the VM.

func (*Machine) SetNIC

func (m *Machine) SetNIC(n int, nic NIC) error

SetNIC set the n-th NIC.

func (*Machine) Start

func (m *Machine) Start() error

Start starts the machine.

func (*Machine) Stop

func (m *Machine) Stop() error

Stop gracefully stops the machine.

type MachineState

type MachineState string

MachineState stores the last retrieved VM state.

type NATNet

type NATNet struct {
	Name    string
	IPv4    net.IPNet
	IPv6    net.IPNet
	DHCP    bool
	Enabled bool
}

A NATNet defines a NAT network.

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 NICHardware

type NICHardware string

NICHardware represents the type of NIC hardware.

type NICNetwork

type NICNetwork string

NICNetwork represents the type of NIC networks.

type PFProto

type PFProto string

PFProto represents the protocol of a port forwarding rule.

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.

func (PFRule) Format

func (r PFRule) Format() string

Format returns the string needed as a command-line argument to VBoxManage.

func (PFRule) String

func (r PFRule) String() string

String returns a human-friendly representation of the 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 SystemBus

type SystemBus string

SystemBus represents the system bus of a storage controller.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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