github.com/sneal/packer@v0.5.2/builder/openstack/step_run_source_server.go (about)

     1  package openstack
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/mitchellh/multistep"
     6  	"github.com/mitchellh/packer/packer"
     7  	"github.com/rackspace/gophercloud"
     8  	"log"
     9  )
    10  
    11  type StepRunSourceServer struct {
    12  	Flavor      string
    13  	Name        string
    14  	SourceImage string
    15  
    16  	server *gophercloud.Server
    17  }
    18  
    19  func (s *StepRunSourceServer) Run(state multistep.StateBag) multistep.StepAction {
    20  	csp := state.Get("csp").(gophercloud.CloudServersProvider)
    21  	keyName := state.Get("keyPair").(string)
    22  	ui := state.Get("ui").(packer.Ui)
    23  
    24  	// XXX - validate image and flavor is available
    25  
    26  	server := gophercloud.NewServer{
    27  		Name:        s.Name,
    28  		ImageRef:    s.SourceImage,
    29  		FlavorRef:   s.Flavor,
    30  		KeyPairName: keyName,
    31  	}
    32  
    33  	serverResp, err := csp.CreateServer(server)
    34  	if err != nil {
    35  		err := fmt.Errorf("Error launching source server: %s", err)
    36  		state.Put("error", err)
    37  		ui.Error(err.Error())
    38  		return multistep.ActionHalt
    39  	}
    40  
    41  	s.server, err = csp.ServerById(serverResp.Id)
    42  	log.Printf("server id: %s", s.server.Id)
    43  
    44  	ui.Say(fmt.Sprintf("Waiting for server (%s) to become ready...", s.server.Id))
    45  	stateChange := StateChangeConf{
    46  		Pending:   []string{"BUILD"},
    47  		Target:    "ACTIVE",
    48  		Refresh:   ServerStateRefreshFunc(csp, s.server),
    49  		StepState: state,
    50  	}
    51  	latestServer, err := WaitForState(&stateChange)
    52  	if err != nil {
    53  		err := fmt.Errorf("Error waiting for server (%s) to become ready: %s", s.server.Id, err)
    54  		state.Put("error", err)
    55  		ui.Error(err.Error())
    56  		return multistep.ActionHalt
    57  	}
    58  
    59  	s.server = latestServer.(*gophercloud.Server)
    60  	state.Put("server", s.server)
    61  
    62  	return multistep.ActionContinue
    63  }
    64  
    65  func (s *StepRunSourceServer) Cleanup(state multistep.StateBag) {
    66  	if s.server == nil {
    67  		return
    68  	}
    69  
    70  	csp := state.Get("csp").(gophercloud.CloudServersProvider)
    71  	ui := state.Get("ui").(packer.Ui)
    72  
    73  	ui.Say("Terminating the source server...")
    74  	if err := csp.DeleteServerById(s.server.Id); err != nil {
    75  		ui.Error(fmt.Sprintf("Error terminating server, may still be around: %s", err))
    76  		return
    77  	}
    78  
    79  	stateChange := StateChangeConf{
    80  		Pending: []string{"ACTIVE", "BUILD", "REBUILD", "SUSPENDED"},
    81  		Refresh: ServerStateRefreshFunc(csp, s.server),
    82  		Target:  "DELETED",
    83  	}
    84  
    85  	WaitForState(&stateChange)
    86  }