-
Notifications
You must be signed in to change notification settings - Fork 88
/
registry.go
367 lines (303 loc) · 9.73 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
package registry
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"net/url"
"strings"
"sync"
"github.com/pkg/errors"
kotsv1beta1 "github.com/replicatedhq/kots/kotskinds/apis/kots/v1beta1"
corev1 "k8s.io/api/core/v1"
kuberneteserrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
type RegistryProxyInfo struct {
Registry string
Proxy string
Upstream string
}
type DockercfgAuth struct {
Auth string `json:"auth,omitempty"`
}
type DockerCfgJSON struct {
Auths map[string]DockercfgAuth `json:"auths"`
}
type Credentials struct {
Username string
Password string
}
type ImagePullSecrets struct {
AdminConsoleSecret *corev1.Secret
AppSecret *corev1.Secret
DockerHubSecret *corev1.Secret
}
const DockerHubRegistryName = "index.docker.io"
const DockerHubSecretName = "kotsadm-dockerhub"
var ErrDockerHubCredentialsExist = errors.New("dockerhub credentials exists")
var dockerHubSecretMutex sync.Mutex
// try to ensure secrets are created first if using a helm install
var secretAnnotations = map[string]string{
"helm.sh/hook": "pre-install,pre-upgrade",
"helm.sh/hook-weight": "-9999",
}
func GetRegistryProxyInfo(license *kotsv1beta1.License, app *kotsv1beta1.Application) *RegistryProxyInfo {
registryProxyInfo := getRegistryProxyInfoFromLicense(license)
proxyEndpoint, registryEndpoint := getRegistryProxyEndpointFromKotsApplication(app)
if proxyEndpoint != "" {
registryProxyInfo.Proxy = proxyEndpoint
}
if registryEndpoint != "" {
registryProxyInfo.Upstream = registryProxyInfo.Registry
registryProxyInfo.Registry = registryEndpoint
}
return registryProxyInfo
}
func getRegistryProxyEndpointFromKotsApplication(kotsApplication *kotsv1beta1.Application) (proxyEndpoint string, registryEndpoint string) {
if kotsApplication == nil {
return "", ""
}
if kotsApplication.Spec.ProxyRegistryDomain != "" {
proxyEndpoint = kotsApplication.Spec.ProxyRegistryDomain
}
if kotsApplication.Spec.ReplicatedRegistryDomain != "" {
registryEndpoint = kotsApplication.Spec.ReplicatedRegistryDomain
}
return proxyEndpoint, registryEndpoint
}
func getRegistryProxyInfoFromLicense(license *kotsv1beta1.License) *RegistryProxyInfo {
defaultInfo := &RegistryProxyInfo{
Registry: "registry.replicated.com",
Proxy: "proxy.replicated.com",
}
if license == nil {
return defaultInfo
}
u, err := url.Parse(license.Spec.Endpoint)
if err != nil {
return defaultInfo
}
if u.Hostname() == "staging.replicated.app" {
return &RegistryProxyInfo{
Registry: "registry.staging.replicated.com",
Proxy: "proxy.staging.replicated.com",
}
}
if strings.HasSuffix(u.Hostname(), ".okteto.repldev.com") {
hostnameParts := strings.Split(u.Hostname(), ".")
if len(hostnameParts) == 4 {
parts := strings.Split(hostnameParts[0], "-")
if len(parts) == 3 {
namespace := parts[2]
return &RegistryProxyInfo{
Registry: fmt.Sprintf("vendor-registry-v2-%s.okteto.repldev.com", namespace),
Proxy: fmt.Sprintf("registry-proxy-%s.okteto.repldev.com", namespace),
}
}
}
}
return defaultInfo
}
func (r *RegistryProxyInfo) ToSlice() []string {
return []string{
r.Proxy,
r.Registry,
}
}
func SecretNameFromPrefix(namePrefix string) string {
if namePrefix == "" {
return ""
}
return fmt.Sprintf("%s-registry", namePrefix)
}
func PullSecretForRegistries(registries []string, username, password string, appNamespace string, namePrefix string) (ImagePullSecrets, error) {
dockercfgAuth := DockercfgAuth{
Auth: base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password))),
}
dockerCfgJSON := DockerCfgJSON{
Auths: map[string]DockercfgAuth{},
}
for _, r := range registries {
// we can get "host/namespace" here, which can break parts of kots that use hostname to lookup secret.
host := strings.Split(r, "/")[0]
dockerCfgJSON.Auths[host] = dockercfgAuth
}
secretData, err := json.Marshal(dockerCfgJSON)
if err != nil {
return ImagePullSecrets{}, errors.Wrap(err, "failed to marshal pull secret data")
}
secrets := ImagePullSecrets{
AdminConsoleSecret: &corev1.Secret{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Secret",
},
ObjectMeta: metav1.ObjectMeta{
Name: "kotsadm-replicated-registry",
Namespace: appNamespace,
Annotations: secretAnnotations,
},
Type: corev1.SecretTypeDockerConfigJson,
Data: map[string][]byte{
".dockerconfigjson": secretData,
},
},
}
if namePrefix == "" {
return secrets, nil
}
secrets.AppSecret = &corev1.Secret{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Secret",
},
ObjectMeta: metav1.ObjectMeta{
Name: SecretNameFromPrefix(namePrefix),
Namespace: appNamespace,
Annotations: secretAnnotations,
},
Type: corev1.SecretTypeDockerConfigJson,
Data: map[string][]byte{
".dockerconfigjson": secretData,
},
}
return secrets, nil
}
func EnsureDockerHubSecret(username string, password string, namespace string, clientset *kubernetes.Clientset) error {
dockerHubSecretMutex.Lock()
defer dockerHubSecretMutex.Unlock()
newSecret, err := PullSecretForDockerHub(username, password, namespace)
if err != nil {
return errors.Wrap(err, "failed to build pull secret for dockerhub")
}
existingSecret, err := clientset.CoreV1().Secrets(namespace).Get(context.TODO(), DockerHubSecretName, metav1.GetOptions{})
if err != nil {
if !kuberneteserrors.IsNotFound(err) {
return errors.Wrap(err, "failed to get pull secret for dockerhub")
}
_, err = clientset.CoreV1().Secrets(namespace).Create(context.TODO(), newSecret, metav1.CreateOptions{})
if err != nil {
return errors.Wrap(err, "failed to create dockerhub secret")
}
return nil
}
// Ignore error, if JSON is bad or missing, we should replace it anyway
existingCreds, _ := GetCredentialsForRegistryFromConfigJSON(existingSecret.Data[".dockerconfigjson"], DockerHubRegistryName)
if existingCreds.Username == username && existingCreds.Password == password {
return ErrDockerHubCredentialsExist
}
existingSecret.Data = newSecret.DeepCopy().Data
_, err = clientset.CoreV1().Secrets(namespace).Update(context.TODO(), newSecret, metav1.UpdateOptions{})
if err != nil {
return errors.Wrap(err, "failed to update dockerhub secret")
}
return nil
}
func PullSecretForDockerHub(username string, password string, kuberneteNamespace string) (*corev1.Secret, error) {
dockercfgAuth := DockercfgAuth{
Auth: base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password))),
}
dockerCfgJSON := DockerCfgJSON{
Auths: map[string]DockercfgAuth{
DockerHubRegistryName: dockercfgAuth,
},
}
secretData, err := json.Marshal(dockerCfgJSON)
if err != nil {
return nil, errors.Wrap(err, "failed to marshal pull secret data")
}
secret := &corev1.Secret{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Secret",
},
ObjectMeta: metav1.ObjectMeta{
Name: DockerHubSecretName,
Namespace: kuberneteNamespace,
},
Type: corev1.SecretTypeDockerConfigJson,
Data: map[string][]byte{
".dockerconfigjson": secretData,
},
}
return secret, nil
}
func GetDockerHubCredentials(clientset kubernetes.Interface, namespace string) (Credentials, error) {
imagePullSecret, err := clientset.CoreV1().Secrets(namespace).Get(context.TODO(), DockerHubSecretName, metav1.GetOptions{})
if err != nil {
if kuberneteserrors.IsNotFound(err) {
return Credentials{}, nil
}
return Credentials{}, errors.Wrap(err, "failed to get existing dockerhub secret")
}
dockerConfigJson := imagePullSecret.Data[".dockerconfigjson"]
if len(dockerConfigJson) == 0 {
return Credentials{}, nil
}
return GetCredentialsForRegistryFromConfigJSON(dockerConfigJson, DockerHubRegistryName)
}
func GetDockerHubPullSecret(clientset kubernetes.Interface, namespace string, appNamespace string, namePrefix string) (*corev1.Secret, error) {
if namePrefix == "" {
return nil, nil
}
secret, err := clientset.CoreV1().Secrets(namespace).Get(context.TODO(), DockerHubSecretName, metav1.GetOptions{})
if err != nil {
if kuberneteserrors.IsNotFound(err) {
return nil, nil
}
return nil, errors.Wrap(err, "failed to get existing dockerhub secret")
}
cleanSecret := &corev1.Secret{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Secret",
},
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("%s-%s", namePrefix, DockerHubSecretName),
Namespace: appNamespace,
Annotations: secretAnnotations,
},
Type: corev1.SecretTypeDockerConfigJson,
Data: secret.DeepCopy().Data,
}
return cleanSecret, nil
}
func GetCredentialsForRegistryFromConfigJSON(configJson []byte, registry string) (Credentials, error) {
creds, err := GetCredentialsFromConfigJSON(configJson)
if err != nil {
return Credentials{}, errors.Wrap(err, "failed parse config json")
}
c, ok := creds[registry]
if !ok {
return Credentials{}, nil
}
return c, nil
}
func GetCredentialsFromConfigJSON(configJson []byte) (map[string]Credentials, error) {
if len(configJson) == 0 {
return nil, errors.New("docker config JSON data is empty")
}
dockerCfgJSON := DockerCfgJSON{}
err := json.Unmarshal(configJson, &dockerCfgJSON)
if err != nil {
return nil, errors.Wrap(err, "failed to unmarshal config json")
}
result := map[string]Credentials{}
for registry, auth := range dockerCfgJSON.Auths {
decoded, err := base64.StdEncoding.DecodeString(auth.Auth)
if err != nil {
return nil, errors.Wrap(err, "failed to decode auth string")
}
parts := strings.SplitN(string(decoded), ":", 2)
if len(parts) != 2 {
return nil, errors.Errorf("expected 2 parts in the string, but found %d", len(parts))
}
result[registry] = Credentials{
Username: parts[0],
Password: parts[1],
}
}
return result, nil
}