summaryrefslogtreecommitdiff
path: root/vendor/github.com/mitchellh/packer/builder/profitbricks/step_take_snapshot.go
blob: 822ea869968599eddc6977a1f52eaf8aed7cfec1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package profitbricks

import (
	"encoding/json"
	"time"

	"github.com/hashicorp/packer/packer"
	"github.com/mitchellh/multistep"
	"github.com/profitbricks/profitbricks-sdk-go"
)

type stepTakeSnapshot struct{}

func (s *stepTakeSnapshot) Run(state multistep.StateBag) multistep.StepAction {
	ui := state.Get("ui").(packer.Ui)
	c := state.Get("config").(*Config)

	ui.Say("Creating ProfitBricks snapshot...")

	profitbricks.SetAuth(c.PBUsername, c.PBPassword)

	dcId := state.Get("datacenter_id").(string)
	volumeId := state.Get("volume_id").(string)

	snapshot := profitbricks.CreateSnapshot(dcId, volumeId, c.SnapshotName, "")

	state.Put("snapshotname", c.SnapshotName)

	if snapshot.StatusCode > 299 {
		var restError RestError
		if err := json.Unmarshal([]byte(snapshot.Response), &restError); err != nil {
			ui.Error(err.Error())
			return multistep.ActionHalt
		}
		if len(restError.Messages) > 0 {
			ui.Error(restError.Messages[0].Message)
		} else {
			ui.Error(snapshot.Response)
		}

		return multistep.ActionHalt
	}

	s.waitTillProvisioned(snapshot.Headers.Get("Location"), *c)

	return multistep.ActionContinue
}

func (s *stepTakeSnapshot) Cleanup(state multistep.StateBag) {
}

func (d *stepTakeSnapshot) waitTillProvisioned(path string, config Config) {
	d.setPB(config.PBUsername, config.PBPassword, config.PBUrl)
	waitCount := 50
	if config.Retries > 0 {
		waitCount = config.Retries
	}
	for i := 0; i < waitCount; i++ {
		request := profitbricks.GetRequestStatus(path)
		if request.Metadata.Status == "DONE" {
			break
		}
		time.Sleep(10 * time.Second)
		i++
	}
}

func (d *stepTakeSnapshot) setPB(username string, password string, url string) {
	profitbricks.SetAuth(username, password)
	profitbricks.SetEndpoint(url)
}