github.com/mmcquillan/packer@v1.1.1-0.20171009221028-c85cf0483a5d/builder/profitbricks/step_take_snapshot.go (about) 1 package profitbricks 2 3 import ( 4 "encoding/json" 5 "time" 6 7 "github.com/hashicorp/packer/packer" 8 "github.com/mitchellh/multistep" 9 "github.com/profitbricks/profitbricks-sdk-go" 10 ) 11 12 type stepTakeSnapshot struct{} 13 14 func (s *stepTakeSnapshot) Run(state multistep.StateBag) multistep.StepAction { 15 ui := state.Get("ui").(packer.Ui) 16 c := state.Get("config").(*Config) 17 18 ui.Say("Creating ProfitBricks snapshot...") 19 20 profitbricks.SetAuth(c.PBUsername, c.PBPassword) 21 22 dcId := state.Get("datacenter_id").(string) 23 volumeId := state.Get("volume_id").(string) 24 25 snapshot := profitbricks.CreateSnapshot(dcId, volumeId, c.SnapshotName, "") 26 27 state.Put("snapshotname", c.SnapshotName) 28 29 if snapshot.StatusCode > 299 { 30 var restError RestError 31 if err := json.Unmarshal([]byte(snapshot.Response), &restError); err != nil { 32 ui.Error(err.Error()) 33 return multistep.ActionHalt 34 } 35 if len(restError.Messages) > 0 { 36 ui.Error(restError.Messages[0].Message) 37 } else { 38 ui.Error(snapshot.Response) 39 } 40 41 return multistep.ActionHalt 42 } 43 44 s.waitTillProvisioned(snapshot.Headers.Get("Location"), *c) 45 46 return multistep.ActionContinue 47 } 48 49 func (s *stepTakeSnapshot) Cleanup(state multistep.StateBag) { 50 } 51 52 func (d *stepTakeSnapshot) waitTillProvisioned(path string, config Config) { 53 d.setPB(config.PBUsername, config.PBPassword, config.PBUrl) 54 waitCount := 50 55 if config.Retries > 0 { 56 waitCount = config.Retries 57 } 58 for i := 0; i < waitCount; i++ { 59 request := profitbricks.GetRequestStatus(path) 60 if request.Metadata.Status == "DONE" { 61 break 62 } 63 time.Sleep(10 * time.Second) 64 i++ 65 } 66 } 67 68 func (d *stepTakeSnapshot) setPB(username string, password string, url string) { 69 profitbricks.SetAuth(username, password) 70 profitbricks.SetEndpoint(url) 71 }