/
registry.go
292 lines (268 loc) · 8.44 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
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License 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 trait
import (
"encoding/json"
"errors"
"fmt"
"regexp"
"strings"
base64 "encoding/base64"
v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1"
traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait"
"github.com/apache/camel-k/v2/pkg/platform"
"github.com/apache/camel-k/v2/pkg/util/defaults"
"github.com/apache/camel-k/v2/pkg/util/kubernetes"
"github.com/apache/camel-k/v2/pkg/util/registry"
corev1 "k8s.io/api/core/v1"
"k8s.io/utils/pointer"
ctrl "sigs.k8s.io/controller-runtime/pkg/client"
)
type registryTrait struct {
BaseTrait
traitv1.RegistryTrait `property:",squash"`
}
func newRegistryTrait() Trait {
return ®istryTrait{
BaseTrait: NewBaseTrait("registry", 1650),
}
}
// InfluencesKit overrides base class method.
func (t *registryTrait) InfluencesKit() bool {
return true
}
func (t *registryTrait) Configure(e *Environment) (bool, *TraitCondition, error) {
// disabled by default
if e.IntegrationKit == nil || !pointer.BoolDeref(t.Enabled, false) {
return false, nil, nil
}
enabled := e.IntegrationKitInPhase(v1.IntegrationKitPhaseBuildSubmitted)
if enabled {
condition := NewIntegrationCondition(
"Registry",
v1.IntegrationConditionTraitInfo,
corev1.ConditionTrue,
traitConfigurationReason,
"Registry trait is deprecated. It may be removed in future version. Read documentation to find alternatives (likely JVM trait).",
)
return true, condition, nil
}
return false, nil, nil
}
func (t *registryTrait) Apply(e *Environment) error {
registryAddress := e.Platform.Status.Build.Registry.Address
if registryAddress == "" && e.Platform.Status.Cluster == v1.IntegrationPlatformClusterOpenShift {
registryAddress = defaults.OpenShiftRegistryAddress
}
if registryAddress == "" {
return errors.New("could not figure out Image Registry URL, please set it manually")
}
build := getBuilderTask(e.Pipeline)
registryCa := e.Platform.Status.Build.Registry.CA
registrySecret := e.Platform.Status.Build.Registry.Secret
if e.Platform.Status.Cluster == v1.IntegrationPlatformClusterOpenShift {
if registryCa == "" {
ca, err := getOpenShiftImageRegistryCA(e)
if err != nil {
return err
}
registryCa = ca
}
if registrySecret == "" {
secret, err := getOpenShiftRegistrySecret(e)
if err != nil {
return err
}
registrySecret = secret
}
}
if registryCa != "" {
err := addImageRegistryCaToMavenBuild(registryCa, build)
if err != nil {
return err
}
}
if registrySecret != "" {
server, err := extractMavenServerCredentialsFromSecret(registrySecret, e, registryAddress)
if err != nil {
return err
}
build.Maven.Servers = append(build.Maven.Servers, server)
}
addRegistryAndExtensionToMaven(registryAddress, build, e.Platform)
return nil
}
func addRegistryAndExtensionToMaven(registryAddress string, build *v1.BuilderTask, platform *v1.IntegrationPlatform) {
organization := platform.Status.Build.Registry.Organization
if organization == "" {
organization = platform.Namespace
}
registryAddress = fmt.Sprintf("%s/%s", registryAddress, organization)
ext := v1.MavenArtifact{
GroupID: "com.github.johnpoth",
ArtifactID: "wagon-docker-registry",
Version: "0.2.0",
}
policy := v1.RepositoryPolicy{
Enabled: true,
ChecksumPolicy: "fail",
}
repo := v1.Repository{
ID: "image-registry",
URL: "docker://" + registryAddress,
Snapshots: policy,
Releases: policy,
}
build.Maven.Repositories = append(build.Maven.Repositories, repo)
build.Maven.Extension = append(build.Maven.Extension, ext)
}
func getOpenShiftRegistrySecret(e *Environment) (string, error) {
// does not create it if it already exists
err := platform.CreateBuilderServiceAccount(e.Ctx, e.Client, e.Platform)
if err != nil {
return "", err
}
sa := corev1.ServiceAccount{}
key := ctrl.ObjectKey{
Name: platform.BuilderServiceAccount,
Namespace: e.Platform.Namespace,
}
err = e.Client.Get(e.Ctx, key, &sa)
if err != nil {
return "", err
}
for _, secret := range sa.Secrets {
if strings.Contains(secret.Name, "camel-k-builder-dockercfg") {
return secret.Name, nil
}
}
return "", nil
}
func extractMavenServerCredentialsFromSecret(registrySecret string, e *Environment, registryAddress string) (v1.Server, error) {
secret, err := kubernetes.GetSecret(e.Ctx, e.Client, registrySecret, e.Platform.Namespace)
if err != nil {
return v1.Server{}, err
}
if secret.Type == corev1.SecretTypeBasicAuth {
return v1.Server{
ID: "image-registry",
Username: string(secret.Data[corev1.BasicAuthUsernameKey]),
Password: string(secret.Data[corev1.BasicAuthPasswordKey]),
}, nil
}
secretData, err := getDockerConfig(secret)
if err != nil {
return v1.Server{}, err
}
dockerAuth := registry.DockerConfigList{}
err = json.Unmarshal(secretData, &dockerAuth)
if err != nil {
return v1.Server{}, err
}
config, ok := dockerAuth.Auths[registryAddress]
if !ok {
return v1.Server{}, fmt.Errorf("cannot resolve registry address %s in secret %s", registryAddress, registrySecret)
}
username := config.Username
password := config.Password
if username == "" && config.Auth != "" {
decoded := base64.StdEncoding.EncodeToString([]byte(config.Auth))
parts := strings.Split(decoded, ":")
if len(parts) == 2 {
username = strings.Split(decoded, ":")[0]
}
}
if password == "" && config.Auth != "" {
decoded := base64.StdEncoding.EncodeToString([]byte(config.Auth))
parts := strings.Split(decoded, ":")
if len(parts) == 2 {
password = strings.Split(decoded, ":")[1]
}
}
return v1.Server{
ID: "image-registry",
Username: username,
Password: password,
}, nil
}
func getDockerConfig(secret *corev1.Secret) ([]byte, error) {
if secret.Type == corev1.SecretTypeDockerConfigJson {
secretData, ok := secret.Data[corev1.DockerConfigJsonKey]
if !ok {
return nil, fmt.Errorf("cannot convert secret into Docker Config")
}
return secretData, nil
}
if secret.Type == corev1.SecretTypeDockercfg {
secretData, ok := secret.Data[corev1.DockerConfigKey]
if !ok {
return nil, fmt.Errorf("cannot convert secret into Docker config")
}
secretData = []byte(fmt.Sprintf("{ \"auths\": %s}", secretData))
return secretData, nil
}
return nil, fmt.Errorf("unsupported Secret type %s", secret.Type)
}
func getOpenShiftImageRegistryCA(e *Environment) (string, error) {
// does not create it if it already exists
err := platform.CreateBuilderServiceAccount(e.Ctx, e.Client, e.Platform)
if err != nil {
return "", err
}
sa := corev1.ServiceAccount{}
key := ctrl.ObjectKey{
Name: platform.BuilderServiceAccount,
Namespace: e.Platform.Namespace,
}
err = e.Client.Get(e.Ctx, key, &sa)
if err != nil {
return "", err
}
for _, secret := range sa.Secrets {
if strings.Contains(secret.Name, "camel-k-builder-token") {
return secret.Name + "/service-ca.crt", nil
}
}
return "", errors.New("could not find OpenShift Image Registry CA")
}
func addImageRegistryCaToMavenBuild(registryCa string, build *v1.BuilderTask) error {
secret, err := decodeSecretKeySelector(registryCa)
if err != nil {
return err
}
contains := false
for _, ca := range build.Maven.CASecrets {
if ca.Name == secret.Name && ca.Key == secret.Key {
contains = true
}
}
if !contains {
build.Maven.CASecrets = append(build.Maven.CASecrets, *secret)
}
return nil
}
func decodeSecretKeySelector(secretKey string) (*corev1.SecretKeySelector, error) {
r := regexp.MustCompile(`^([a-zA-Z0-9-]*)/([a-zA-Z0-9.].*)$`)
if !r.MatchString(secretKey) {
return nil, fmt.Errorf("illegal Maven CA certificates secret key selector, syntax: secret-name/secret-key")
}
match := r.FindStringSubmatch(secretKey)
return &corev1.SecretKeySelector{
LocalObjectReference: corev1.LocalObjectReference{
Name: match[1],
},
Key: match[2],
}, nil
}