forked from aws/amazon-ecs-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
agent.go
238 lines (210 loc) · 8.99 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
// Copyright 2014-2015 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 (
"flag"
mathrand "math/rand"
"os"
"runtime"
"time"
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/config"
"github.com/aws/amazon-ecs-agent/agent/ec2"
"github.com/aws/amazon-ecs-agent/agent/engine"
"github.com/aws/amazon-ecs-agent/agent/eventhandler"
"github.com/aws/amazon-ecs-agent/agent/handlers"
"github.com/aws/amazon-ecs-agent/agent/httpclient"
"github.com/aws/amazon-ecs-agent/agent/logger"
"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"
utilatomic "github.com/aws/amazon-ecs-agent/agent/utils/atomic"
"github.com/aws/amazon-ecs-agent/agent/version"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
log "github.com/cihub/seelog"
"golang.org/x/net/context"
)
func init() {
runtime.GOMAXPROCS(1)
mathrand.Seed(time.Now().UnixNano())
}
func main() {
// Use a returning main instead of os.Exiting main to allow defers to run
// before exit
os.Exit(_main())
}
func _main() int {
defer log.Flush()
versionFlag := flag.Bool("version", false, "Print the agent version information and exit")
acceptInsecureCert := flag.Bool("k", false, "Do not verify ssl certs")
logLevel := flag.String("loglevel", "", "Loglevel: [<crit>|<error>|<warn>|<info>|<debug>]")
flag.Parse()
logger.SetLevel(*logLevel)
log.Infof("Starting Agent: %v", version.String())
log.Info("Loading configuration")
cfg, err := config.NewConfig()
// Load cfg before doing 'versionFlag' so that it has the DOCKER_HOST
// variable loaded if needed
if *versionFlag {
versionableEngine := engine.NewTaskEngine(cfg)
version.PrintVersion(versionableEngine)
return exitcodes.ExitSuccess
}
sighandlers.StartDebugHandler()
ctx := context.Background()
if err != nil {
log.Criticalf("Error loading config: %v", err)
// All required config values can be inferred from EC2 Metadata, so this error could be transient.
return exitcodes.ExitError
}
log.Debug("Loaded config: " + cfg.String())
var currentEc2InstanceID, containerInstanceArn string
var taskEngine engine.TaskEngine
if cfg.Checkpoint {
log.Info("Checkpointing is enabled. Attempting to load state")
var previousCluster, previousEc2InstanceID, previousContainerInstanceArn string
previousTaskEngine := engine.NewTaskEngine(cfg)
// previousState is used to verify that our current runtime configuration is
// compatible with our past configuration as reflected by our state-file
previousState, err := initializeStateManager(cfg, previousTaskEngine, &previousCluster, &previousContainerInstanceArn, &previousEc2InstanceID, acshandler.SequenceNumber)
if err != nil {
log.Criticalf("Error creating state manager: %v", err)
return exitcodes.ExitTerminal
}
err = previousState.Load()
if err != nil {
log.Criticalf("Error loading previously saved state: %v", err)
return exitcodes.ExitTerminal
}
if previousCluster != "" {
// TODO Handle default cluster in a sane and unified way across the codebase
configuredCluster := cfg.Cluster
if configuredCluster == "" {
log.Debug("Setting cluster to default; none configured")
configuredCluster = config.DEFAULT_CLUSTER_NAME
}
if previousCluster != configuredCluster {
log.Criticalf("Data mismatch; saved cluster '%v' does not match configured cluster '%v'. Perhaps you want to delete the configured checkpoint file?", previousCluster, configuredCluster)
return exitcodes.ExitTerminal
}
cfg.Cluster = previousCluster
log.Infof("Restored cluster '%v'", cfg.Cluster)
}
if instanceIdentityDoc, err := ec2.GetInstanceIdentityDocument(); err == nil {
currentEc2InstanceID = instanceIdentityDoc.InstanceId
} else {
log.Criticalf("Unable to access EC2 Metadata service to determine EC2 ID: %v", err)
}
if previousEc2InstanceID != "" && previousEc2InstanceID != currentEc2InstanceID {
log.Warnf("Data mismatch; saved InstanceID '%v' does not match current InstanceID '%v'. Overwriting old datafile", previousEc2InstanceID, currentEc2InstanceID)
// Reset taskEngine; all the other values are still default
taskEngine = engine.NewTaskEngine(cfg)
} else {
// Use the values we loaded if there's no issue
containerInstanceArn = previousContainerInstanceArn
taskEngine = previousTaskEngine
}
} else {
log.Info("Checkpointing not enabled; a new container instance will be created each time the agent is run")
taskEngine = engine.NewTaskEngine(cfg)
}
stateManager, err := initializeStateManager(cfg, taskEngine, &cfg.Cluster, &containerInstanceArn, ¤tEc2InstanceID, acshandler.SequenceNumber)
if err != nil {
log.Criticalf("Error creating state manager: %v", err)
return exitcodes.ExitTerminal
}
credentialProvider := aws.DefaultChainCredentials
// Preflight request to make sure they're good
if preflightCreds, err := credentialProvider.Get(); err != nil || preflightCreds.AccessKeyID == "" {
log.Warnf("Error getting valid credentials (AKID %v): %v", preflightCreds.AccessKeyID, err)
}
client := api.NewECSClient(credentialProvider, cfg, httpclient.New(api.RoundtripTimeout, *acceptInsecureCert))
if containerInstanceArn == "" {
log.Info("Registering Instance with ECS")
containerInstanceArn, err = client.RegisterContainerInstance("")
if err != nil {
log.Errorf("Error registering: %v", err)
if retriable, ok := err.(utils.Retriable); ok && !retriable.Retry() {
return exitcodes.ExitTerminal
}
return exitcodes.ExitError
}
log.Infof("Registration completed successfully. I am running as '%v' in cluster '%v'", containerInstanceArn, cfg.Cluster)
// Save our shiny new containerInstanceArn
stateManager.Save()
} else {
log.Infof("Restored from checkpoint file. I am running as '%v' in cluster '%v'", containerInstanceArn, cfg.Cluster)
_, err = client.RegisterContainerInstance(containerInstanceArn)
if err != nil {
log.Errorf("Error registering: %v", err)
if awserr, ok := err.(awserr.Error); ok && api.IsInstanceTypeChangedError(awserr) {
log.Criticalf("The current instance type does not match the registered instance type. Please revert the instance type change, or alternatively launch a new instance. Error: %v", err)
return exitcodes.ExitTerminal
}
}
}
// Begin listening to the docker daemon and saving changes
taskEngine.SetSaver(stateManager)
taskEngine.MustInit()
go sighandlers.StartTerminationHandler(stateManager, taskEngine)
// Agent introspection api
go handlers.ServeHttp(&containerInstanceArn, taskEngine, cfg)
// Start sending events to the backend
go eventhandler.HandleEngineEvents(taskEngine, client, stateManager)
telemetrySessionParams := tcshandler.TelemetrySessionParams{
ContainerInstanceArn: containerInstanceArn,
CredentialProvider: credentialProvider,
Cfg: cfg,
AcceptInvalidCert: *acceptInsecureCert,
EcsClient: client,
TaskEngine: taskEngine,
}
// Start metrics session in a go routine
go tcshandler.StartMetricsSession(telemetrySessionParams)
log.Info("Beginning Polling for updates")
err = acshandler.StartSession(ctx, acshandler.StartSessionArguments{
AcceptInvalidCert: *acceptInsecureCert,
Config: cfg,
ContainerInstanceArn: containerInstanceArn,
CredentialProvider: credentialProvider,
ECSClient: client,
StateManager: stateManager,
TaskEngine: taskEngine,
})
if err != nil {
log.Criticalf("Unretriable error starting communicating with ACS: %v", err)
return exitcodes.ExitTerminal
}
log.Critical("ACS Session handler should never exit")
return exitcodes.ExitError
}
func initializeStateManager(cfg *config.Config, taskEngine engine.TaskEngine, cluster, containerInstanceArn, savedInstanceID *string, sequenceNumber *utilatomic.IncreasingInt64) (statemanager.StateManager, error) {
if !cfg.Checkpoint {
return statemanager.NewNoopStateManager(), nil
}
stateManager, err := statemanager.NewStateManager(cfg,
statemanager.AddSaveable("TaskEngine", taskEngine),
statemanager.AddSaveable("ContainerInstanceArn", containerInstanceArn),
statemanager.AddSaveable("Cluster", cluster),
statemanager.AddSaveable("EC2InstanceID", savedInstanceID),
statemanager.AddSaveable("ACSSeqNum", sequenceNumber),
)
if err != nil {
return nil, err
}
return stateManager, nil
}