This repository was archived by the owner on Sep 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathcache.go
More file actions
338 lines (294 loc) · 10.5 KB
/
cache.go
File metadata and controls
338 lines (294 loc) · 10.5 KB
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
// Copyright 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 cache provides functionality for working with an on-disk cache of
// the ECS Agent image.
package cache
import (
"bufio"
"crypto/md5"
"fmt"
"io"
"os"
"strings"
"github.com/aws/amazon-ecs-init/ecs-init/config"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/session"
log "github.com/cihub/seelog"
"github.com/pkg/errors"
)
const (
orwPerm = 0700
regionalBucketFormat = "%s-%s"
)
// CacheStatus represents the status of the on-disk cache for agent
// tarballs in the cache directory. This status may be used to
// determine what the appropriate actions are based on the
// availability of agent images and communicates advice from the
// cache's state file.
type CacheStatus uint8
const (
// StatusUncached indicates that there is not an already downloaded
// and cached agent that is suitable for loading.
StatusUncached CacheStatus = 0
// StatusCached indicates that there is an agent downloaded and
// cached. This should be taken to mean that the image is suitable
// for load if agent isn't already loaded.
StatusCached CacheStatus = 1
// StatusReloadNeeded indicates that the cached image should take
// precedence over the already loaded agent image. This may be
// specified by the packaging to cause ecs-init to load a package
// distributed cached image on package installation, upgrades, or
// downgrades.
StatusReloadNeeded CacheStatus = 2
)
// Downloader is responsible for cache operations relating to downloading the agent
type Downloader struct {
s3Downloader s3DownloaderAPI
fs fileSystem
metadata instanceMetadata
region string
}
// NewDownloader returns a Downloader with default dependencies
func NewDownloader() (*Downloader, error) {
downloader := &Downloader{
fs: &standardFS{},
}
if config.RunningInExternal() {
downloader.metadata = &blackholeInstanceMetadata{}
} else {
sessionInstance, err := session.NewSession()
if err != nil {
// metadata client is only used for retrieving the user's region.
// If it cannot be initialized, the region field is populated with the default value to prevent future
// calls to retrieve the region from metadata.
log.Warnf("Got error when initializing session for metadata client: %v. Use default region: %s",
err, config.DefaultRegionName)
downloader.region = config.DefaultRegionName
} else {
downloader.metadata = ec2metadata.New(sessionInstance)
}
}
s3Downloader := &s3Downloader{
bucketDownloaders: make([]*s3BucketDownloader, 0),
cacheDir: config.CacheDirectory(),
fs: downloader.fs,
}
partitionBucketRegion := downloader.getPartitionBucketRegion()
partitionBucket := config.AgentPartitionBucketName
partitionBucketDownloader, err := newS3BucketDownloader(partitionBucketRegion, partitionBucket)
if err != nil {
log.Warnf("Failed to initialize partition bucket downloader: %v", err)
} else {
s3Downloader.addBucketDownloader(partitionBucketDownloader)
}
region := downloader.getRegion()
regionalBucket := fmt.Sprintf(regionalBucketFormat, partitionBucket, region)
regionalBucketDownloader, err := newS3BucketDownloader(region, regionalBucket)
if err != nil {
log.Warnf("Failed to initialize regional bucket downloader: %v", err)
} else {
s3Downloader.addBucketDownloader(regionalBucketDownloader)
}
if len(s3Downloader.bucketDownloaders) == 0 {
log.Error("Failed to initialize s3 downloader for either partition bucket or regional bucket. Downloader initialization fails.")
return nil, errors.New("failed to initialize downloader")
}
downloader.s3Downloader = s3Downloader
return downloader, nil
}
// AgentCacheStatus inspects the on-disk cache and returns its
// status. See `CacheStatus` for possible cache statuses and
// scenarios.
func (d *Downloader) AgentCacheStatus() CacheStatus {
stateFile := config.CacheState()
// State file and tarball must be non-zero to report status on
uncached := !(d.fileNotEmpty(stateFile) && d.fileNotEmpty(config.AgentTarball()))
if uncached {
return StatusUncached
}
file, err := d.fs.Open(stateFile)
if err != nil {
return StatusUncached
}
var status CacheStatus
_, err = fmt.Fscanf(file, "%d", &status)
if err != nil {
return StatusUncached
}
return status
}
// IsAgentCached returns true if there is a cached copy of the Agent present
// and a cache state file is not empty (no validation is performed on the
// tarball or cache state file contents)
func (d *Downloader) IsAgentCached() bool {
switch d.AgentCacheStatus() {
case StatusUncached:
return false
}
return true
}
func (d *Downloader) fileNotEmpty(filename string) bool {
fileinfo, err := d.fs.Stat(filename)
if err != nil {
return false
}
return fileinfo.Size() > 0
}
// getRegion finds region from metadata and caches for the life of downloader
func (d *Downloader) getRegion() string {
if d.region != "" {
return d.region
}
defaultRegion := config.DefaultRegionName
if config.RunningInExternal() {
region := os.Getenv(config.DefaultRegionEnvVar)
if region == "" {
log.Warnf("%s is not specified while running in external (non-EC2) environment. Using default region: %s",
config.DefaultRegionEnvVar, defaultRegion)
}
d.region = defaultRegion
return d.region
}
region, err := d.metadata.Region()
if err != nil {
log.Warn("Could not retrieve the region from EC2 Instance Metadata. Error: %s", err.Error())
region = defaultRegion
}
d.region = region
return d.region
}
// getBucketRegion returns a region that contains the agent's bucket
func (d *Downloader) getPartitionBucketRegion() string {
region := d.getRegion()
destination, err := config.GetAgentPartitionBucketRegion(region)
if err != nil {
log.Warnf("Current region not supported, using the default region (%s) for downloader, err: %v", config.DefaultRegionName, err)
return config.DefaultRegionName
}
return destination
}
// DownloadAgent downloads a copy of the Agent and performs an
// integrity check of the downloaded image
func (d *Downloader) DownloadAgent() error {
err := d.fs.MkdirAll(config.CacheDirectory(), os.ModeDir|orwPerm)
if err != nil {
return err
}
publishedMd5Sum, err := d.getPublishedMd5Sum()
if err != nil {
return err
}
tempFileName, err := d.getPublishedTarball()
if err != nil {
return err
}
defer func() { // clean up temp file
if _, err := d.fs.Stat(tempFileName); err == nil { // if temp file exists, remove it
log.Debugf("Removing temp file %s", tempFileName)
d.fs.Remove(tempFileName)
}
}()
publishedTarballReader, err := d.fs.Open(tempFileName)
if err != nil {
return err
}
defer publishedTarballReader.Close()
md5hash := md5.New()
_, err = d.fs.Copy(md5hash, publishedTarballReader)
if err != nil {
return err
}
calculatedMd5Sum := md5hash.Sum(nil)
calculatedMd5SumString := fmt.Sprintf("%x", calculatedMd5Sum)
log.Debugf("Expected MD5 %q", publishedMd5Sum)
log.Debugf("Calculated MD5 %q", calculatedMd5SumString)
if publishedMd5Sum != calculatedMd5SumString {
agentTarballName, err := config.AgentRemoteTarballKey()
if err != nil {
return errors.New("downloaded agent does not match expected checksum")
}
return errors.Errorf("downloaded agent %q does not match expected checksum", agentTarballName)
}
log.Debugf("Attempting to rename %s to %s", tempFileName, config.AgentTarball())
return d.fs.Rename(tempFileName, config.AgentTarball())
}
func (d *Downloader) getPublishedMd5Sum() (string, error) {
objectKey, err := config.AgentRemoteTarballMD5Key()
if err != nil {
return "", errors.Wrap(err, "failed to determine md5 file for download")
}
tempMd5FileName, err := d.s3Downloader.downloadFile(objectKey)
if err != nil {
return "", errors.Wrap(err, "failed to download md5 file for published tarball")
}
tempMd5File, err := d.fs.Open(tempMd5FileName)
if err != nil {
return "", errors.Wrap(err, "failed to open temporary md5 file")
}
defer func() { // clean up temp file
log.Debugf("Removing temp file %s", tempMd5FileName)
d.fs.Remove(tempMd5FileName)
}()
body, err := d.fs.ReadAll(tempMd5File)
if err != nil {
return "", errors.Wrap(err, "failed to read from temporary md5 file")
}
return strings.TrimSpace(string(body)), nil
}
func (d *Downloader) getPublishedTarball() (string, error) {
objectKey, err := config.AgentRemoteTarballKey()
if err != nil {
return "", errors.Wrap(err, "failed to determine download tarball")
}
tempAgentFileName, err := d.s3Downloader.downloadFile(objectKey)
if err != nil {
return "", errors.Wrap(err, "failed to download published tarball")
}
return tempAgentFileName, nil
}
// LoadCachedAgent returns an io.ReadCloser of the Agent from the cache
func (d *Downloader) LoadCachedAgent() (io.ReadCloser, error) {
return d.fs.Open(config.AgentTarball())
}
// RecordCachedAgent writes the StatusCached state to disk to record a newly
// cached or loaded agent image; this prevents StatusReloadNeeded from
// being interpreted after the reload.
func (d *Downloader) RecordCachedAgent() error {
data := []byte(fmt.Sprintf("%d", StatusCached))
return d.fs.WriteFile(config.CacheState(), data, orwPerm)
}
// LoadDesiredAgent returns an io.ReadCloser of the Agent indicated by the desiredImageLocatorFile
// (/var/cache/ecs/desired-image). The desiredImageLocatorFile must contain as the beginning of the file the name of
// the file containing the desired image (interpreted as a basename) and ending in a newline. Only the first line is
// read, with the rest of the file reserved for future use.
func (d *Downloader) LoadDesiredAgent() (io.ReadCloser, error) {
desiredImageFile, err := d.getDesiredImageFile()
if err != nil {
return nil, err
}
return d.fs.Open(desiredImageFile)
}
func (d *Downloader) getDesiredImageFile() (string, error) {
file, err := d.fs.Open(config.DesiredImageLocatorFile())
if err != nil {
return "", err
}
defer file.Close()
reader := bufio.NewReader(file)
desiredImageString, err := reader.ReadString('\n')
if err != nil {
return "", err
}
desiredImageFile := strings.TrimSpace(config.CacheDirectory() + "/" + d.fs.Base(desiredImageString))
return desiredImageFile, nil
}