2013-07-20 22:58:27 -04:00
|
|
|
package common
|
2013-05-21 03:55:32 -04:00
|
|
|
|
|
|
|
import (
|
2013-07-25 21:49:15 -04:00
|
|
|
"errors"
|
2013-05-21 03:55:32 -04:00
|
|
|
"fmt"
|
|
|
|
"github.com/mitchellh/goamz/ec2"
|
2013-07-25 21:49:15 -04:00
|
|
|
"github.com/mitchellh/multistep"
|
2013-05-21 03:55:32 -04:00
|
|
|
"log"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2013-07-25 21:49:15 -04:00
|
|
|
type StateChangeConf struct {
|
|
|
|
Conn *ec2.EC2
|
|
|
|
Pending []string
|
2013-07-29 21:47:43 -04:00
|
|
|
Refresh func() (interface{}, string, error)
|
2013-07-25 21:49:15 -04:00
|
|
|
StepState map[string]interface{}
|
|
|
|
Target string
|
|
|
|
}
|
|
|
|
|
2013-07-29 21:47:43 -04:00
|
|
|
func InstanceStateRefreshFunc(conn *ec2.EC2, i *ec2.Instance) func() (interface{}, string, error) {
|
|
|
|
return func() (interface{}, string, error) {
|
|
|
|
resp, err := conn.Instances([]string{i.InstanceId}, ec2.NewFilter())
|
|
|
|
if err != nil {
|
|
|
|
return nil, "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
i = &resp.Reservations[0].Instances[0]
|
|
|
|
return i, i.State.Name, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func WaitForState(conf *StateChangeConf) (i interface{}, err error) {
|
2013-07-25 21:49:15 -04:00
|
|
|
log.Printf("Waiting for instance state to become: %s", conf.Target)
|
|
|
|
|
2013-07-29 21:47:43 -04:00
|
|
|
for {
|
|
|
|
var currentState string
|
|
|
|
i, currentState, err = conf.Refresh()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if currentState == conf.Target {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-07-25 21:49:15 -04:00
|
|
|
if conf.StepState != nil {
|
|
|
|
if _, ok := conf.StepState[multistep.StateCancelled]; ok {
|
|
|
|
return nil, errors.New("interrupted")
|
|
|
|
}
|
|
|
|
}
|
2013-05-21 03:55:32 -04:00
|
|
|
|
2013-06-04 14:29:59 -04:00
|
|
|
found := false
|
2013-07-25 21:49:15 -04:00
|
|
|
for _, allowed := range conf.Pending {
|
2013-07-29 21:47:43 -04:00
|
|
|
if currentState == allowed {
|
2013-06-04 14:29:59 -04:00
|
|
|
found = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if !found {
|
2013-07-29 21:47:43 -04:00
|
|
|
fmt.Errorf("unexpected state '%s', wanted target '%s'", currentState, conf.Target)
|
2013-06-04 14:29:59 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-05-21 03:55:32 -04:00
|
|
|
time.Sleep(2 * time.Second)
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|