packer-cn/builder/vsphere/common/step_shutdown.go

82 lines
1.9 KiB
Go
Raw Normal View History

//go:generate struct-markdown
//go:generate mapstructure-to-hcl2 -type ShutdownConfig
package common
import (
2018-10-31 17:42:24 -04:00
"bytes"
"context"
"fmt"
"log"
"time"
"github.com/hashicorp/packer/builder/vsphere/driver"
2018-04-25 07:22:38 -04:00
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
)
2017-07-01 20:06:02 -04:00
type ShutdownConfig struct {
// Specify a VM guest shutdown command. VMware guest tools are used by
// default.
Command string `mapstructure:"shutdown_command"`
// Amount of time to wait for graceful VM shutdown. Examples 45s and 10m.
// Defaults to 5m(5 minutes).
2019-07-12 04:29:41 -04:00
Timeout time.Duration `mapstructure:"shutdown_timeout"`
2017-07-01 20:06:02 -04:00
}
func (c *ShutdownConfig) Prepare() []error {
var errs []error
2019-07-12 04:29:41 -04:00
if c.Timeout == 0 {
2017-07-01 20:06:02 -04:00
c.Timeout = 5 * time.Minute
}
2019-07-12 04:29:41 -04:00
return errs
2017-07-01 20:06:02 -04:00
}
type StepShutdown struct {
Config *ShutdownConfig
}
2018-05-16 09:05:08 -04:00
func (s *StepShutdown) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
ui := state.Get("ui").(packer.Ui)
2017-07-02 08:27:52 -04:00
comm := state.Get("communicator").(packer.Communicator)
2017-08-23 20:06:50 -04:00
vm := state.Get("vm").(*driver.VirtualMachine)
if s.Config.Command != "" {
2017-07-02 08:27:52 -04:00
ui.Say("Executing shutdown command...")
log.Printf("Shutdown command: %s", s.Config.Command)
var stdout, stderr bytes.Buffer
cmd := &packer.RemoteCmd{
Command: s.Config.Command,
Stdout: &stdout,
Stderr: &stderr,
}
err := comm.Start(ctx, cmd)
2017-07-02 16:29:50 -04:00
if err != nil {
2017-07-01 20:06:02 -04:00
state.Put("error", fmt.Errorf("Failed to send shutdown command: %s", err))
return multistep.ActionHalt
}
} else {
2017-07-02 08:27:52 -04:00
ui.Say("Shut down VM...")
2017-08-23 20:06:50 -04:00
err := vm.StartShutdown()
if err != nil {
2017-07-01 20:06:02 -04:00
state.Put("error", fmt.Errorf("Cannot shut down VM: %v", err))
return multistep.ActionHalt
}
}
log.Printf("Waiting max %s for shutdown to complete", s.Config.Timeout)
2018-05-16 09:05:08 -04:00
err := vm.WaitForShutdown(ctx, s.Config.Timeout)
2017-07-02 08:27:52 -04:00
if err != nil {
state.Put("error", err)
return multistep.ActionHalt
}
return multistep.ActionContinue
}
func (s *StepShutdown) Cleanup(state multistep.StateBag) {}