github.phpd.cn/hashicorp/packer@v1.3.2/builder/profitbricks/step_take_snapshot.go (about) 1 package profitbricks 2 3 import ( 4 "context" 5 "encoding/json" 6 "time" 7 8 "github.com/hashicorp/packer/helper/multistep" 9 "github.com/hashicorp/packer/packer" 10 "github.com/profitbricks/profitbricks-sdk-go" 11 ) 12 13 type stepTakeSnapshot struct{} 14 15 func (s *stepTakeSnapshot) Run(_ context.Context, 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 if err := json.Unmarshal([]byte(snapshot.Response), &restError); err != nil { 33 ui.Error(err.Error()) 34 return multistep.ActionHalt 35 } 36 if len(restError.Messages) > 0 { 37 ui.Error(restError.Messages[0].Message) 38 } else { 39 ui.Error(snapshot.Response) 40 } 41 42 return multistep.ActionHalt 43 } 44 45 s.waitTillProvisioned(snapshot.Headers.Get("Location"), *c) 46 47 return multistep.ActionContinue 48 } 49 50 func (s *stepTakeSnapshot) Cleanup(state multistep.StateBag) { 51 } 52 53 func (d *stepTakeSnapshot) waitTillProvisioned(path string, config Config) { 54 d.setPB(config.PBUsername, config.PBPassword, config.PBUrl) 55 waitCount := 50 56 if config.Retries > 0 { 57 waitCount = config.Retries 58 } 59 for i := 0; i < waitCount; i++ { 60 request := profitbricks.GetRequestStatus(path) 61 if request.Metadata.Status == "DONE" { 62 break 63 } 64 time.Sleep(10 * time.Second) 65 i++ 66 } 67 } 68 69 func (d *stepTakeSnapshot) setPB(username string, password string, url string) { 70 profitbricks.SetAuth(username, password) 71 profitbricks.SetEndpoint(url) 72 }