/
push.go
300 lines (264 loc) · 8.16 KB
/
push.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
/*
Copyright 2022 The KubeVela Authors.
Licensed 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 addon
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
cm "github.com/chartmuseum/helm-push/pkg/chartmuseum"
cmhelm "github.com/chartmuseum/helm-push/pkg/helm"
"github.com/fatih/color"
helmrepo "helm.sh/helm/v3/pkg/repo"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// PushCmd is the command object to initiate a push command to ChartMuseum
type PushCmd struct {
ChartName string
AppVersion string
ChartVersion string
RepoName string
Username string
Password string
AccessToken string
AuthHeader string
ContextPath string
ForceUpload bool
UseHTTP bool
CaFile string
CertFile string
KeyFile string
InsecureSkipVerify bool
Out io.Writer
Timeout int64
KeepChartMetadata bool
// We need it to search in addon registries.
// If you use URL, instead of registry names, then it is not needed.
Client client.Client
}
// Push pushes addons (i.e. Helm Charts) to ChartMuseum.
// It will package the addon into a Helm Chart if necessary.
func (p *PushCmd) Push(ctx context.Context) error {
var repo *cmhelm.Repo
var err error
// Get the user specified Helm repo
repo, err = GetHelmRepo(ctx, p.Client, p.RepoName)
if err != nil {
return err
}
// Make the addon dir a Helm Chart
// The user can decide if they want Chart.yaml be in sync with addon metadata.yaml
// By default, it will recreate Chart.yaml according to addon metadata.yaml
err = MakeChartCompatible(p.ChartName, !p.KeepChartMetadata)
// `Not a directory` errors are ignored, that's fine,
// since .tgz files are also supported.
if err != nil && !strings.Contains(err.Error(), "is not a directory") {
return err
}
// Get chart from a directory or .tgz package
chart, err := cmhelm.GetChartByName(p.ChartName)
if err != nil {
return err
}
// Override chart version using specified version
if p.ChartVersion != "" {
chart.SetVersion(p.ChartVersion)
}
// Override app version using specified version
if p.AppVersion != "" {
chart.SetAppVersion(p.AppVersion)
}
// Override username and password using specified values
username := repo.Config.Username
password := repo.Config.Password
if p.Username != "" {
username = p.Username
}
if p.Password != "" {
password = p.Password
}
// Unset accessToken if repo credentials are provided
if username != "" && password != "" {
p.AccessToken = ""
}
// In case the repo is stored with cm:// protocol,
// (if that's somehow possible with KubeVela addon registries)
// use http instead,
// otherwise keep as it-is.
var url string
if p.UseHTTP {
url = strings.Replace(repo.Config.URL, "cm://", "http://", 1)
} else {
url = strings.Replace(repo.Config.URL, "cm://", "https://", 1)
}
cmClient, err := cm.NewClient(
cm.URL(url),
cm.Username(username),
cm.Password(password),
cm.AccessToken(p.AccessToken),
cm.AuthHeader(p.AuthHeader),
cm.ContextPath(p.ContextPath),
cm.CAFile(p.CaFile),
cm.CertFile(p.CertFile),
cm.KeyFile(p.KeyFile),
cm.InsecureSkipVerify(p.InsecureSkipVerify),
cm.Timeout(p.Timeout),
)
if err != nil {
return err
}
// Use a temporary dir to hold packaged .tgz Charts
tmp, err := os.MkdirTemp("", "helm-push-")
if err != nil {
return err
}
defer func(path string) {
_ = os.RemoveAll(path)
}(tmp)
// Package Chart into .tgz packages for uploading to ChartMuseum
chartPackagePath, err := cmhelm.CreateChartPackage(chart, tmp)
if err != nil {
return err
}
_, _ = fmt.Fprintf(os.Stderr, "Pushing %s to %s... ",
color.New(color.Bold).Sprintf(filepath.Base(chartPackagePath)),
formatRepoNameAndURL(p.RepoName, repo.Config.URL),
)
// Push Chart to ChartMuseum
resp, err := cmClient.UploadChartPackage(chartPackagePath, p.ForceUpload)
if err != nil {
return err
}
defer func() {
_ = resp.Body.Close()
}()
return handlePushResponse(resp)
}
// GetHelmRepo searches for a Helm repo by name.
// By saying name, it can actually be a URL or a name.
// If a URL is provided, a temp repo object is returned.
// If a name is provided, we will try to find it in local addon registries (only Helm type).
func GetHelmRepo(ctx context.Context, c client.Client, repoName string) (*cmhelm.Repo, error) {
var repo *cmhelm.Repo
var err error
// If RepoName looks like a URL (https / http), just create a temp repo object.
// We do not look for it in local addon registries.
if regexp.MustCompile(`^https?://`).MatchString(repoName) {
repo, err = cmhelm.TempRepoFromURL(repoName)
if err != nil {
return nil, err
}
return repo, nil
}
// Otherwise, search for in it in the local addon registries.
ds := NewRegistryDataStore(c)
registries, err := ds.ListRegistries(ctx)
if err != nil {
return nil, err
}
var matchedEntry *helmrepo.Entry
// Search for the target repo name in addon registries
for _, reg := range registries {
// We are only interested in Helm registries.
if reg.Helm == nil {
continue
}
if reg.Name == repoName {
matchedEntry = &helmrepo.Entry{
Name: reg.Name,
URL: reg.Helm.URL,
Username: reg.Helm.Username,
Password: reg.Helm.Password,
}
break
}
}
if matchedEntry == nil {
return nil, fmt.Errorf("we cannot find Helm repository %s. Make sure you hava added it using `vela addon registry add` and it is a Helm repository", repoName)
}
// Use the repo found locally.
repo = &cmhelm.Repo{ChartRepository: &helmrepo.ChartRepository{Config: matchedEntry}}
return repo, nil
}
// SetFieldsFromEnv sets fields in PushCmd from environment variables
func (p *PushCmd) SetFieldsFromEnv() {
if v, ok := os.LookupEnv("HELM_REPO_USERNAME"); ok && p.Username == "" {
p.Username = v
}
if v, ok := os.LookupEnv("HELM_REPO_PASSWORD"); ok && p.Password == "" {
p.Password = v
}
if v, ok := os.LookupEnv("HELM_REPO_ACCESS_TOKEN"); ok && p.AccessToken == "" {
p.AccessToken = v
}
if v, ok := os.LookupEnv("HELM_REPO_AUTH_HEADER"); ok && p.AuthHeader == "" {
p.AuthHeader = v
}
if v, ok := os.LookupEnv("HELM_REPO_CONTEXT_PATH"); ok && p.ContextPath == "" {
p.ContextPath = v
}
if v, ok := os.LookupEnv("HELM_REPO_USE_HTTP"); ok {
p.UseHTTP, _ = strconv.ParseBool(v)
}
if v, ok := os.LookupEnv("HELM_REPO_CA_FILE"); ok && p.CaFile == "" {
p.CaFile = v
}
if v, ok := os.LookupEnv("HELM_REPO_CERT_FILE"); ok && p.CertFile == "" {
p.CertFile = v
}
if v, ok := os.LookupEnv("HELM_REPO_KEY_FILE"); ok && p.KeyFile == "" {
p.KeyFile = v
}
if v, ok := os.LookupEnv("HELM_REPO_INSECURE"); ok {
p.InsecureSkipVerify, _ = strconv.ParseBool(v)
}
}
// handlePushResponse checks response from ChartMuseum
func handlePushResponse(resp *http.Response) error {
if resp.StatusCode != 201 && resp.StatusCode != 202 {
_, _ = fmt.Fprintf(os.Stderr, "%s\n", color.RedString("Failed"))
b, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
return getChartMuseumError(b, resp.StatusCode)
}
_, _ = fmt.Fprintf(os.Stderr, "%s\n", color.GreenString("Done"))
return nil
}
// getChartMuseumError checks error messages from the response
func getChartMuseumError(b []byte, code int) error {
var er struct {
Error string `json:"error"`
}
err := json.Unmarshal(b, &er)
if err != nil || er.Error == "" {
return fmt.Errorf("%d: could not properly parse response JSON: %s", code, string(b))
}
return fmt.Errorf("%d: %s", code, er.Error)
}
func formatRepoNameAndURL(name, url string) string {
if name == "" || regexp.MustCompile(`^https?://`).MatchString(name) {
return color.BlueString(url)
}
return fmt.Sprintf("%s(%s)",
color.New(color.Bold).Sprintf(name),
color.BlueString(url),
)
}