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

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