-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
64 lines (57 loc) · 1.45 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main
import (
"encoding/json"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ecs"
"io/ioutil"
"log"
"net/http"
"time"
)
type ECSMetadata struct {
Cluster string `json:"Cluster"`
ContainerInstanceArn string `json:"ContainerInstanceArn"`
}
func main() {
client := &http.Client{Timeout: time.Second * 10}
for {
time.Sleep(5 * time.Second)
response, err := client.Get("http://169.254.169.254/latest/meta-data/spot/termination-time")
if err != nil {
panic(err)
}
if response.StatusCode == 200 {
log.Print("Spot instance termination notice detected")
break
}
}
response, err := client.Get("http://localhost:51678/v1/metadata")
if err != nil {
panic(err)
}
buf, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
}
var ecsMetadata ECSMetadata
err = json.Unmarshal(buf, &ecsMetadata)
if err != nil {
panic(err)
}
svc := ecs.New(session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
})))
status := "DRAINING"
state := &ecs.UpdateContainerInstancesStateInput{
Cluster: &ecsMetadata.Cluster,
ContainerInstances: []*string{&ecsMetadata.ContainerInstanceArn},
Status: &status,
}
log.Print("Putting instance in state DRAINING")
_, err = svc.UpdateContainerInstancesState(state)
if err != nil {
panic(err)
}
log.Print("Sleeping for 120s until termination")
time.Sleep(120 * time.Second)
}