-
Notifications
You must be signed in to change notification settings - Fork 88
/
registry.go
425 lines (367 loc) · 13.4 KB
/
registry.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
package handlers
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/containers/image/v5/docker"
"github.com/docker/distribution/registry/api/errcode"
"github.com/gorilla/mux"
"github.com/pkg/errors"
apptypes "github.com/replicatedhq/kots/pkg/app/types"
dockerregistry "github.com/replicatedhq/kots/pkg/docker/registry"
"github.com/replicatedhq/kots/pkg/logger"
"github.com/replicatedhq/kots/pkg/preflight"
"github.com/replicatedhq/kots/pkg/registry"
registrytypes "github.com/replicatedhq/kots/pkg/registry/types"
"github.com/replicatedhq/kots/pkg/store"
"github.com/replicatedhq/kots/pkg/version"
corev1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes/scheme"
)
type UpdateAppRegistryRequest struct {
Hostname string `json:"hostname"`
Username string `json:"username"`
Password string `json:"password"`
Namespace string `json:"namespace"`
IsReadOnly bool `json:"isReadOnly"`
}
type UpdateAppRegistryResponse struct {
Success bool `json:"success"`
Error string `json:"error,omitempty"`
Hostname string `json:"hostname"`
Username string `json:"username"`
Namespace string `json:"namespace"`
}
type GetAppRegistryResponse struct {
Success bool `json:"success"`
Error string `json:"error,omitempty"`
Hostname string `json:"hostname"`
Namespace string `json:"namespace"`
Username string `json:"username"`
Password string `json:"password"`
IsReadOnly bool `json:"isReadOnly"`
}
type GetKotsadmRegistryResponse struct {
Success bool `json:"success"`
Error string `json:"error,omitempty"`
Hostname string `json:"hostname"`
Namespace string `json:"namespace"`
Username string `json:"username"`
Password string `json:"password"`
IsReadOnly bool `json:"isReadOnly"`
}
type ValidateAppRegistryRequest struct {
Hostname string `json:"hostname"`
Namespace string `json:"namespace"`
Username string `json:"username"`
Password string `json:"password"`
IsReadOnly bool `json:"isReadOnly"`
}
type ValidateAppRegistryResponse struct {
Success bool `json:"success"`
Error string `json:"error,omitempty"`
}
func (h *Handler) UpdateAppRegistry(w http.ResponseWriter, r *http.Request) {
updateAppRegistryResponse := UpdateAppRegistryResponse{
Success: false,
}
updateAppRegistryRequest := UpdateAppRegistryRequest{}
if err := json.NewDecoder(r.Body).Decode(&updateAppRegistryRequest); err != nil {
logger.Error(errors.Wrap(err, "failed to decode UpdateAppRegistry request body"))
updateAppRegistryResponse.Error = err.Error()
JSON(w, http.StatusInternalServerError, updateAppRegistryResponse)
return
}
if updateAppRegistryRequest.Namespace == "" {
err := errors.New("registry namespace is required")
logger.Error(err)
updateAppRegistryResponse.Error = err.Error()
JSON(w, http.StatusBadRequest, updateAppRegistryResponse)
return
}
currentStatus, _, err := store.GetStore().GetTaskStatus("image-rewrite")
if err != nil {
logger.Error(errors.Wrap(err, "failed to get image-rewrite taks status"))
updateAppRegistryResponse.Error = err.Error()
JSON(w, http.StatusInternalServerError, updateAppRegistryResponse)
return
}
if currentStatus == "running" {
err := errors.New("image-rewrite is already running, not starting a new one")
logger.Error(err)
updateAppRegistryResponse.Error = err.Error()
JSON(w, http.StatusInternalServerError, updateAppRegistryResponse)
return
}
if err := store.GetStore().ClearTaskStatus("image-rewrite"); err != nil {
logger.Error(errors.Wrap(err, "failed to clear image-rewrite taks status"))
updateAppRegistryResponse.Error = err.Error()
JSON(w, http.StatusInternalServerError, updateAppRegistryResponse)
return
}
foundApp, err := store.GetStore().GetAppFromSlug(mux.Vars(r)["appSlug"])
if err != nil {
logger.Error(errors.Wrap(err, "failed to get app from slug"))
updateAppRegistryResponse.Error = err.Error()
JSON(w, http.StatusInternalServerError, updateAppRegistryResponse)
return
}
registrySettings, err := store.GetStore().GetRegistryDetailsForApp(foundApp.ID)
if err != nil {
logger.Error(errors.Wrap(err, "failed to get app registry settings"))
updateAppRegistryResponse.Error = err.Error()
JSON(w, http.StatusInternalServerError, updateAppRegistryResponse)
return
}
registryPassword := updateAppRegistryRequest.Password
if registryPassword == registrytypes.PasswordMask {
registryPassword = registrySettings.Password
}
access := dockerregistry.ActionPush
if updateAppRegistryRequest.IsReadOnly {
access = dockerregistry.ActionPull
}
err = dockerregistry.CheckAccess(updateAppRegistryRequest.Hostname, updateAppRegistryRequest.Username, registryPassword, updateAppRegistryRequest.Namespace, access)
if err != nil {
logger.Infof("Failed to test %s access to %q with user %q: %v", access, updateAppRegistryRequest.Hostname, updateAppRegistryRequest.Username, err)
JSON(w, 400, NewErrorResponse(err))
return
}
updateAppRegistryResponse.Hostname = updateAppRegistryRequest.Hostname
updateAppRegistryResponse.Username = updateAppRegistryRequest.Username
updateAppRegistryResponse.Namespace = updateAppRegistryRequest.Namespace
registryChanged, err := registrySettingsChanged(foundApp, updateAppRegistryRequest, registrySettings)
if err != nil {
logger.Error(errors.Wrap(err, "failed to check registry settings"))
updateAppRegistryResponse.Error = err.Error()
JSON(w, http.StatusInternalServerError, updateAppRegistryResponse)
return
}
if !registryChanged {
updateAppRegistryResponse.Success = true
JSON(w, http.StatusOK, updateAppRegistryResponse)
return
}
// in a goroutine, start pushing the images to the remote registry
// we will let this function return while this happens
go func() {
skipImagePush := updateAppRegistryRequest.IsReadOnly
if foundApp.IsAirgap {
// TODO: pushing images not yet supported in airgapped instances.
skipImagePush = true
}
appDir, err := registry.RewriteImages(
foundApp.ID, foundApp.CurrentSequence, updateAppRegistryRequest.Hostname,
updateAppRegistryRequest.Username, registryPassword,
updateAppRegistryRequest.Namespace, skipImagePush, nil)
if err != nil {
// log credential errors at info level
causeErr := errors.Cause(err)
switch causeErr.(type) {
case docker.ErrUnauthorizedForCredentials, errcode.Errors, errcode.Error, awserr.Error, *url.Error:
logger.Infof(
"Failed to rewrite images for host %q and username %q: %v",
updateAppRegistryRequest.Hostname,
updateAppRegistryRequest.Username,
causeErr,
)
default:
logger.Error(errors.Wrap(err, "failed to rewrite images"))
}
return
}
defer os.RemoveAll(appDir)
newSequence, err := store.GetStore().CreateAppVersion(foundApp.ID, &foundApp.CurrentSequence, appDir, "Registry Change", false, &version.DownstreamGitOps{})
if err != nil {
logger.Error(errors.Wrap(err, "failed to create app version"))
return
}
err = store.GetStore().UpdateRegistry(foundApp.ID, updateAppRegistryRequest.Hostname, updateAppRegistryRequest.Username, updateAppRegistryRequest.Password, updateAppRegistryRequest.Namespace, updateAppRegistryRequest.IsReadOnly)
if err != nil {
logger.Error(errors.Wrap(err, "failed to update registry"))
return
}
if err := preflight.Run(foundApp.ID, foundApp.Slug, newSequence, foundApp.IsAirgap, appDir); err != nil {
logger.Error(errors.Wrap(err, "failed to run preflights"))
return
}
}()
updateAppRegistryResponse.Success = true
JSON(w, http.StatusOK, updateAppRegistryResponse)
}
func registrySettingsChanged(app *apptypes.App, new UpdateAppRegistryRequest, current registrytypes.RegistrySettings) (bool, error) {
if new.Hostname != current.Hostname {
return true, nil
}
if new.Namespace != current.Namespace {
return true, nil
}
if new.Username != current.Username {
return true, nil
}
if new.Password != registrytypes.PasswordMask && new.Password != current.Password {
return true, nil
}
if new.IsReadOnly != current.IsReadOnly {
return true, nil
}
// Because an old version can be editted, we may need to push images if registry hostname has changed
// TODO: Handle namespace changes too
archiveDir, err := ioutil.TempDir("", "kotsadm-")
if err != nil {
return false, errors.Wrap(err, "failed to create temp dir")
}
defer os.RemoveAll(archiveDir)
err = store.GetStore().GetAppVersionArchive(app.ID, app.CurrentSequence, archiveDir)
if err != nil {
return false, errors.Wrap(err, "failed to get version archive")
}
secretData, err := ioutil.ReadFile(filepath.Join(archiveDir, "overlays", "midstream", "secret.yaml"))
if err != nil {
if os.IsNotExist(err) {
if new.Hostname != "" {
return true, nil
} else {
return false, nil
}
}
return false, errors.Wrap(err, "failed to load image pull secret")
}
decode := scheme.Codecs.UniversalDeserializer().Decode
obj, gvk, err := decode(secretData, nil, nil)
if err != nil {
return false, errors.Wrap(err, "failed to decode image pull secret")
}
if gvk.Group != "" || gvk.Version != "v1" || gvk.Kind != "Secret" {
return false, errors.Errorf("unexpected secret GVK: %s", gvk.String())
}
secret := obj.(*corev1.Secret)
if secret.Type != "kubernetes.io/dockerconfigjson" {
return false, errors.Errorf("unexpected secret type: %s", secret.Type)
}
dockerConfig := struct {
Auths map[string]interface{} `json:"auths"`
}{}
err = json.Unmarshal(secret.Data[".dockerconfigjson"], &dockerConfig)
if err != nil {
return false, errors.Wrap(err, "failed to unmarshal .dockerconfigjson")
}
_, ok := dockerConfig.Auths[new.Hostname]
if !ok {
// New hostname is not in the auths list, so images have to pushed
return true, nil
}
return false, nil
}
func (h *Handler) GetAppRegistry(w http.ResponseWriter, r *http.Request) {
getAppRegistryResponse := GetAppRegistryResponse{
Success: false,
}
foundApp, err := store.GetStore().GetAppFromSlug(mux.Vars(r)["appSlug"])
if err != nil {
logger.Error(err)
getAppRegistryResponse.Error = err.Error()
JSON(w, 500, getAppRegistryResponse)
return
}
settings, err := store.GetStore().GetRegistryDetailsForApp(foundApp.ID)
if err != nil {
logger.Error(err)
getAppRegistryResponse.Error = err.Error()
JSON(w, 500, getAppRegistryResponse)
return
}
getAppRegistryResponse.Hostname = settings.Hostname
getAppRegistryResponse.Namespace = settings.Namespace
getAppRegistryResponse.Username = settings.Username
getAppRegistryResponse.IsReadOnly = settings.IsReadOnly
if settings.Password != "" {
getAppRegistryResponse.Password = registrytypes.PasswordMask
}
getAppRegistryResponse.Success = true
JSON(w, 200, getAppRegistryResponse)
}
func (h *Handler) GetKotsadmRegistry(w http.ResponseWriter, r *http.Request) {
getKotsadmRegistryResponse := GetKotsadmRegistryResponse{
Success: false,
}
settings, err := registry.GetKotsadmRegistry()
if err != nil {
logger.Error(err)
getKotsadmRegistryResponse.Error = err.Error()
JSON(w, 500, getKotsadmRegistryResponse)
return
}
getKotsadmRegistryResponse.Success = true
getKotsadmRegistryResponse.Hostname = settings.Hostname
getKotsadmRegistryResponse.Namespace = settings.Namespace
getKotsadmRegistryResponse.Username = settings.Username
getKotsadmRegistryResponse.IsReadOnly = settings.IsReadOnly
if settings.Hostname != "" && settings.Username != "" {
getKotsadmRegistryResponse.Password = registrytypes.PasswordMask
}
JSON(w, 200, getKotsadmRegistryResponse)
}
func (h *Handler) ValidateAppRegistry(w http.ResponseWriter, r *http.Request) {
validateAppRegistryResponse := ValidateAppRegistryResponse{
Success: false,
}
validateAppRegistryRequest := ValidateAppRegistryRequest{}
if err := json.NewDecoder(r.Body).Decode(&validateAppRegistryRequest); err != nil {
logger.Error(err)
validateAppRegistryResponse.Error = err.Error()
JSON(w, 500, validateAppRegistryResponse)
return
}
foundApp, err := store.GetStore().GetAppFromSlug(mux.Vars(r)["appSlug"])
if err != nil {
logger.Error(err)
validateAppRegistryResponse.Error = err.Error()
JSON(w, 500, validateAppRegistryResponse)
return
}
password := validateAppRegistryRequest.Password
if password == registrytypes.PasswordMask {
appSettings, err := store.GetStore().GetRegistryDetailsForApp(foundApp.ID)
if err != nil {
logger.Error(err)
validateAppRegistryResponse.Error = err.Error()
JSON(w, 500, validateAppRegistryResponse)
return
}
if appSettings.Password != "" {
password = appSettings.Password
} else {
kotsadmSettings, err := registry.GetKotsadmRegistry()
if err != nil {
logger.Error(err)
validateAppRegistryResponse.Error = err.Error()
JSON(w, 500, validateAppRegistryResponse)
return
}
password = kotsadmSettings.Password
}
}
if password == registrytypes.PasswordMask {
err := errors.Errorf("no password found for %s", validateAppRegistryRequest.Hostname)
JSON(w, 400, NewErrorResponse(err))
return
}
access := dockerregistry.ActionPush
if validateAppRegistryRequest.IsReadOnly {
access = dockerregistry.ActionPull
}
err = dockerregistry.CheckAccess(validateAppRegistryRequest.Hostname, validateAppRegistryRequest.Username, password, validateAppRegistryRequest.Namespace, access)
if err != nil {
// NOTE: it is possible this is a 500 sometimes
logger.Infof("Failed to test %s access to %q with user %q: %v", access, validateAppRegistryRequest.Hostname, validateAppRegistryRequest.Username, err)
JSON(w, 400, NewErrorResponse(err))
return
}
validateAppRegistryResponse.Success = true
JSON(w, 200, validateAppRegistryResponse)
}