/
awsutil.go
193 lines (167 loc) · 5.45 KB
/
awsutil.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package awsutil
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"runtime"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ecs"
"github.com/hashicorp/consul-ecs/version"
)
const (
ECSMetadataURIEnvVar = "ECS_CONTAINER_METADATA_URI_V4"
AWSRegionEnvVar = "AWS_REGION"
// This is the type assigned to the containers that are
// present in the task definition.
containerTypeNormal = "NORMAL"
)
type ECSTaskMeta struct {
Cluster string `json:"Cluster"`
TaskARN string `json:"TaskARN"`
Family string `json:"Family"`
Containers []ECSTaskMetaContainer `json:"Containers"`
AvailabilityZone string `json:"AvailabilityZone"`
}
type ECSTaskMetaContainer struct {
Name string `json:"Name"`
Health ECSTaskMetaHealth `json:"Health"`
DesiredStatus string `json:"DesiredStatus"`
KnownStatus string `json:"KnownStatus"`
Networks []ECSTaskMetaNetwork `json:"Networks"`
Type string `json:"Type"`
}
type ECSTaskMetaHealth struct {
Status string `json:"status"`
StatusSince string `json:"statusSince"`
ExitCode int `json:"exitCode"`
}
type ECSTaskMetaNetwork struct {
IPv4Addresses []string `json:"IPv4Addresses"`
PrivateDNSName string `json:"PrivateDNSName"`
}
func (e ECSTaskMeta) TaskID() string {
return ParseTaskID(e.TaskARN)
}
func (e ECSTaskMeta) ClusterARN() (string, error) {
if strings.HasPrefix(e.Cluster, "arn:") {
return e.Cluster, nil
}
// On EC2, the "Cluster" field is the name, not the ARN.
clusterArn := strings.Replace(e.TaskARN, ":task/", ":cluster/", 1)
index := strings.LastIndex(clusterArn, "/")
if index < 0 {
return "", fmt.Errorf("unable to determine cluster ARN from task ARN %q", e.TaskARN)
}
return clusterArn[:index], nil
}
func ParseTaskID(taskArn string) string {
split := strings.Split(taskArn, "/")
if len(split) == 0 {
return ""
}
return split[len(split)-1]
}
func (e ECSTaskMeta) AccountID() (string, error) {
a, err := arn.Parse(e.TaskARN)
if err != nil {
return "", fmt.Errorf("unable to determine AWS account id from Task ARN: %q", e.TaskARN)
}
return a.AccountID, nil
}
func (e ECSTaskMeta) Region() (string, error) {
// Task ARN: "arn:aws:ecs:us-east-1:000000000000:task/cluster/00000000000000000000000000000000"
// https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html
// See also: https://github.com/aws/containers-roadmap/issues/337
a, err := arn.Parse(e.TaskARN)
if err != nil {
return "", fmt.Errorf("unable to determine AWS region from Task ARN: %q", e.TaskARN)
}
return a.Region, nil
}
// NodeIP returns the IP of the node the task is running on.
func (e ECSTaskMeta) NodeIP() string {
ip := "127.0.0.1" // default to localhost
if len(e.Containers) > 0 &&
len(e.Containers[0].Networks) > 0 &&
len(e.Containers[0].Networks[0].IPv4Addresses) > 0 {
ip = e.Containers[0].Networks[0].IPv4Addresses[0]
}
return ip
}
func (e ECSTaskMeta) HasContainerStopped(name string) bool {
stopped := true
for _, c := range e.Containers {
if c.Name == name && !c.HasStopped() {
stopped = false
break
}
}
return stopped
}
func (c ECSTaskMetaContainer) HasStopped() bool {
return c.DesiredStatus == ecs.DesiredStatusStopped &&
c.KnownStatus == ecs.DesiredStatusStopped
}
func (c ECSTaskMetaContainer) IsNormalType() bool {
return c.Type == containerTypeNormal
}
func ECSTaskMetadata() (ECSTaskMeta, error) {
var metadataResp ECSTaskMeta
metadataURI := os.Getenv(ECSMetadataURIEnvVar)
if metadataURI == "" {
return metadataResp, fmt.Errorf("%s env var not set", ECSMetadataURIEnvVar)
}
resp, err := http.Get(fmt.Sprintf("%s/task", metadataURI))
if err != nil {
return metadataResp, fmt.Errorf("calling metadata uri: %s", err)
}
respBytes, err := io.ReadAll(resp.Body)
if err != nil {
return metadataResp, fmt.Errorf("reading metadata uri response body: %s", err)
}
if err := json.Unmarshal(respBytes, &metadataResp); err != nil {
return metadataResp, fmt.Errorf("unmarshalling metadata uri response: %s", err)
}
return metadataResp, nil
}
func UserAgentHandler(caller string) request.NamedHandler {
return request.NamedHandler{
Name: "UserAgentHandler",
Fn: func(r *request.Request) {
userAgent := r.HTTPRequest.Header.Get("User-Agent")
r.HTTPRequest.Header.Set("User-Agent",
fmt.Sprintf("consul-ecs-%s/%s (%s) %s", caller, version.Version, runtime.GOOS, userAgent))
},
}
}
// NewSession prepares a client session.
// The returned session includes a User-Agent handler to enable AWS to track usage.
// If the AWS SDK fails to find the region, the region is parsed from Task metadata
// (on EC2 the region is not typically defined in the environment).
func NewSession(meta ECSTaskMeta, userAgentCaller string) (*session.Session, error) {
clientSession, err := session.NewSession()
if err != nil {
return nil, err
}
clientSession.Handlers.Build.PushBackNamed(UserAgentHandler(userAgentCaller))
cfg := clientSession.Config
if cfg.Region == nil || *cfg.Region == "" {
region, err := meta.Region()
if err != nil {
return nil, err
}
cfg.Region = aws.String(region)
}
return clientSession, nil
}
func GetAWSRegion() string {
return os.Getenv(AWSRegionEnvVar)
}