-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathecr.go
255 lines (212 loc) · 6.33 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
package registry
import (
"encoding/base64"
"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"
"github.com/dgraph-io/ristretto"
"github.com/go-co-op/gocron"
"github.com/rs/zerolog/log"
)
var execCommand = exec.Command
type ECRClient struct {
client ecriface.ECRAPI
ecrDomain string
authToken []byte
cache *ristretto.Cache
scheduler *gocron.Scheduler
targetAccount string
accessPolicy string
lifecyclePolicy string
}
func (e *ECRClient) Credentials() string {
return string(e.authToken)
}
func (e *ECRClient) CreateRepository(name string) error {
if _, found := e.cache.Get(name); found {
return nil
}
_, err := e.client.CreateRepository(&ecr.CreateRepositoryInput{
RepositoryName: aws.String(name),
ImageScanningConfiguration: &ecr.ImageScanningConfiguration{
ScanOnPush: aws.Bool(true),
},
ImageTagMutability: aws.String(ecr.ImageTagMutabilityMutable),
RegistryId: &e.targetAccount,
Tags: []*ecr.Tag{
{
Key: aws.String("CreatedBy"),
Value: aws.String("k8s-image-swapper"),
},
},
})
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.Debug().Str("repo", name).Str("accessPolicy", e.accessPolicy).Msg("setting access policy on repo")
_, err := e.client.SetRepositoryPolicy(&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.Debug().Str("repo", name).Str("lifecyclePolicy", e.lifecyclePolicy).Msg("setting lifecycle policy on repo")
_, err := e.client.PutLifecyclePolicy(&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) RepositoryExists() bool {
panic("implement me")
}
func (e *ECRClient) CopyImage() error {
panic("implement me")
}
func (e *ECRClient) PullImage() error {
panic("implement me")
}
func (e *ECRClient) PutImage() error {
panic("implement me")
}
func (e *ECRClient) ImageExists(ref string) bool {
if _, found := e.cache.Get(ref); found {
return true
}
app := "skopeo"
args := []string{
"inspect",
"--retry-times", "3",
"docker://" + ref,
"--creds", e.Credentials(),
}
log.Trace().Str("app", app).Strs("args", args).Msg("executing command to inspect image")
cmd := execCommand(app, args...)
if _, err := cmd.Output(); err != nil {
return false
}
e.cache.Set(ref, "", 1)
return true
}
func (e *ECRClient) Endpoint() string {
return e.ecrDomain
}
// 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
}
func NewECRClient(region string, ecrDomain string, targetAccount string, role string, accessPolicy string, lifecyclePolicy string) (*ECRClient, error) {
var sess *session.Session
var config *aws.Config
if role != "" {
log.Info().Str("assumedRole", role).Msg("assuming specified role")
stsSession, _ := session.NewSession(config)
creds := stscreds.NewCredentials(stsSession, role)
config = aws.NewConfig().
WithRegion(region).
WithCredentialsChainVerboseErrors(true).
WithHTTPClient(&http.Client{
Timeout: 3 * time.Second,
}).
WithCredentials(creds)
} else {
config = aws.NewConfig().
WithRegion(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: targetAccount,
accessPolicy: accessPolicy,
lifecyclePolicy: lifecyclePolicy,
}
if err := client.scheduleTokenRenewal(); err != nil {
return nil, err
}
return client, nil
}
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"),
}
return client, nil
}