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

     1  package vmware
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/mitchellh/multistep"
     6  	"github.com/mitchellh/packer/packer"
     7  	"time"
     8  )
     9  
    10  // This step runs the created virtual machine.
    11  //
    12  // Uses:
    13  //   config *config
    14  //   driver Driver
    15  //   ui     packer.Ui
    16  //   vmx_path string
    17  //
    18  // Produces:
    19  //   <nothing>
    20  type stepRun struct {
    21  	bootTime time.Time
    22  	vmxPath  string
    23  }
    24  
    25  func (s *stepRun) Run(state multistep.StateBag) multistep.StepAction {
    26  	config := state.Get("config").(*config)
    27  	driver := state.Get("driver").(Driver)
    28  	ui := state.Get("ui").(packer.Ui)
    29  	vmxPath := state.Get("vmx_path").(string)
    30  	vncPort := state.Get("vnc_port").(uint)
    31  
    32  	// Set the VMX path so that we know we started the machine
    33  	s.bootTime = time.Now()
    34  	s.vmxPath = vmxPath
    35  
    36  	ui.Say("Starting virtual machine...")
    37  	if config.Headless {
    38  		ui.Message(fmt.Sprintf(
    39  			"The VM will be run headless, without a GUI. If you want to\n"+
    40  				"view the screen of the VM, connect via VNC without a password to\n"+
    41  				"127.0.0.1:%d", vncPort))
    42  	}
    43  
    44  	if err := driver.Start(vmxPath, config.Headless); err != nil {
    45  		err := fmt.Errorf("Error starting VM: %s", err)
    46  		state.Put("error", err)
    47  		ui.Error(err.Error())
    48  		return multistep.ActionHalt
    49  	}
    50  
    51  	// Wait the wait amount
    52  	if int64(config.bootWait) > 0 {
    53  		ui.Say(fmt.Sprintf("Waiting %s for boot...", config.bootWait.String()))
    54  		time.Sleep(config.bootWait)
    55  	}
    56  
    57  	return multistep.ActionContinue
    58  }
    59  
    60  func (s *stepRun) Cleanup(state multistep.StateBag) {
    61  	driver := state.Get("driver").(Driver)
    62  	ui := state.Get("ui").(packer.Ui)
    63  
    64  	// If we started the machine... stop it.
    65  	if s.vmxPath != "" {
    66  		// If we started it less than 5 seconds ago... wait.
    67  		sinceBootTime := time.Since(s.bootTime)
    68  		waitBootTime := 5 * time.Second
    69  		if sinceBootTime < waitBootTime {
    70  			sleepTime := waitBootTime - sinceBootTime
    71  			ui.Say(fmt.Sprintf("Waiting %s to give VMware time to clean up...", sleepTime.String()))
    72  			time.Sleep(sleepTime)
    73  		}
    74  
    75  		// See if it is running
    76  		running, _ := driver.IsRunning(s.vmxPath)
    77  		if running {
    78  			ui.Say("Stopping virtual machine...")
    79  			if err := driver.Stop(s.vmxPath); err != nil {
    80  				ui.Error(fmt.Sprintf("Error stopping VM: %s", err))
    81  			}
    82  		}
    83  	}
    84  }