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