github.com/alouche/packer@v0.3.7/builder/virtualbox/step_run.go (about)

     1  package virtualbox
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/mitchellh/multistep"
     6  	"github.com/mitchellh/packer/packer"
     7  	"time"
     8  )
     9  
    10  // This step starts the virtual machine.
    11  //
    12  // Uses:
    13  //
    14  // Produces:
    15  type stepRun struct {
    16  	vmName string
    17  }
    18  
    19  func (s *stepRun) Run(state multistep.StateBag) multistep.StepAction {
    20  	config := state.Get("config").(*config)
    21  	driver := state.Get("driver").(Driver)
    22  	ui := state.Get("ui").(packer.Ui)
    23  	vmName := state.Get("vmName").(string)
    24  
    25  	ui.Say("Starting the virtual machine...")
    26  	guiArgument := "gui"
    27  	if config.Headless == true {
    28  		ui.Message("WARNING: The VM will be started in headless mode, as configured.\n" +
    29  			"In headless mode, errors during the boot sequence or OS setup\n" +
    30  			"won't be easily visible. Use at your own discretion.")
    31  		guiArgument = "headless"
    32  	}
    33  	command := []string{"startvm", vmName, "--type", guiArgument}
    34  	if err := driver.VBoxManage(command...); err != nil {
    35  		err := fmt.Errorf("Error starting VM: %s", err)
    36  		state.Put("error", err)
    37  		ui.Error(err.Error())
    38  		return multistep.ActionHalt
    39  	}
    40  
    41  	s.vmName = vmName
    42  
    43  	if int64(config.bootWait) > 0 {
    44  		ui.Say(fmt.Sprintf("Waiting %s for boot...", config.bootWait))
    45  		time.Sleep(config.bootWait)
    46  	}
    47  
    48  	return multistep.ActionContinue
    49  }
    50  
    51  func (s *stepRun) Cleanup(state multistep.StateBag) {
    52  	if s.vmName == "" {
    53  		return
    54  	}
    55  
    56  	driver := state.Get("driver").(Driver)
    57  	ui := state.Get("ui").(packer.Ui)
    58  
    59  	if running, _ := driver.IsRunning(s.vmName); running {
    60  		if err := driver.VBoxManage("controlvm", s.vmName, "poweroff"); err != nil {
    61  			ui.Error(fmt.Sprintf("Error shutting down VM: %s", err))
    62  		}
    63  	}
    64  }