packer-cn/builder/virtualbox/vm/step_create_snapshot.go

70 lines
2.0 KiB
Go
Raw Normal View History

2019-02-16 08:32:22 -05:00
package vm
import (
"context"
"fmt"
"log"
2019-02-16 08:32:22 -05:00
vboxcommon "github.com/hashicorp/packer/builder/virtualbox/common"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
)
type StepCreateSnapshot struct {
Name string
TargetSnapshot string
}
func (s *StepCreateSnapshot) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
driver := state.Get("driver").(vboxcommon.Driver)
ui := state.Get("ui").(packer.Ui)
if s.TargetSnapshot != "" {
running, err := driver.IsRunning(s.Name)
if err != nil {
err = fmt.Errorf("Failed to test if VM %s is still running: %s", s.Name, err)
} else if running {
err = fmt.Errorf("VM %s is still running. Unable to create snapshot %s", s.Name, s.TargetSnapshot)
}
if err != nil {
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
2019-02-16 08:32:22 -05:00
ui.Say(fmt.Sprintf("Creating snapshot %s on virtual machine %s", s.TargetSnapshot, s.Name))
snapshotTree, err := driver.LoadSnapshots(s.Name)
if err != nil {
err = fmt.Errorf("Failed to load snapshots for VM %s: %s", s.Name, err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
currentSnapshot := snapshotTree.GetCurrentSnapshot()
targetSnapshot := currentSnapshot.GetChildWithName(s.TargetSnapshot)
if nil != targetSnapshot {
log.Printf("Deleting existing target snapshot %s", s.TargetSnapshot)
err = driver.DeleteSnapshot(s.Name, targetSnapshot)
if nil != err {
err = fmt.Errorf("Unable to delete snapshot %s from VM %s: %s", s.TargetSnapshot, s.Name, err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
}
err = driver.CreateSnapshot(s.Name, s.TargetSnapshot)
2019-02-16 08:32:22 -05:00
if err != nil {
err := fmt.Errorf("Error creating snaphot VM: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
} else {
ui.Say("No target snapshot defined...")
}
return multistep.ActionContinue
}
func (s *StepCreateSnapshot) Cleanup(state multistep.StateBag) {}