forked from aws/amazon-ecs-agent
/
agent.go
508 lines (450 loc) · 18.9 KB
/
agent.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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
// Copyright 2014-2017 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 app
import (
"errors"
"fmt"
"golang.org/x/net/context"
acshandler "github.com/aws/amazon-ecs-agent/agent/acs/handler"
"github.com/aws/amazon-ecs-agent/agent/api"
"github.com/aws/amazon-ecs-agent/agent/api/ecsclient"
"github.com/aws/amazon-ecs-agent/agent/app/factory"
"github.com/aws/amazon-ecs-agent/agent/app/oswrapper"
"github.com/aws/amazon-ecs-agent/agent/config"
"github.com/aws/amazon-ecs-agent/agent/credentials"
"github.com/aws/amazon-ecs-agent/agent/ec2"
"github.com/aws/amazon-ecs-agent/agent/ecs_client/model/ecs"
"github.com/aws/amazon-ecs-agent/agent/ecscni"
"github.com/aws/amazon-ecs-agent/agent/engine"
"github.com/aws/amazon-ecs-agent/agent/engine/dockerclient"
"github.com/aws/amazon-ecs-agent/agent/engine/dockerstate"
"github.com/aws/amazon-ecs-agent/agent/eni/pause"
"github.com/aws/amazon-ecs-agent/agent/eventhandler"
"github.com/aws/amazon-ecs-agent/agent/eventstream"
"github.com/aws/amazon-ecs-agent/agent/handlers"
credentialshandler "github.com/aws/amazon-ecs-agent/agent/handlers/credentials"
"github.com/aws/amazon-ecs-agent/agent/sighandlers"
"github.com/aws/amazon-ecs-agent/agent/sighandlers/exitcodes"
"github.com/aws/amazon-ecs-agent/agent/statemanager"
"github.com/aws/amazon-ecs-agent/agent/tcs/handler"
"github.com/aws/amazon-ecs-agent/agent/utils"
"github.com/aws/amazon-ecs-agent/agent/version"
"github.com/aws/aws-sdk-go/aws"
aws_credentials "github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/defaults"
"github.com/cihub/seelog"
)
const (
containerChangeEventStreamName = "ContainerChange"
deregisterContainerInstanceEventStreamName = "DeregisterContainerInstance"
clusterMismatchErrorFormat = "Data mismatch; saved cluster '%v' does not match configured cluster '%v'. Perhaps you want to delete the configured checkpoint file?"
instanceIDMismatchErrorFormat = "Data mismatch; saved InstanceID '%s' does not match current InstanceID '%s'. Overwriting old datafile"
instanceTypeMismatchErrorFormat = "The current instance type does not match the registered instance type. Please revert the instance type change, or alternatively launch a new instance: %v"
vpcIDAttributeName = "ecs.vpc-id"
subnetIDAttributeName = "ecs.subnet-id"
)
var (
instanceNotLaunchedInVPCError = errors.New("instance not launched in VPC")
)
// agent interface is used by the app runner to interact with the ecsAgent
// object. Its purpose is to mostly demonstrate how to interact with the
// ecsAgent type.
type agent interface {
// printVersion prints the Agent version string
printVersion() int
// start starts the Agent execution
start() int
}
// ecsAgent wraps all the entities needed to start the ECS Agent execution.
// after creating it via
// the newAgent() method
type ecsAgent struct {
ctx context.Context
ec2MetadataClient ec2.EC2MetadataClient
cfg *config.Config
dockerClient engine.DockerClient
containerInstanceARN string
credentialProvider *aws_credentials.Credentials
stateManagerFactory factory.StateManager
saveableOptionFactory factory.SaveableOption
pauseLoader pause.Loader
cniClient ecscni.CNIClient
os oswrapper.OS
vpc string
subnet string
mac string
}
// newAgent returns a new ecsAgent object
func newAgent(
ctx context.Context,
blackholeEC2Metadata bool,
acceptInsecureCert *bool) (agent, error) {
ec2MetadataClient := ec2.NewEC2MetadataClient(nil)
if blackholeEC2Metadata {
ec2MetadataClient = ec2.NewBlackholeEC2MetadataClient()
}
seelog.Info("Loading configuration")
cfg, err := config.NewConfig(ec2MetadataClient)
if err != nil {
// All required config values can be inferred from EC2 Metadata,
// so this error could be transient.
seelog.Criticalf("Error loading config: %v", err)
return nil, err
}
cfg.AcceptInsecureCert = aws.BoolValue(acceptInsecureCert)
if cfg.AcceptInsecureCert {
seelog.Warn("SSL certificate verification disabled. This is not recommended.")
}
seelog.Debugf("Loaded config: %s", cfg.String())
dockerClient, err := engine.NewDockerGoClient(dockerclient.NewFactory(cfg.DockerEndpoint), cfg)
if err != nil {
// This is also non terminal in the current config
seelog.Criticalf("Error creating Docker client: %v", err)
return nil, err
}
return &ecsAgent{
ctx: ctx,
ec2MetadataClient: ec2MetadataClient,
cfg: cfg,
dockerClient: dockerClient,
// We instantiate our own credentialProvider for use in acs/tcs. This tries
// to mimic roughly the way it's instantiated by the SDK for a default
// session.
credentialProvider: defaults.CredChain(defaults.Config(), defaults.Handlers()),
stateManagerFactory: factory.NewStateManager(),
saveableOptionFactory: factory.NewSaveableOption(),
pauseLoader: pause.New(),
cniClient: ecscni.NewClient(&ecscni.Config{
PluginsPath: cfg.CNIPluginsPath,
MinSupportedCNIVersion: config.DefaultMinSupportedCNIVersion,
}),
os: oswrapper.New(),
}, nil
}
// printVersion prints the ECS Agent version string
func (agent *ecsAgent) printVersion() int {
version.PrintVersion(agent.dockerClient)
return exitcodes.ExitSuccess
}
// start starts the ECS Agent
func (agent *ecsAgent) start() int {
sighandlers.StartDebugHandler()
containerChangeEventStream := eventstream.NewEventStream(containerChangeEventStreamName, agent.ctx)
credentialsManager := credentials.NewManager()
state := dockerstate.NewTaskEngineState()
imageManager := engine.NewImageManager(agent.cfg, agent.dockerClient, state)
client := ecsclient.NewECSClient(agent.credentialProvider, agent.cfg, agent.ec2MetadataClient)
return agent.doStart(containerChangeEventStream, credentialsManager, state, imageManager, client)
}
// doStart is the worker invoked by start for starting the ECS Agent. This involves
// initializing the docker task engine, state saver, image manager, credentials
// manager, poll and telemetry sessions, api handler etc
func (agent *ecsAgent) doStart(containerChangeEventStream *eventstream.EventStream,
credentialsManager credentials.Manager,
state dockerstate.TaskEngineState,
imageManager engine.ImageManager,
client api.ECSClient) int {
// Create the task engine
taskEngine, currentEC2InstanceID, err := agent.newTaskEngine(containerChangeEventStream,
credentialsManager, state, imageManager)
if err != nil {
return exitcodes.ExitTerminal
}
// Initialize the state manager
stateManager, err := agent.newStateManager(taskEngine,
&agent.cfg.Cluster, &agent.containerInstanceARN, ¤tEC2InstanceID)
if err != nil {
seelog.Criticalf("Error creating state manager: %v", err)
return exitcodes.ExitTerminal
}
var vpcSubnetAttributes []*ecs.Attribute
// Check if Task ENI is enabled
if agent.cfg.TaskENIEnabled {
err, terminal := agent.initializeTaskENIDependencies(state, taskEngine)
switch err {
case nil:
// No error, we can proceed with the rest of initialization
// Set vpc and subnet id attributes
vpcSubnetAttributes = agent.constructVPCSubnetAttributes()
case instanceNotLaunchedInVPCError:
// We have ascertained that the EC2 Instance is not running in a VPC
// No need to stop the ECS Agent in this case; all we need to do is
// to not update the config to disable the TaskENIEnabled flag and
// move on
seelog.Warnf("Unable to detect VPC ID for the Instance, disabling Task ENI capability: %v", err)
agent.cfg.TaskENIEnabled = false
default:
// Encountered an error initializing dependencies for dealing with
// ENIs for Tasks. Exit with the appropriate error code
seelog.Criticalf("Unable to initialize Task ENI dependencies: %v", err)
if terminal {
return exitcodes.ExitTerminal
}
return exitcodes.ExitError
}
}
// Register the container instance
err = agent.registerContainerInstance(stateManager, client, vpcSubnetAttributes)
if err != nil {
if isTranisent(err) {
return exitcodes.ExitError
}
return exitcodes.ExitTerminal
}
// Begin listening to the docker daemon and saving changes
taskEngine.SetSaver(stateManager)
imageManager.SetSaver(stateManager)
taskEngine.MustInit(agent.ctx)
// Start back ground routines, including the telemetry session
deregisterInstanceEventStream := eventstream.NewEventStream(
deregisterContainerInstanceEventStreamName, agent.ctx)
deregisterInstanceEventStream.StartListening()
taskHandler := eventhandler.NewTaskHandler(stateManager)
agent.startAsyncRoutines(containerChangeEventStream, credentialsManager, imageManager,
taskEngine, stateManager, deregisterInstanceEventStream, client, taskHandler)
// Start the acs session, which should block doStart
return agent.startACSSession(credentialsManager, taskEngine, stateManager,
deregisterInstanceEventStream, client, state, taskHandler)
}
// newTaskEngine creates a new docker task engine object. It tries to load the
// local state if needed, else initializes a new one
func (agent *ecsAgent) newTaskEngine(containerChangeEventStream *eventstream.EventStream,
credentialsManager credentials.Manager,
state dockerstate.TaskEngineState,
imageManager engine.ImageManager) (engine.TaskEngine, string, error) {
containerChangeEventStream.StartListening()
if !agent.cfg.Checkpoint {
seelog.Info("Checkpointing not enabled; a new container instance will be created each time the agent is run")
return engine.NewTaskEngine(agent.cfg, agent.dockerClient,
credentialsManager, containerChangeEventStream, imageManager, state), "", nil
}
// We try to set these values by loading the existing state file first
var previousCluster, previousEC2InstanceID, previousContainerInstanceArn string
previousTaskEngine := engine.NewTaskEngine(agent.cfg, agent.dockerClient,
credentialsManager, containerChangeEventStream, imageManager, state)
// previousState is used to verify that our current runtime configuration is
// compatible with our past configuration as reflected by our state-file
previousState, err := agent.newStateManager(previousTaskEngine, &previousCluster,
&previousContainerInstanceArn, &previousEC2InstanceID)
if err != nil {
seelog.Criticalf("Error creating state manager: %v", err)
return nil, "", err
}
err = previousState.Load()
if err != nil {
seelog.Criticalf("Error loading previously saved state: %v", err)
return nil, "", err
}
currentEC2InstanceID := agent.getEC2InstanceID()
if previousEC2InstanceID != "" && previousEC2InstanceID != currentEC2InstanceID {
seelog.Warnf(instanceIDMismatchErrorFormat,
previousEC2InstanceID, currentEC2InstanceID)
// Reset agent state as a new container instance
state.Reset()
// Reset taskEngine; all the other values are still default
return engine.NewTaskEngine(agent.cfg, agent.dockerClient, credentialsManager,
containerChangeEventStream, imageManager, state), currentEC2InstanceID, nil
}
if previousCluster != "" {
if err := agent.setClusterInConfig(previousCluster); err != nil {
return nil, "", err
}
}
// Use the values we loaded if there's no issue
agent.containerInstanceARN = previousContainerInstanceArn
return previousTaskEngine, currentEC2InstanceID, nil
}
// setClusterInConfig sets the cluster name in the config object based on
// previous state. It returns an error if there's a mismatch between the
// the current cluster name with what's restored from the cluster state
func (agent *ecsAgent) setClusterInConfig(previousCluster string) error {
// TODO Handle default cluster in a sane and unified way across the codebase
configuredCluster := agent.cfg.Cluster
if configuredCluster == "" {
seelog.Debug("Setting cluster to default; none configured")
configuredCluster = config.DefaultClusterName
}
if previousCluster != configuredCluster {
err := clusterMismatchError{
fmt.Errorf(clusterMismatchErrorFormat, previousCluster, configuredCluster),
}
seelog.Criticalf("%v", err)
return err
}
agent.cfg.Cluster = previousCluster
seelog.Infof("Restored cluster '%s'", agent.cfg.Cluster)
return nil
}
// getEC2InstanceID gets the EC2 instance ID from the metadata service
func (agent *ecsAgent) getEC2InstanceID() string {
instanceIdentityDoc, err := agent.ec2MetadataClient.InstanceIdentityDocument()
if err != nil {
seelog.Criticalf(
"Unable to access EC2 Metadata service to determine EC2 ID: %v", err)
return ""
}
return instanceIdentityDoc.InstanceID
}
// newStateManager creates a new state manager object for the task engine.
// Rest of the parameters are pointers and it's expected that all of these
// will be backfilled when state manager's Load() method is invoked
func (agent *ecsAgent) newStateManager(
taskEngine engine.TaskEngine,
cluster *string,
containerInstanceArn *string,
savedInstanceID *string) (statemanager.StateManager, error) {
if !agent.cfg.Checkpoint {
return statemanager.NewNoopStateManager(), nil
}
return agent.stateManagerFactory.NewStateManager(agent.cfg,
statemanager.AddSaveable("TaskEngine", taskEngine),
// This is for making testing easier as we can mock this
agent.saveableOptionFactory.AddSaveable("ContainerInstanceArn",
containerInstanceArn),
agent.saveableOptionFactory.AddSaveable("Cluster", cluster),
// This is for making testing easier as we can mock this
agent.saveableOptionFactory.AddSaveable("EC2InstanceID", savedInstanceID),
)
}
// constructVPCSubnetAttributes returns vpc and subnet IDs of the instance as
// an attribute list
func (agent *ecsAgent) constructVPCSubnetAttributes() []*ecs.Attribute {
return []*ecs.Attribute{
{
Name: aws.String(vpcIDAttributeName),
Value: aws.String(agent.vpc),
},
{
Name: aws.String(subnetIDAttributeName),
Value: aws.String(agent.subnet),
},
}
}
// registerContainerInstance registers the container instance ID for the ECS Agent
func (agent *ecsAgent) registerContainerInstance(
stateManager statemanager.StateManager,
client api.ECSClient,
additionalAttributes []*ecs.Attribute) error {
// Preflight request to make sure they're good
if preflightCreds, err := agent.credentialProvider.Get(); err != nil || preflightCreds.AccessKeyID == "" {
seelog.Warnf("Error getting valid credentials (AKID %s): %v", preflightCreds.AccessKeyID, err)
}
capabilities := append(agent.capabilities(), additionalAttributes...)
if agent.containerInstanceARN != "" {
seelog.Infof("Restored from checkpoint file. I am running as '%s' in cluster '%s'", agent.containerInstanceARN, agent.cfg.Cluster)
return agent.reregisterContainerInstance(client, capabilities)
}
seelog.Info("Registering Instance with ECS")
containerInstanceArn, err := client.RegisterContainerInstance("", capabilities)
if err != nil {
seelog.Errorf("Error registering: %v", err)
if retriable, ok := err.(utils.Retriable); ok && !retriable.Retry() {
return err
}
if _, ok := err.(utils.AttributeError); ok {
seelog.Critical("Instance registration attempt with an invalid attribute")
return err
}
return transientError{err}
}
seelog.Infof("Registration completed successfully. I am running as '%s' in cluster '%s'", containerInstanceArn, agent.cfg.Cluster)
agent.containerInstanceARN = containerInstanceArn
// Save our shiny new containerInstanceArn
stateManager.Save()
return nil
}
// reregisterContainerInstance registers a container instance that has already been
// registered with ECS. This is for cases where the ECS Agent is being restored
// from a check point.
func (agent *ecsAgent) reregisterContainerInstance(client api.ECSClient, capabilities []*ecs.Attribute) error {
_, err := client.RegisterContainerInstance(agent.containerInstanceARN, capabilities)
if err == nil {
return nil
}
seelog.Errorf("Error re-registering: %v", err)
if api.IsInstanceTypeChangedError(err) {
seelog.Criticalf(instanceTypeMismatchErrorFormat, err)
return err
}
if _, ok := err.(utils.AttributeError); ok {
seelog.Critical("Instance re-registration attempt with an invalid attribute")
return err
}
return transientError{err}
}
// startAsyncRoutines starts all of the background methods
func (agent *ecsAgent) startAsyncRoutines(
containerChangeEventStream *eventstream.EventStream,
credentialsManager credentials.Manager,
imageManager engine.ImageManager,
taskEngine engine.TaskEngine,
stateManager statemanager.StateManager,
deregisterInstanceEventStream *eventstream.EventStream,
client api.ECSClient,
taskHandler *eventhandler.TaskHandler) {
// Start of the periodic image cleanup process
if !agent.cfg.ImageCleanupDisabled {
go imageManager.StartImageCleanupProcess(agent.ctx)
}
go sighandlers.StartTerminationHandler(stateManager, taskEngine)
// Agent introspection api
go handlers.ServeHttp(&agent.containerInstanceARN, taskEngine, agent.cfg)
// Start serving the endpoint to fetch IAM Role credentials
go credentialshandler.ServeHTTP(credentialsManager, agent.containerInstanceARN, agent.cfg)
// Start sending events to the backend
go eventhandler.HandleEngineEvents(taskEngine, client, taskHandler)
telemetrySessionParams := tcshandler.TelemetrySessionParams{
CredentialProvider: agent.credentialProvider,
Cfg: agent.cfg,
ContainerInstanceArn: agent.containerInstanceARN,
DeregisterInstanceEventStream: deregisterInstanceEventStream,
ContainerChangeEventStream: containerChangeEventStream,
DockerClient: agent.dockerClient,
ECSClient: client,
TaskEngine: taskEngine,
}
// Start metrics session in a go routine
go tcshandler.StartMetricsSession(telemetrySessionParams)
}
// startACSSession starts a session with ECS's Agent Communication service. This
// is a blocking call and only returns when the handler returns
func (agent *ecsAgent) startACSSession(
credentialsManager credentials.Manager,
taskEngine engine.TaskEngine,
stateManager statemanager.StateManager,
deregisterInstanceEventStream *eventstream.EventStream,
client api.ECSClient,
state dockerstate.TaskEngineState,
taskHandler *eventhandler.TaskHandler) int {
acsSession := acshandler.NewSession(
agent.ctx,
agent.cfg,
deregisterInstanceEventStream,
agent.containerInstanceARN,
agent.credentialProvider,
client,
state,
stateManager,
taskEngine,
credentialsManager,
taskHandler,
)
seelog.Info("Beginning Polling for updates")
err := acsSession.Start()
if err != nil {
seelog.Criticalf("Unretriable error starting communicating with ACS: %v", err)
return exitcodes.ExitTerminal
}
seelog.Critical("ACS Session handler should never exit")
return exitcodes.ExitError
}