github.com/sneal/packer@v0.5.2/builder/virtualbox/common/driver.go (about)

     1  package common
     2  
     3  import (
     4  	"log"
     5  	"os"
     6  	"os/exec"
     7  	"path/filepath"
     8  	"runtime"
     9  	"strings"
    10  )
    11  
    12  // A driver is able to talk to VirtualBox and perform certain
    13  // operations with it. Some of the operations on here may seem overly
    14  // specific, but they were built specifically in mind to handle features
    15  // of the VirtualBox builder for Packer, and to abstract differences in
    16  // versions out of the builder steps, so sometimes the methods are
    17  // extremely specific.
    18  type Driver interface {
    19  	// Create a SATA controller.
    20  	CreateSATAController(vm string, controller string) error
    21  
    22  	// Delete a VM by name
    23  	Delete(string) error
    24  
    25  	// Import a VM
    26  	Import(string, string, string) error
    27  
    28  	// Checks if the VM with the given name is running.
    29  	IsRunning(string) (bool, error)
    30  
    31  	// Stop stops a running machine, forcefully.
    32  	Stop(string) error
    33  
    34  	// SuppressMessages should do what needs to be done in order to
    35  	// suppress any annoying popups from VirtualBox.
    36  	SuppressMessages() error
    37  
    38  	// VBoxManage executes the given VBoxManage command
    39  	VBoxManage(...string) error
    40  
    41  	// Verify checks to make sure that this driver should function
    42  	// properly. If there is any indication the driver can't function,
    43  	// this will return an error.
    44  	Verify() error
    45  
    46  	// Version reads the version of VirtualBox that is installed.
    47  	Version() (string, error)
    48  }
    49  
    50  func NewDriver() (Driver, error) {
    51  	var vboxmanagePath string
    52  
    53  	// On Windows, we check VBOX_INSTALL_PATH env var for the path
    54  	if runtime.GOOS == "windows" {
    55  		if installPath := os.Getenv("VBOX_INSTALL_PATH"); installPath != "" {
    56  			log.Printf("[DEBUG] builder/virtualbox: VBOX_INSTALL_PATH: %s",
    57  				installPath)
    58  			for _, path := range strings.Split(installPath, ";") {
    59  				path = filepath.Join(path, "VBoxManage.exe")
    60  				if _, err := os.Stat(path); err == nil {
    61  					vboxmanagePath = path
    62  					break
    63  				}
    64  			}
    65  		}
    66  	}
    67  
    68  	if vboxmanagePath == "" {
    69  		var err error
    70  		vboxmanagePath, err = exec.LookPath("VBoxManage")
    71  		if err != nil {
    72  			return nil, err
    73  		}
    74  	}
    75  
    76  	log.Printf("VBoxManage path: %s", vboxmanagePath)
    77  	driver := &VBox42Driver{vboxmanagePath}
    78  	if err := driver.Verify(); err != nil {
    79  		return nil, err
    80  	}
    81  
    82  	return driver, nil
    83  }