-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathecr.go
333 lines (277 loc) · 9.05 KB
/
ecr.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
package registry
import (
"context"
"encoding/base64"
"fmt"
"github.com/containers/image/v5/docker/reference"
"net/http"
"os/exec"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ecr"
"github.com/aws/aws-sdk-go/service/ecr/ecriface"
ctypes "github.com/containers/image/v5/types"
"github.com/dgraph-io/ristretto"
"github.com/estahn/k8s-image-swapper/pkg/config"
"github.com/go-co-op/gocron"
"github.com/rs/zerolog/log"
)
type ECRClient struct {
client ecriface.ECRAPI
ecrDomain string
authToken []byte
cache *ristretto.Cache
scheduler *gocron.Scheduler
targetAccount string
accessPolicy string
lifecyclePolicy string
tags []config.Tag
}
func NewECRClient(clientConfig config.AWS) (*ECRClient, error) {
ecrDomain := clientConfig.EcrDomain()
var sess *session.Session
var config *aws.Config
if clientConfig.Role != "" {
log.Info().Str("assumedRole", clientConfig.Role).Msg("assuming specified role")
stsSession, _ := session.NewSession(config)
creds := stscreds.NewCredentials(stsSession, clientConfig.Role)
config = aws.NewConfig().
WithRegion(clientConfig.Region).
WithCredentialsChainVerboseErrors(true).
WithHTTPClient(&http.Client{
Timeout: 3 * time.Second,
}).
WithCredentials(creds)
} else {
config = aws.NewConfig().
WithRegion(clientConfig.Region).
WithCredentialsChainVerboseErrors(true).
WithHTTPClient(&http.Client{
Timeout: 3 * time.Second,
})
}
sess = session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
Config: (*config),
}))
ecrClient := ecr.New(sess, config)
cache, err := ristretto.NewCache(&ristretto.Config{
NumCounters: 1e7, // number of keys to track frequency of (10M).
MaxCost: 1 << 30, // maximum cost of cache (1GB).
BufferItems: 64, // number of keys per Get buffer.
})
if err != nil {
panic(err)
}
scheduler := gocron.NewScheduler(time.UTC)
scheduler.StartAsync()
client := &ECRClient{
client: ecrClient,
ecrDomain: ecrDomain,
cache: cache,
scheduler: scheduler,
targetAccount: clientConfig.AccountID,
accessPolicy: clientConfig.ECROptions.AccessPolicy,
lifecyclePolicy: clientConfig.ECROptions.LifecyclePolicy,
tags: clientConfig.ECROptions.Tags,
}
if err := client.scheduleTokenRenewal(); err != nil {
return nil, err
}
return client, nil
}
func (e *ECRClient) Credentials() string {
return string(e.authToken)
}
func (e *ECRClient) CreateRepository(ctx context.Context, name string) error {
if _, found := e.cache.Get(name); found {
return nil
}
log.Ctx(ctx).Debug().Str("repository", name).Msg("create repository")
_, err := e.client.CreateRepositoryWithContext(ctx, &ecr.CreateRepositoryInput{
RepositoryName: aws.String(name),
ImageScanningConfiguration: &ecr.ImageScanningConfiguration{
ScanOnPush: aws.Bool(true),
},
ImageTagMutability: aws.String(ecr.ImageTagMutabilityMutable),
RegistryId: &e.targetAccount,
Tags: e.buildEcrTags(),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case ecr.ErrCodeRepositoryAlreadyExistsException:
// We ignore this case as it is valid.
default:
return err
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
return err
}
}
if len(e.accessPolicy) > 0 {
log.Ctx(ctx).Debug().Str("repo", name).Str("accessPolicy", e.accessPolicy).Msg("setting access policy on repo")
_, err := e.client.SetRepositoryPolicyWithContext(ctx, &ecr.SetRepositoryPolicyInput{
PolicyText: &e.accessPolicy,
RegistryId: &e.targetAccount,
RepositoryName: aws.String(name),
})
if err != nil {
log.Err(err).Msg(err.Error())
return err
}
}
if len(e.lifecyclePolicy) > 0 {
log.Ctx(ctx).Debug().Str("repo", name).Str("lifecyclePolicy", e.lifecyclePolicy).Msg("setting lifecycle policy on repo")
_, err := e.client.PutLifecyclePolicyWithContext(ctx, &ecr.PutLifecyclePolicyInput{
LifecyclePolicyText: &e.lifecyclePolicy,
RegistryId: &e.targetAccount,
RepositoryName: aws.String(name),
})
if err != nil {
log.Err(err).Msg(err.Error())
return err
}
}
e.cache.Set(name, "", 1)
return nil
}
func (e *ECRClient) buildEcrTags() []*ecr.Tag {
ecrTags := []*ecr.Tag{}
for _, t := range e.tags {
tag := ecr.Tag{Key: aws.String(t.Key), Value: aws.String(t.Value)}
ecrTags = append(ecrTags, &tag)
}
return ecrTags
}
func (e *ECRClient) RepositoryExists() bool {
panic("implement me")
}
func (e *ECRClient) CopyImage(ctx context.Context, srcRef ctypes.ImageReference, srcCreds string, destRef ctypes.ImageReference, destCreds string) error {
src := srcRef.DockerReference().String()
dest := destRef.DockerReference().String()
app := "skopeo"
args := []string{
"--override-os", "linux",
"copy",
"--multi-arch", "all",
"--retry-times", "3",
"docker://" + src,
"docker://" + dest,
}
if len(srcCreds) > 0 {
args = append(args, "--src-authfile", srcCreds)
} else {
args = append(args, "--src-no-creds")
}
if len(destCreds) > 0 {
args = append(args, "--dest-creds", destCreds)
} else {
args = append(args, "--dest-no-creds")
}
log.Ctx(ctx).
Trace().
Str("app", app).
Strs("args", args).
Msg("execute command to copy image")
output, cmdErr := exec.CommandContext(ctx, app, args...).CombinedOutput()
// check if the command timed out during execution for proper logging
if err := ctx.Err(); err != nil {
return err
}
// enrich error with output from the command which may contain the actual reason
if cmdErr != nil {
return fmt.Errorf("Command error, stderr: %s, stdout: %s", cmdErr.Error(), string(output))
}
return nil
}
func (e *ECRClient) PullImage() error {
panic("implement me")
}
func (e *ECRClient) PutImage() error {
panic("implement me")
}
func (e *ECRClient) ImageExists(ctx context.Context, imageRef ctypes.ImageReference) bool {
ref := imageRef.DockerReference().String()
if _, found := e.cache.Get(ref); found {
log.Ctx(ctx).Trace().Str("ref", ref).Msg("found in cache")
return true
}
app := "skopeo"
args := []string{
"inspect",
"--retry-times", "3",
"docker://" + ref,
"--creds", e.Credentials(),
}
log.Ctx(ctx).Trace().Str("app", app).Strs("args", args).Msg("executing command to inspect image")
if err := exec.CommandContext(ctx, app, args...).Run(); err != nil {
log.Ctx(ctx).Trace().Str("ref", ref).Msg("not found in target repository")
return false
}
log.Ctx(ctx).Trace().Str("ref", ref).Msg("found in target repository")
e.cache.Set(ref, "", 1)
return true
}
func (e *ECRClient) Endpoint() string {
return e.ecrDomain
}
// IsOrigin returns true if the references origin is from this registry
func (e *ECRClient) IsOrigin(imageRef ctypes.ImageReference) bool {
domain := reference.Domain(imageRef.DockerReference())
return domain == e.Endpoint()
}
// requestAuthToken requests and returns an authentication token from ECR with its expiration date
func (e *ECRClient) requestAuthToken() ([]byte, time.Time, error) {
getAuthTokenOutput, err := e.client.GetAuthorizationToken(&ecr.GetAuthorizationTokenInput{
RegistryIds: []*string{&e.targetAccount},
})
if err != nil {
return []byte(""), time.Time{}, err
}
authToken, err := base64.StdEncoding.DecodeString(*getAuthTokenOutput.AuthorizationData[0].AuthorizationToken)
if err != nil {
return []byte(""), time.Time{}, err
}
return authToken, *getAuthTokenOutput.AuthorizationData[0].ExpiresAt, nil
}
// scheduleTokenRenewal sets a scheduler to execute token renewal before the token expires
func (e *ECRClient) scheduleTokenRenewal() error {
token, expiryAt, err := e.requestAuthToken()
if err != nil {
return err
}
renewalAt := expiryAt.Add(-2 * time.Minute)
e.authToken = token
log.Debug().Time("expiryAt", expiryAt).Time("renewalAt", renewalAt).Msg("auth token set, schedule next token renewal")
j, _ := e.scheduler.Every(1).StartAt(renewalAt).Do(e.scheduleTokenRenewal)
j.LimitRunsTo(1)
return nil
}
// For testing purposes
func NewDummyECRClient(region string, targetAccount string, role string, options config.ECROptions, authToken []byte) *ECRClient {
return &ECRClient{
targetAccount: targetAccount,
accessPolicy: options.AccessPolicy,
lifecyclePolicy: options.LifecyclePolicy,
ecrDomain: fmt.Sprintf("%s.dkr.ecr.%s.amazonaws.com", targetAccount, region),
authToken: authToken,
}
}
func NewMockECRClient(ecrClient ecriface.ECRAPI, region string, ecrDomain string, targetAccount, role string) (*ECRClient, error) {
client := &ECRClient{
client: ecrClient,
ecrDomain: ecrDomain,
cache: nil,
scheduler: nil,
targetAccount: targetAccount,
authToken: []byte("mock-ecr-client-fake-auth-token"),
tags: []config.Tag{{Key: "CreatedBy", Value: "k8s-image-swapper"}, {Key: "AnotherTag", Value: "another-tag"}},
}
return client, nil
}