/
updater.go
282 lines (245 loc) · 7.78 KB
/
updater.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
// 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 updater
import (
"crypto/sha256"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/aws/amazon-ecs-agent/agent/config"
"github.com/aws/amazon-ecs-agent/agent/data"
"github.com/aws/amazon-ecs-agent/agent/engine"
"github.com/aws/amazon-ecs-agent/agent/engine/dockerstate"
"github.com/aws/amazon-ecs-agent/agent/sighandlers"
"github.com/aws/amazon-ecs-agent/agent/sighandlers/exitcodes"
"github.com/aws/amazon-ecs-agent/agent/utils"
agentversion "github.com/aws/amazon-ecs-agent/agent/version"
"github.com/aws/amazon-ecs-agent/ecs-agent/acs/model/ecsacs"
"github.com/aws/amazon-ecs-agent/ecs-agent/httpclient"
"github.com/aws/amazon-ecs-agent/ecs-agent/utils/ttime"
"github.com/aws/amazon-ecs-agent/ecs-agent/wsclient"
"github.com/aws/aws-sdk-go/aws"
"github.com/cihub/seelog"
)
const desiredImageFile = "desired-image"
// update describes metadata around an update 2-phase request
type updater struct {
stage updateStage
stageTime time.Time
// downloadMessageID is the most recent message id seen for this update id
downloadMessageID string
// updateID is a unique identifier for this update used to determine if a
// new update request, even with a different message id, is a duplicate or
// not
updateID string
acs wsclient.ClientServer
config *config.Config
httpclient *http.Client
state dockerstate.TaskEngineState
dataClient data.Client
taskEngine engine.TaskEngine
sync.Mutex
}
type updateStage int8
const (
updateNone updateStage = iota
updateDownloading
updateDownloaded
)
const (
updateDownloadTimeout = 15 * time.Minute
)
func NewUpdater(cfg *config.Config, state dockerstate.TaskEngineState, dataClient data.Client,
taskEngine engine.TaskEngine) *updater {
return &updater{
config: cfg,
httpclient: httpclient.New(updateDownloadTimeout, false, agentversion.String(), config.OSType),
state: state,
dataClient: dataClient,
taskEngine: taskEngine,
}
}
// AddAgentUpdateHandlers adds the needed update handlers to perform agent
// updates
func (u *updater) AddAgentUpdateHandlers(cs wsclient.ClientServer) {
u.acs = cs
cs.AddRequestHandler(u.stageUpdateHandler())
cs.AddRequestHandler(u.performUpdateHandler())
}
func (u *updater) stageUpdateHandler() func(req *ecsacs.StageUpdateMessage) {
return func(req *ecsacs.StageUpdateMessage) {
u.Lock()
defer u.Unlock()
if req == nil || req.MessageId == nil {
seelog.Error("Nil request to stage update or missing MessageID")
return
}
nack := func(reason string) {
seelog.Errorf("Nacking StageUpdate; reason: %s", reason)
u.acs.MakeRequest(&ecsacs.NackRequest{
Cluster: req.ClusterArn,
ContainerInstance: req.ContainerInstanceArn,
MessageId: req.MessageId,
Reason: aws.String(reason),
})
u.reset()
}
if !u.config.UpdatesEnabled.Enabled() {
nack("Updates are disabled")
return
}
if err := validateUpdateInfo(req.UpdateInfo); err != nil {
nack("Invalid update: " + err.Error())
return
}
seelog.Debug("Staging update", "update", req)
if u.stage != updateNone {
if u.updateID != "" && u.updateID == *req.UpdateInfo.Signature {
seelog.Debug("Update already in progress, acking duplicate message", "id", u.updateID)
// Acking here is safe as any currently-downloading update will already be holding
// the update lock. A failed download will nack and clear state (while holding the
// update lock) before this code is reached, meaning that the above conditional will
// not evaluate true (no matching, in-progress update).
u.acs.MakeRequest(&ecsacs.AckRequest{
Cluster: req.ClusterArn,
ContainerInstance: req.ContainerInstanceArn,
MessageId: req.MessageId,
})
return
} else {
// Nack previous update
reason := "New update arrived: " + *req.MessageId
u.acs.MakeRequest(&ecsacs.NackRequest{
Cluster: req.ClusterArn,
ContainerInstance: req.ContainerInstanceArn,
MessageId: &u.downloadMessageID,
Reason: &reason,
})
}
}
u.updateID = *req.UpdateInfo.Signature
u.stage = updateDownloading
u.stageTime = ttime.Now()
u.downloadMessageID = *req.MessageId
err := u.download(req.UpdateInfo)
if err != nil {
nack("Unable to download: " + err.Error())
return
}
u.stage = updateDownloaded
u.acs.MakeRequest(&ecsacs.AckRequest{
Cluster: req.ClusterArn,
ContainerInstance: req.ContainerInstanceArn,
MessageId: req.MessageId,
})
}
}
var removeFile = os.Remove
var writeFile = os.WriteFile
var createFile = func(name string) (io.ReadWriteCloser, error) {
return os.Create(name)
}
func (u *updater) download(info *ecsacs.UpdateInfo) (err error) {
if info == nil || info.Location == nil {
return errors.New("No location given")
}
if info.Signature == nil {
return errors.New("No signature given")
}
resp, err := u.httpclient.Get(*info.Location)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
return err
}
outFileBasename := utils.RandHex() + ".ecs-update.tar"
outFilePath := filepath.Join(u.config.UpdateDownloadDir, outFileBasename)
outFile, err := createFile(outFilePath)
if err != nil {
return err
}
defer func() {
outFile.Close()
if err != nil {
removeFile(outFilePath)
}
}()
hashsum := sha256.New()
bodyHashReader := io.TeeReader(resp.Body, hashsum)
_, err = io.Copy(outFile, bodyHashReader)
if err != nil {
return err
}
shasum := hashsum.Sum(nil)
shasumString := fmt.Sprintf("%x", shasum)
if shasumString != strings.TrimSpace(*info.Signature) {
return errors.New("Hashsum validation failed")
}
err = writeFile(filepath.Join(u.config.UpdateDownloadDir, desiredImageFile), []byte(outFileBasename+"\n"), 0644)
return err
}
var exit = os.Exit
func (u *updater) performUpdateHandler() func(req *ecsacs.PerformUpdateMessage) {
return func(req *ecsacs.PerformUpdateMessage) {
u.Lock()
defer u.Unlock()
seelog.Debug("Got perform update request")
if !u.config.UpdatesEnabled.Enabled() {
reason := "Updates are disabled"
seelog.Errorf("Nacking PerformUpdate; reason: %s", reason)
u.acs.MakeRequest(&ecsacs.NackRequest{
Cluster: req.ClusterArn,
ContainerInstance: req.ContainerInstanceArn,
MessageId: req.MessageId,
Reason: aws.String(reason),
})
return
}
if u.stage != updateDownloaded {
seelog.Error("Nacking PerformUpdate; not downloaded")
reason := "Cannot perform update; update not downloaded"
u.acs.MakeRequest(&ecsacs.NackRequest{
Cluster: req.ClusterArn,
ContainerInstance: req.ContainerInstanceArn,
MessageId: req.MessageId,
Reason: aws.String(reason),
})
return
}
u.acs.MakeRequest(&ecsacs.AckRequest{
Cluster: req.ClusterArn,
ContainerInstance: req.ContainerInstanceArn,
MessageId: req.MessageId,
})
err := sighandlers.FinalSave(u.state, u.dataClient, u.taskEngine)
if err != nil {
seelog.Critical("Error saving before update exit", "err", err)
} else {
seelog.Debug("Saved state!")
}
exit(exitcodes.ExitUpdate)
}
}
func (u *updater) reset() {
u.updateID = ""
u.downloadMessageID = ""
u.stage = updateNone
u.stageTime = time.Time{}
}