packer-cn/builder/hyperv/common/step_run.go

61 lines
1.3 KiB
Go
Raw Normal View History

package common
import (
"context"
"fmt"
"github.com/hashicorp/packer/helper/multistep"
2017-04-04 16:39:01 -04:00
"github.com/hashicorp/packer/packer"
)
type StepRun struct {
Headless bool
vmName string
}
func (s *StepRun) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
vmName := state.Get("vmName").(string)
ui.Say("Starting the virtual machine...")
err := driver.Start(vmName)
if err != nil {
err := fmt.Errorf("Error starting vm: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
s.vmName = vmName
if !s.Headless {
ui.Say("Connecting to vmconnect...")
cancel := driver.Connect(vmName)
state.Put("guiCancelFunc", cancel)
}
return multistep.ActionContinue
}
func (s *StepRun) Cleanup(state multistep.StateBag) {
if s.vmName == "" {
return
}
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
guiCancelFunc := state.Get("guiCancelFunc").(context.CancelFunc)
if guiCancelFunc != nil {
ui.Say("Disconnecting from vmconnect...")
guiCancelFunc()
}
if running, _ := driver.IsRunning(s.vmName); running {
if err := driver.Stop(s.vmName); err != nil {
ui.Error(fmt.Sprintf("Error shutting down VM: %s", err))
}
}
}