forked from convox/rack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
instances.go
199 lines (163 loc) · 4.9 KB
/
instances.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
package aws
import (
"fmt"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ecs"
"github.com/convox/rack/api/structs"
)
func (p *AWSProvider) InstanceList() (structs.Instances, error) {
ecsRes, err := p.describeContainerInstances()
var instanceIds []*string
for _, i := range ecsRes.ContainerInstances {
instanceIds = append(instanceIds, i.Ec2InstanceId)
}
ec2Res, err := p.ec2().DescribeInstances(&ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
{Name: aws.String("instance-id"), Values: instanceIds},
},
MaxResults: aws.Int64(1000),
})
if err != nil {
return nil, err
}
ec2Instances := make(map[string]*ec2.Instance)
ec2Metrics := make(map[string]float64)
// collect instance data from EC2, and CPU Utilization from CloudWatch Metrics
for _, r := range ec2Res.Reservations {
for _, i := range r.Instances {
ec2Instances[*i.InstanceId] = i
ec2Metrics[*i.InstanceId] = 0.0
res, err := p.cloudwatch().GetMetricStatistics(&cloudwatch.GetMetricStatisticsInput{
Dimensions: []*cloudwatch.Dimension{
{Name: aws.String("InstanceId"), Value: i.InstanceId},
},
EndTime: aws.Time(time.Now()),
MetricName: aws.String("CPUUtilization"),
Namespace: aws.String("AWS/EC2"),
Period: aws.Int64(5 * 60), // seconds
StartTime: aws.Time(time.Now().Add(time.Duration(-5) * time.Minute)),
Statistics: []*string{aws.String("Average")},
})
if err != nil {
continue
}
if len(res.Datapoints) > 0 {
ec2Metrics[*i.InstanceId] = *res.Datapoints[0].Average / 100.0
}
}
}
var instances structs.Instances
// Calculate memory metrics from ECS DescribeContainerInstances
// We can not collect CPU metrics since we are not yet using ECS CPU reservations
for _, i := range ecsRes.ContainerInstances {
var memory structs.InstanceResource
for _, r := range i.RegisteredResources {
switch *r.Name {
case "MEMORY":
memory.Total = int(*r.IntegerValue)
}
}
for _, r := range i.RemainingResources {
switch *r.Name {
case "MEMORY":
memory.Free = int(*r.IntegerValue)
memory.Used = memory.Total - memory.Free
}
}
// find the matching Instance from the EC2 response
ec2Instance := ec2Instances[*i.Ec2InstanceId]
// build up the struct
instance := structs.Instance{
Cpu: ec2Metrics[*i.Ec2InstanceId],
Memory: memory.PercentUsed(),
Id: *i.Ec2InstanceId,
}
if i.AgentConnected != nil {
instance.Agent = *i.AgentConnected
}
if ec2Instance != nil {
if ec2Instance.PrivateIpAddress != nil {
instance.PrivateIp = *ec2Instance.PrivateIpAddress
}
if ec2Instance.PublicIpAddress != nil {
instance.PublicIp = *ec2Instance.PublicIpAddress
}
if ec2Instance.LaunchTime != nil {
instance.Started = *ec2Instance.LaunchTime
}
}
if i.RunningTasksCount != nil {
instance.Processes = int(*i.RunningTasksCount)
}
if i.Status != nil {
instance.Status = strings.ToLower(*i.Status)
}
instances = append(instances, instance)
}
return instances, nil
}
func (p *AWSProvider) InstanceTerminate(id string) error {
instances, err := p.InstanceList()
if err != nil {
return err
}
found := false
for _, i := range instances {
if i.Id == id {
found = true
break
}
}
if !found {
return fmt.Errorf("no such instance: %s", id)
}
_, err = p.autoscaling().TerminateInstanceInAutoScalingGroup(&autoscaling.TerminateInstanceInAutoScalingGroupInput{
InstanceId: aws.String(id),
ShouldDecrementDesiredCapacity: aws.Bool(false),
})
if err != nil {
return err
}
return nil
}
// describeContainerInstances lists and describes all the ECS instances.
// It handles pagination for clusters > 100 instances.
func (p *AWSProvider) describeContainerInstances() (*ecs.DescribeContainerInstancesOutput, error) {
instances := []*ecs.ContainerInstance{}
var nextToken string
for {
res, err := p.listContainerInstances(&ecs.ListContainerInstancesInput{
Cluster: aws.String(p.Cluster),
NextToken: &nextToken,
})
if ae, ok := err.(awserr.Error); ok && ae.Code() == "ClusterNotFoundException" {
return nil, errorNotFound(fmt.Sprintf("cluster not found: %s", p.Cluster))
}
if err != nil {
return nil, err
}
dres, err := p.ecs().DescribeContainerInstances(&ecs.DescribeContainerInstancesInput{
Cluster: aws.String(p.Cluster),
ContainerInstances: res.ContainerInstanceArns,
})
if err != nil {
return nil, err
}
instances = append(instances, dres.ContainerInstances...)
// No more container results
if res.NextToken == nil {
break
}
// set the nextToken to be used for the next iteration
nextToken = *res.NextToken
}
return &ecs.DescribeContainerInstancesOutput{
ContainerInstances: instances,
}, nil
}