packer-cn/builder/ucloud/uhost/step_stop_instance.go

81 lines
2.2 KiB
Go
Raw Normal View History

2019-06-13 03:16:49 -04:00
package uhost
import (
"context"
"fmt"
"github.com/hashicorp/packer/common/retry"
"time"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
"github.com/ucloud/ucloud-sdk-go/services/uhost"
"github.com/ucloud/ucloud-sdk-go/ucloud"
)
type stepStopInstance struct {
}
func (s *stepStopInstance) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
client := state.Get("client").(*UCloudClient)
conn := client.uhostconn
instance := state.Get("instance").(*uhost.UHostInstanceSet)
ui := state.Get("ui").(packer.Ui)
instance, err := client.describeUHostById(instance.UHostId)
if err != nil {
2019-06-19 09:32:33 -04:00
return halt(state, err, fmt.Sprintf("Error on reading instance when stopping %q", instance.UHostId))
2019-06-13 03:16:49 -04:00
}
2019-06-13 08:17:08 -04:00
if instance.State != instanceStateStopped {
2019-07-26 05:03:57 -04:00
stopReq := conn.NewStopUHostInstanceRequest()
2019-06-13 03:16:49 -04:00
stopReq.UHostId = ucloud.String(instance.UHostId)
ui.Say(fmt.Sprintf("Stopping instance %q", instance.UHostId))
err = retry.Config{
Tries: 5,
ShouldRetry: func(err error) bool {
return err != nil
},
RetryDelay: (&retry.Backoff{InitialBackoff: 2 * time.Second, MaxBackoff: 6 * time.Second, Multiplier: 2}).Linear,
}.Run(ctx, func(ctx context.Context) error {
2019-07-26 05:03:57 -04:00
if _, err = conn.StopUHostInstance(stopReq); err != nil {
2019-06-13 03:16:49 -04:00
return err
}
return nil
})
if err != nil {
return halt(state, err, fmt.Sprintf("Error on stopping instance %q", instance.UHostId))
}
err = retry.Config{
Tries: 20,
ShouldRetry: func(err error) bool {
return isExpectedStateError(err)
},
RetryDelay: (&retry.Backoff{InitialBackoff: 2 * time.Second, MaxBackoff: 6 * time.Second, Multiplier: 2}).Linear,
}.Run(ctx, func(ctx context.Context) error {
instance, err := client.describeUHostById(instance.UHostId)
if err != nil {
return err
}
2019-06-13 08:17:08 -04:00
if instance.State != instanceStateStopped {
2019-06-13 03:16:49 -04:00
return newExpectedStateError("instance", instance.UHostId)
}
return nil
})
if err != nil {
2019-06-19 09:32:33 -04:00
return halt(state, err, fmt.Sprintf("Error on waiting for stopping instance when stopping %q", instance.UHostId))
2019-06-13 03:16:49 -04:00
}
2019-06-19 09:32:33 -04:00
ui.Message(fmt.Sprintf("Stopping instance %q complete", instance.UHostId))
2019-06-13 03:16:49 -04:00
}
return multistep.ActionContinue
}
func (s *stepStopInstance) Cleanup(multistep.StateBag) {
}