/
repo.go
301 lines (265 loc) · 7.97 KB
/
repo.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
// Copyright © 2023 Horizoncd.
//
// 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 chartmuseumbase
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
"path"
"time"
herrors "github.com/horizoncd/horizon/core/errors"
config "github.com/horizoncd/horizon/pkg/config/templaterepo"
perror "github.com/horizoncd/horizon/pkg/errors"
"github.com/horizoncd/horizon/pkg/templaterepo"
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/chart/loader"
"k8s.io/helm/pkg/tlsutil"
)
const (
kindHarbor = "harbor"
kindChartMuseum = "chartmuseum"
)
func init() {
templaterepo.Register(kindHarbor, NewRepo)
templaterepo.Register(kindChartMuseum, NewRepo)
}
type Metadata struct {
Name string `json:"name"`
Version string `json:"version"`
Description string `json:"description"`
APIVersion string `json:"apiVersion"`
Type string `json:"type"`
Urls []string `json:"urls"`
Created time.Time `json:"created"`
Digest string `json:"digest"`
}
type Stat struct {
Metadata Metadata `json:"metadata"`
}
type Repo struct {
kind string
prefix string
host *url.URL
token string
username string
password string
repoName string
client *http.Client
}
func NewRepo(config config.Repo) (templaterepo.TemplateRepo, error) {
host, err := url.Parse(config.Host)
if err != nil {
return nil, perror.Wrap(herrors.ErrParamInvalid,
fmt.Sprintf("url is incorrect: %v", err))
}
tlsConf, err := tlsutil.NewClientTLS(config.CertFile, config.KeyFile, config.CAFile)
if err != nil {
return nil, perror.Wrap(herrors.NewErrCreateFailed(herrors.TLS, err.Error()),
"failed to create TLS: %v")
}
tlsConf.InsecureSkipVerify = config.Insecure
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConf,
},
}
prefix := ""
if config.Kind == kindHarbor {
prefix = fmt.Sprintf("chartrepo/%s", config.RepoName)
}
return &Repo{
kind: config.Kind,
repoName: config.RepoName,
prefix: prefix,
host: host,
username: config.Username,
password: config.Password,
token: config.Token,
client: client,
}, nil
}
func (h *Repo) GetLoc() string {
if h.kind == kindHarbor {
return fmt.Sprintf("%s://%s/chartrepo/%s", h.host.Scheme, h.host.Host, url.PathEscape(h.repoName))
}
return fmt.Sprintf("%s://%s", h.host.Scheme, h.host.Host)
}
func (h *Repo) UploadChart(chartPkg *chart.Chart) error {
var buf bytes.Buffer
bodyWriter := multipart.NewWriter(&buf)
chartWriter, err := bodyWriter.CreateFormFile("chart",
fmt.Sprintf("%s-%s", chartPkg.Metadata.Name, chartPkg.Metadata.Version))
if err != nil {
return perror.Wrap(herrors.ErrHTTPRequestFailed,
fmt.Sprintf("failed to create multipart writer: %v", err))
}
err = templaterepo.ChartSerialize(chartPkg, chartWriter)
if err != nil {
return err
}
contentType := bodyWriter.FormDataContentType()
err = bodyWriter.Close()
if err != nil {
return perror.Wrap(herrors.ErrHTTPRequestFailed,
fmt.Sprintf("failed to create multipart writer: %v", err))
}
resp, err := h.do(http.MethodPost, h.uploadLink(),
ioutil.NopCloser(&buf), http.Header{"Content-Type": []string{contentType}})
if err != nil {
return err
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != 201 && resp.StatusCode != 202 {
var b []byte
b, err = ioutil.ReadAll(resp.Body)
if err != nil {
return perror.Wrap(herrors.ErrReadFailed,
fmt.Sprintf("failed to read response: %v", err))
}
return perror.Wrap(herrors.ErrHTTPRespNotAsExpected,
fmt.Sprintf("%s: %s", resp.Status, string(b)))
}
return nil
}
func (h *Repo) DeleteChart(name string, version string) error {
resp, err := h.do(http.MethodDelete, h.deleteLink(name, version), nil)
if err != nil {
return err
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != 200 {
var b []byte
b, err = ioutil.ReadAll(resp.Body)
if err != nil {
return perror.Wrap(herrors.ErrReadFailed,
fmt.Sprintf("failed to read response: %v", err))
}
return perror.Wrap(herrors.ErrHTTPRespNotAsExpected,
fmt.Sprintf("%s: %s", resp.Status, string(b)))
}
return nil
}
func (h *Repo) ExistChart(name string, version string) (bool, error) {
_, err := h.statChart(name, version)
if err != nil {
return false, err
}
return true, nil
}
func (h *Repo) GetChart(name string, version string, lastSyncAt time.Time) (*chart.Chart, error) {
resp, err := h.do(http.MethodGet, h.downloadLink(name, version), nil)
if err != nil {
return nil, err
}
defer func() {
_ = resp.Body.Close()
}()
b, err := ioutil.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
if err != nil {
return nil, perror.Wrap(herrors.ErrReadFailed,
fmt.Sprintf("failed to read response: %v", err))
}
if resp.StatusCode == http.StatusNotFound {
return nil, perror.Wrap(herrors.NewErrNotFound(herrors.TemplateReleaseInRepo,
fmt.Sprintf("%s: %s", resp.Status, string(b))),
"not found")
}
return nil, perror.Wrap(herrors.ErrHTTPRespNotAsExpected,
fmt.Sprintf("%s: %s", resp.Status, string(b)))
}
chartPackage, err := loader.LoadArchive(bytes.NewReader(b))
if err != nil {
return nil, perror.Wrap(herrors.ErrLoadChartArchive,
fmt.Sprintf("failed to load archive: %v", err))
}
return chartPackage, nil
}
func (h *Repo) statChart(name string, version string) (*Metadata, error) {
resp, err := h.do(http.MethodGet, h.statLink(name, version), nil)
if err != nil {
return nil, err
}
defer func() {
_ = resp.Body.Close()
}()
var stat Stat
b, err := ioutil.ReadAll(resp.Body)
if resp.StatusCode != 200 {
if err != nil {
return nil, perror.Wrap(herrors.ErrReadFailed,
fmt.Sprintf("failed to read response: %v", err))
}
return nil, perror.Wrap(herrors.ErrHTTPRespNotAsExpected,
fmt.Sprintf("%s: %s, chart name = %s version = %s", resp.Status, string(b), name, version))
}
err = json.Unmarshal(b, &stat)
if err != nil {
return nil, perror.Wrap(herrors.ErrParamInvalid,
fmt.Sprintf("could not unmarshal stat: %v", err))
}
return &stat.Metadata, nil
}
func (h *Repo) do(method, url string, body io.Reader, headers ...http.Header) (*http.Response, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, perror.Wrap(herrors.ErrHTTPRequestFailed,
fmt.Sprintf("failed to create request: %v", err))
}
for _, header := range headers {
for k, values := range header {
for _, v := range values {
req.Header.Add(k, v)
}
}
}
req.SetBasicAuth(h.username, h.password)
resp, err := h.client.Do(req)
if err != nil {
return nil, perror.Wrap(herrors.ErrHTTPRequestFailed,
fmt.Sprintf("failed to create send request: %v", err))
}
return resp, nil
}
func (h *Repo) linkWithSchemeAndHost() string {
return fmt.Sprintf("%s://%s", h.host.Scheme, h.host.Host)
}
func (h *Repo) uploadLink() string {
return fmt.Sprintf("%s/%s?force",
h.linkWithSchemeAndHost(), path.Join("api", h.prefix, "charts"))
}
func (h *Repo) deleteLink(name, version string) string {
return fmt.Sprintf("%s/%s",
h.linkWithSchemeAndHost(), path.Join("api", h.prefix, "charts",
url.PathEscape(name), url.PathEscape(version)))
}
func (h *Repo) statLink(name, version string) string {
return fmt.Sprintf("%s/%s",
h.linkWithSchemeAndHost(), path.Join("api", h.prefix, "charts",
url.PathEscape(name), url.PathEscape(version)))
}
func (h *Repo) downloadLink(name, version string) string {
return fmt.Sprintf("%s/%s/%s-%s.tgz",
h.linkWithSchemeAndHost(), path.Join(h.prefix, "charts"),
url.PathEscape(name), url.PathEscape(version))
}