github.com/rahart/packer@v0.12.2-0.20161229105310-282bb6ad370f/builder/parallels/common/step_run.go (about)

     1  package common
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  
     7  	"github.com/mitchellh/multistep"
     8  	"github.com/mitchellh/packer/packer"
     9  )
    10  
    11  // StepRun is a step that starts the virtual machine.
    12  //
    13  // Uses:
    14  //   driver Driver
    15  //   ui packer.Ui
    16  //   vmName string
    17  //
    18  // Produces:
    19  type StepRun struct {
    20  	BootWait time.Duration
    21  
    22  	vmName string
    23  }
    24  
    25  // Run starts the VM.
    26  func (s *StepRun) Run(state multistep.StateBag) multistep.StepAction {
    27  	driver := state.Get("driver").(Driver)
    28  	ui := state.Get("ui").(packer.Ui)
    29  	vmName := state.Get("vmName").(string)
    30  
    31  	ui.Say("Starting the virtual machine...")
    32  	command := []string{"start", vmName}
    33  	if err := driver.Prlctl(command...); err != nil {
    34  		err = fmt.Errorf("Error starting VM: %s", err)
    35  		state.Put("error", err)
    36  		ui.Error(err.Error())
    37  		return multistep.ActionHalt
    38  	}
    39  
    40  	s.vmName = vmName
    41  
    42  	if int64(s.BootWait) > 0 {
    43  		ui.Say(fmt.Sprintf("Waiting %s for boot...", s.BootWait))
    44  		wait := time.After(s.BootWait)
    45  	WAITLOOP:
    46  		for {
    47  			select {
    48  			case <-wait:
    49  				break WAITLOOP
    50  			case <-time.After(1 * time.Second):
    51  				if _, ok := state.GetOk(multistep.StateCancelled); ok {
    52  					return multistep.ActionHalt
    53  				}
    54  			}
    55  		}
    56  	}
    57  
    58  	return multistep.ActionContinue
    59  }
    60  
    61  // Cleanup stops the VM.
    62  func (s *StepRun) Cleanup(state multistep.StateBag) {
    63  	if s.vmName == "" {
    64  		return
    65  	}
    66  
    67  	driver := state.Get("driver").(Driver)
    68  	ui := state.Get("ui").(packer.Ui)
    69  
    70  	if running, _ := driver.IsRunning(s.vmName); running {
    71  		if err := driver.Prlctl("stop", s.vmName); err != nil {
    72  			ui.Error(fmt.Sprintf("Error stopping VM: %s", err))
    73  		}
    74  	}
    75  }