packer-plugin-xenserver/builder/xenserver/common/step_attach_vdi.go

84 lines
2.0 KiB
Go
Raw Normal View History

package common
import (
"fmt"
2020-09-13 03:21:07 -05:00
"log"
"github.com/mitchellh/multistep"
"github.com/mitchellh/packer/packer"
2020-09-13 03:21:07 -05:00
xsclient "github.com/terra-farm/go-xen-api-client"
)
type StepAttachVdi struct {
VdiUuidKey string
2020-09-13 03:21:07 -05:00
VdiType xsclient.VbdType
2020-09-13 03:21:07 -05:00
vdi xsclient.VDIRef
}
func (self *StepAttachVdi) Run(state multistep.StateBag) multistep.StepAction {
ui := state.Get("ui").(packer.Ui)
2020-09-13 03:21:07 -05:00
c := state.Get("client").(*Connection)
var vdiUuid string
if vdiUuidRaw, ok := state.GetOk(self.VdiUuidKey); ok {
vdiUuid = vdiUuidRaw.(string)
} else {
log.Printf("Skipping attach of '%s'", self.VdiUuidKey)
return multistep.ActionContinue
}
var err error
2020-09-13 03:21:07 -05:00
self.vdi, err = c.client.VDI.GetByUUID(c.session, vdiUuid)
if err != nil {
ui.Error(fmt.Sprintf("Unable to get VDI from UUID '%s': %s", vdiUuid, err.Error()))
return multistep.ActionHalt
}
uuid := state.Get("instance_uuid").(string)
2020-09-13 03:21:07 -05:00
instance, err := c.client.VM.GetByUUID(c.session, uuid)
if err != nil {
ui.Error(fmt.Sprintf("Unable to get VM from UUID '%s': %s", uuid, err.Error()))
return multistep.ActionHalt
}
2020-09-13 03:21:07 -05:00
err = ConnectVdi(c, instance, self.vdi, self.VdiType)
if err != nil {
ui.Error(fmt.Sprintf("Error attaching VDI '%s': '%s'", vdiUuid, err.Error()))
return multistep.ActionHalt
}
log.Printf("Attached VDI '%s'", vdiUuid)
return multistep.ActionContinue
}
func (self *StepAttachVdi) Cleanup(state multistep.StateBag) {
config := state.Get("commonconfig").(CommonConfig)
2020-09-13 03:21:07 -05:00
c := state.Get("client").(*Connection)
if config.ShouldKeepVM(state) {
return
}
2020-09-13 03:21:07 -05:00
// TODO: What the fuck does this mean?
if self.vdi == "" {
return
}
uuid := state.Get("instance_uuid").(string)
2020-09-13 03:21:07 -05:00
vmRef, err := c.client.VM.GetByUUID(c.session, uuid)
if err != nil {
log.Printf("Unable to get VM from UUID '%s': %s", uuid, err.Error())
return
}
vdiUuid := state.Get(self.VdiUuidKey).(string)
2020-09-13 03:21:07 -05:00
err = DisconnectVdi(c, vmRef, self.vdi)
if err != nil {
log.Printf("Unable to disconnect VDI '%s': %s", vdiUuid, err.Error())
return
}
log.Printf("Detached VDI '%s'", vdiUuid)
}