forked from aws/amazon-ecs-agent
/
taskmetadata-validator.go
313 lines (264 loc) · 9.03 KB
/
taskmetadata-validator.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"time"
"github.com/docker/docker/api/types"
)
const (
v2MetadataEndpoint = "http://169.254.170.2/v2/metadata"
v2MetadataWithTagsEndpoint = "http://169.254.170.2/v2/metadataWithTags"
v2StatsEndpoint = "http://169.254.170.2/v2/stats"
maxRetries = 4
durationBetweenRetries = time.Second
)
// TaskResponse defines the schema for the task response JSON object
type TaskResponse struct {
Cluster string
TaskARN string
Family string
Revision string
DesiredStatus string `json:",omitempty"`
KnownStatus string
AvailabilityZone string
Containers []ContainerResponse `json:",omitempty"`
Limits LimitsResponse `json:",omitempty"`
TaskTags map[string]string `json:"TaskTags,omitempty"`
ContainerInstanceTags map[string]string `json:"ContainerInstanceTags,omitempty"`
}
// ContainerResponse defines the schema for the container response
// JSON object
type ContainerResponse struct {
ID string `json:"DockerId"`
Name string
DockerName string
Image string
ImageID string
Ports []PortResponse `json:",omitempty"`
Labels map[string]string `json:",omitempty"`
DesiredStatus string
KnownStatus string
ExitCode *int `json:",omitempty"`
Limits LimitsResponse
CreatedAt *time.Time `json:",omitempty"`
StartedAt *time.Time `json:",omitempty"`
FinishedAt *time.Time `json:",omitempty"`
Type string
Health HealthStatus `json:"health,omitempty"`
Networks []Network `json:",omitempty"`
Volumes []VolumeResponse `json:"Volumes,omitempty"`
}
type HealthStatus struct {
Status string `json:"status,omitempty"`
Since *time.Time `json:"statusSince,omitempty"`
ExitCode int `json:"exitCode,omitempty"`
Output string `json:"output,omitempty"`
}
// LimitsResponse defines the schema for task/cpu limits response
// JSON object
type LimitsResponse struct {
CPU uint
Memory uint
}
// PortResponse defines the schema for portmapping response JSON
// object
type PortResponse struct {
ContainerPort uint16
Protocol string
HostPort uint16 `json:",omitempty"`
}
// Network is a struct that keeps track of metadata of a network interface
type Network struct {
NetworkMode string `json:"NetworkMode,omitempty"`
IPv4Addresses []string `json:"IPv4Addresses,omitempty"`
IPv6Addresses []string `json:"IPv6Addresses,omitempty"`
}
// VolumeResponse is the schema for the volume response JSON object
type VolumeResponse struct {
DockerName string `json:"DockerName,omitempty"`
Source string `json:"Source,omitempty"`
Destination string `json:"Destination,omitempty"`
}
func taskMetadata(client *http.Client) (*TaskResponse, error) {
body, err := metadataResponse(client, v2MetadataEndpoint, "task metadata")
if err != nil {
return nil, err
}
fmt.Printf("Received task metadata: %s \n", string(body))
var taskMetadata TaskResponse
err = json.Unmarshal(body, &taskMetadata)
if err != nil {
return nil, fmt.Errorf("task metadata: unable to parse response body: %v", err)
}
return &taskMetadata, nil
}
func taskWithTagsMetadata(client *http.Client) (*TaskResponse, error) {
body, err := metadataResponse(client, v2MetadataWithTagsEndpoint, "task with tags metadata")
if err != nil {
return nil, err
}
fmt.Printf("Received task with tags metadata: %s \n", string(body))
var taskMetadata TaskResponse
err = json.Unmarshal(body, &taskMetadata)
if err != nil {
return nil, fmt.Errorf("task with tags metadata: unable to parse response body: %v", err)
}
return &taskMetadata, nil
}
func containerMetadata(client *http.Client, id string) (*ContainerResponse, error) {
body, err := metadataResponse(client, v2MetadataEndpoint+"/"+id, "container metadata")
if err != nil {
return nil, err
}
fmt.Printf("Received container metadata: %s \n", string(body))
var containerMetadata ContainerResponse
err = json.Unmarshal(body, &containerMetadata)
if err != nil {
return nil, fmt.Errorf("container metadata: unable to parse response body: %v", err)
}
return &containerMetadata, nil
}
func taskStats(client *http.Client) (map[string]*types.StatsJSON, error) {
body, err := metadataResponse(client, v2StatsEndpoint, "task stats")
if err != nil {
return nil, err
}
fmt.Printf("Received task stats: %s \n", string(body))
var taskStats map[string]*types.StatsJSON
err = json.Unmarshal(body, &taskStats)
if err != nil {
return nil, fmt.Errorf("task stats: unable to parse response body: %v", err)
}
return taskStats, nil
}
func containerStats(client *http.Client, id string) (*types.StatsJSON, error) {
body, err := metadataResponse(client, v2StatsEndpoint+"/"+id, "container stats")
if err != nil {
return nil, err
}
fmt.Printf("Received container stats: %s \n", string(body))
var containerStats types.StatsJSON
err = json.Unmarshal(body, &containerStats)
if err != nil {
return nil, fmt.Errorf("container stats: unable to parse response body: %v", err)
}
return &containerStats, nil
}
func metadataResponse(client *http.Client, endpoint string, respType string) ([]byte, error) {
var resp []byte
var err error
for i := 0; i < maxRetries; i++ {
resp, err = metadataResponseOnce(client, endpoint, respType)
if err == nil {
return resp, nil
}
fmt.Fprintf(os.Stderr, "Attempt [%d/%d]: unable to get metadata response for '%s' from '%s': %v",
i, maxRetries, respType, endpoint, err)
time.Sleep(durationBetweenRetries)
}
return nil, err
}
func metadataResponseOnce(client *http.Client, endpoint string, respType string) ([]byte, error) {
resp, err := client.Get(endpoint)
if err != nil {
return nil, fmt.Errorf("%s: unable to get response: %v", respType, err)
}
if resp.Body != nil {
defer resp.Body.Close()
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s: incorrect status code %d", respType, resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("task metadata: unable to read response body: %v", err)
}
return body, nil
}
func main() {
client := &http.Client{
Timeout: 5 * time.Second,
}
// Wait for the Health information to be ready
time.Sleep(5 * time.Second)
// If the image is built with option to check Tags
argsWithoutProg := os.Args[1:]
if len(argsWithoutProg) > 0 && argsWithoutProg[0] == "CheckTags" {
taskWithTagsMetadata, err := taskWithTagsMetadata(client)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to get task stats: %v", err)
os.Exit(1)
}
if len(taskWithTagsMetadata.ContainerInstanceTags) == 0 {
fmt.Fprintf(os.Stderr, "ContainerInstanceTags not found: %v", err)
os.Exit(1)
}
}
taskMetadata, err := taskMetadata(client)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to get task metadata: %v", err)
os.Exit(1)
}
if len(taskMetadata.Containers) != 2 {
fmt.Fprintf(os.Stderr,
"Incorrect number of containers in task metadata response, expected 2: %d [%v]",
len(taskMetadata.Containers), taskMetadata)
os.Exit(1)
}
containerID := ""
for _, container := range taskMetadata.Containers {
if container.Type == "NORMAL" {
containerID = container.ID
break
}
}
if containerID == "" {
fmt.Fprintf(os.Stderr, "Container from task definition not found")
os.Exit(1)
}
containerMetadata, err := containerMetadata(client, containerID)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to get container metadata for '%s': %v", containerID, err)
os.Exit(1)
}
if containerMetadata.Health.Status != "" { // if the health status is available
if containerMetadata.Health.Status != "HEALTHY" || containerMetadata.Health.Output != "hello\n" {
fmt.Fprintf(os.Stderr, "Container health metadata unexpected, got: %s\n", containerMetadata.Health)
os.Exit(1)
}
}
if containerMetadata.Volumes == nil {
fmt.Fprintf(os.Stderr, "Expected container volume metadata to be non-empty")
os.Exit(1)
}
if containerMetadata.Volumes[0].DockerName != "shared-local" || containerMetadata.Volumes[0].Destination != "/ecs" {
fmt.Fprintf(os.Stderr, "Volume metadata fields incorrect")
os.Exit(1)
}
_, err = taskStats(client)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to get task stats: %v", err)
os.Exit(1)
}
_, err = containerStats(client, containerID)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to get container stats for '%s': %v", containerID, err)
os.Exit(1)
}
os.Exit(42)
}