-
Notifications
You must be signed in to change notification settings - Fork 119
/
docker.go
219 lines (195 loc) · 5.85 KB
/
docker.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
// Copyright 2015-2016 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 docker
import (
"io"
"strings"
"github.com/aws/amazon-ecs-init/ecs-init/config"
log "github.com/cihub/seelog"
godocker "github.com/fsouza/go-dockerclient"
)
const (
logDir = "/log"
dataDir = "/data"
readOnly = ":ro"
// set default to /var/run instead of /var/run/docker.sock in case
// /var/run/docker.sock is deleted and recreated outside the container
defaultDockerEndpoint = "/var/run"
// networkMode specifies the networkmode to create the agent container
networkMode = "host"
)
// Client enables business logic for running the Agent inside Docker
type Client struct {
docker dockerclient
fs fileSystem
}
// NewClient reutrns a new Client
func NewClient() (*Client, error) {
client, err := newDockerClient()
if err != nil {
return nil, err
}
return &Client{
docker: client,
fs: standardFS,
}, nil
}
// IsAgentImageLoaded returns true if the Agent image is loaded in Docker
func (c *Client) IsAgentImageLoaded() (bool, error) {
images, err := c.docker.ListImages(godocker.ListImagesOptions{
All: true,
})
if err != nil {
return false, err
}
for _, image := range images {
for _, repoTag := range image.RepoTags {
if repoTag == config.AgentImageName {
return true, nil
}
}
}
return false, nil
}
// LoadImage loads an io.Reader into Docker
func (c *Client) LoadImage(image io.Reader) error {
return c.docker.LoadImage(godocker.LoadImageOptions{image})
}
// RemoveExistingAgentContainer remvoes any existing container named
// "ecs-agent" or returns without error if none is found
func (c *Client) RemoveExistingAgentContainer() error {
containerToRemove, err := c.findAgentContainer()
if err != nil {
return err
}
if containerToRemove == "" {
log.Info("No existing agent container to remove.")
return nil
}
log.Infof("Removing existing agent container ID: %s", containerToRemove)
err = c.docker.RemoveContainer(godocker.RemoveContainerOptions{
ID: containerToRemove,
Force: true,
})
return err
}
func (c *Client) findAgentContainer() (string, error) {
// TODO pagination
containers, err := c.docker.ListContainers(godocker.ListContainersOptions{
All: true,
Filters: map[string][]string{
"status": []string{},
},
})
if err != nil {
return "", err
}
agentContainerName := "/" + config.AgentContainerName
for _, container := range containers {
for _, name := range container.Names {
log.Infof("Container name: %s", name)
if name == agentContainerName {
return container.ID, nil
}
}
}
return "", nil
}
// StartAgent starts the Agent in Docker and returns the exit code from the container
func (c *Client) StartAgent() (int, error) {
container, err := c.docker.CreateContainer(godocker.CreateContainerOptions{
Name: config.AgentContainerName,
Config: c.getContainerConfig(),
HostConfig: c.getHostConfig(),
})
if err != nil {
return 0, err
}
err = c.docker.StartContainer(container.ID, nil)
if err != nil {
return 0, err
}
return c.docker.WaitContainer(container.ID)
}
func (c *Client) getContainerConfig() *godocker.Config {
// default environment variables
envVariables := map[string]string{
"ECS_LOGFILE": logDir + "/" + config.AgentLogFile,
"ECS_DATADIR": dataDir,
"ECS_AGENT_CONFIG_FILE_PATH": config.AgentJSONConfigFile(),
"ECS_UPDATE_DOWNLOAD_DIR": config.CacheDirectory(),
"ECS_UPDATES_ENABLED": "true",
"ECS_AVAILABLE_LOGGING_DRIVERS": `["json-file","syslog","awslogs"]`,
"ECS_ENABLE_TASK_IAM_ROLE": "true",
"ECS_ENABLE_TASK_IAM_ROLE_NETWORK_HOST": "true",
}
// merge in user-supplied environment variables
for envKey, envValue := range c.loadEnvVariables() {
envVariables[envKey] = envValue
}
var env []string
for envKey, envValue := range envVariables {
env = append(env, envKey+"="+envValue)
}
return &godocker.Config{
Env: env,
Image: config.AgentImageName,
}
}
func (c *Client) loadEnvVariables() map[string]string {
envVariables := make(map[string]string)
file, err := c.fs.ReadFile(config.AgentConfigFile())
if err != nil {
return envVariables
}
lines := strings.Split(strings.TrimSpace(string(file)), "\n")
for _, line := range lines {
parts := strings.SplitN(strings.TrimSpace(line), "=", 2)
if len(parts) != 2 {
continue
}
envVariables[parts[0]] = parts[1]
}
return envVariables
}
func (c *Client) getHostConfig() *godocker.HostConfig {
dockerEndpointAgent := defaultDockerEndpoint
dockerUnixSocketSourcePath, fromEnv := config.DockerUnixSocket()
if fromEnv {
dockerEndpointAgent = "/var/run/docker.sock"
}
binds := []string{
dockerUnixSocketSourcePath + ":" + dockerEndpointAgent,
config.LogDirectory() + ":" + logDir,
config.AgentDataDirectory() + ":" + dataDir,
config.AgentConfigDirectory() + ":" + config.AgentConfigDirectory(),
config.CacheDirectory() + ":" + config.CacheDirectory(),
}
return &godocker.HostConfig{
Binds: binds,
NetworkMode: networkMode,
}
}
// StopAgent stops the Agent in docker if one is running
func (c *Client) StopAgent() error {
id, err := c.findAgentContainer()
if err != nil {
return err
}
if id == "" {
log.Info("No running Agent to stop")
return nil
}
stopContainerTimeoutSeconds := uint(10)
return c.docker.StopContainer(id, stopContainerTimeoutSeconds)
}