This repository has been archived by the owner on Feb 9, 2024. It is now read-only.
/
repo.go
302 lines (281 loc) · 8.63 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
302
/*
Copyright 2018 Gravitational, Inc.
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 helm
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"github.com/gravitational/gravity/lib/defaults"
"github.com/gravitational/gravity/lib/loc"
"github.com/gravitational/gravity/lib/pack"
"github.com/gravitational/gravity/lib/schema"
"github.com/gravitational/gravity/lib/storage"
"github.com/gravitational/gravity/lib/utils"
helmutils "github.com/gravitational/gravity/lib/utils/helm"
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/chart/loader"
"helm.sh/helm/v3/pkg/chartutil"
"helm.sh/helm/v3/pkg/provenance"
"helm.sh/helm/v3/pkg/repo"
"github.com/docker/docker/pkg/archive"
"github.com/ghodss/yaml"
"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
)
// Repository defines interface for a Helm repository backend.
type Repository interface {
// FetchChart returns the specified application as a Helm chart tarball.
FetchChart(loc.Locator) (io.ReadCloser, error)
// GetIndexFile returns the chart repository index file.
GetIndexFile() (io.Reader, error)
// AddToIndex adds the specified application to the repository index.
AddToIndex(locator loc.Locator, upsert bool) error
// RemoveFromIndex removes the specified application from the repository index.
RemoveFromIndex(loc.Locator) error
// RebuildIndex fully rebuilds the chart repository index.
RebuildIndex() error
}
// Config is the chart repository configuration.
type Config struct {
// Packages is the cluster package service.
Packages pack.PackageService
// Backend is the cluster backend.
Backend storage.Backend
}
type clusterRepository struct {
// Config is the chart repository configuration.
Config
// FieldLogger is used for logging.
logrus.FieldLogger
}
// NewRepository returns a new cluster chart repository.
func NewRepository(config Config) (Repository, error) {
return &clusterRepository{
Config: config,
FieldLogger: logrus.WithField(trace.Component, "helm.repo"),
}, nil
}
// FetchChart returns the specified application as a Helm chart tarball.
func (r *clusterRepository) FetchChart(locator loc.Locator) (io.ReadCloser, error) {
_, reader, err := r.Packages.ReadPackage(locator)
if err != nil {
return nil, trace.Wrap(err)
}
defer reader.Close()
tmpDir, err := ioutil.TempDir("", "package")
if err != nil {
return nil, trace.Wrap(err)
}
defer os.RemoveAll(tmpDir)
// Unpack application resources (w/o registry) into temporary directory.
err = archive.Untar(reader, tmpDir, &archive.TarOptions{
NoLchown: true,
ExcludePatterns: []string{"registry"},
})
if err != nil {
return nil, trace.Wrap(err)
}
// Load and package a Helm chart.
chart, err := loader.LoadDir(filepath.Join(tmpDir, "resources"))
if err != nil {
return nil, trace.Wrap(err)
}
chartDir, err := ioutil.TempDir("", "chart")
if err != nil {
return nil, trace.Wrap(err)
}
path, err := chartutil.Save(chart, chartDir)
if err != nil {
return nil, trace.Wrap(err)
}
chartReader, err := os.Open(path)
if err != nil {
return nil, trace.Wrap(err)
}
return &utils.CleanupReadCloser{
ReadCloser: chartReader,
Cleanup: func() {
os.RemoveAll(chartDir)
},
}, nil
}
// GetIndexFile returns the chart repository index file.
func (r *clusterRepository) GetIndexFile() (io.Reader, error) {
indexFile, err := r.Backend.GetIndexFile()
if err != nil && !trace.IsNotFound(err) {
return nil, trace.Wrap(err)
}
if trace.IsNotFound(err) {
indexFile = repo.NewIndexFile()
}
data, err := yaml.Marshal(indexFile)
if err != nil {
return nil, trace.Wrap(err)
}
return bytes.NewReader(data), nil
}
// AddToIndex adds the specified application to the repository index.
func (r *clusterRepository) AddToIndex(locator loc.Locator, upsert bool) error {
r.Infof("Adding %v to chart repo index.", locator)
chart, err := r.chartForLocator(locator)
if err != nil {
return trace.Wrap(err)
}
digest, err := r.digest(locator)
if err != nil {
return trace.Wrap(err)
}
indexFile, err := r.Backend.GetIndexFile()
if err != nil && !trace.IsNotFound(err) {
return trace.Wrap(err)
}
if trace.IsNotFound(err) {
indexFile = repo.NewIndexFile()
err = indexFile.MustAdd(chart.Metadata, r.chartURL(chart), "", digest)
if err != nil {
return trace.Wrap(err)
}
return r.Backend.CompareAndSwapIndexFile(indexFile, nil)
}
if indexFile.Has(chart.Metadata.Name, chart.Metadata.Version) {
if !upsert {
return trace.AlreadyExists("index file already has chart %v:%v",
chart.Metadata.Name, chart.Metadata.Version)
}
// Delete the old entry first because "add" will not check for dupes.
err := r.RemoveFromIndex(locator)
if err != nil {
return trace.Wrap(err)
}
indexFile, err = r.Backend.GetIndexFile()
if err != nil {
return trace.Wrap(err)
}
}
prevIndexFile := helmutils.CopyIndexFile(*indexFile)
err = indexFile.MustAdd(chart.Metadata, r.chartURL(chart), "", digest)
if err != nil {
return trace.Wrap(err)
}
indexFile.SortEntries()
return r.Backend.CompareAndSwapIndexFile(indexFile, prevIndexFile)
}
// RemoveFromIndex removes the specified application from the repository index.
func (r *clusterRepository) RemoveFromIndex(locator loc.Locator) error {
r.Infof("Removing %v from chart repo index.", locator)
indexFile, err := r.Backend.GetIndexFile()
if err != nil && !trace.IsNotFound(err) {
return trace.Wrap(err)
}
if trace.IsNotFound(err) {
return nil
}
prevIndexFile := helmutils.CopyIndexFile(*indexFile)
L:
for name, versions := range indexFile.Entries {
if name != locator.Name {
continue
}
for i, version := range versions {
if version.Version != locator.Version {
continue
}
indexFile.Entries[name] = append(
versions[:i], versions[i+1:]...)
if len(indexFile.Entries[name]) == 0 {
delete(indexFile.Entries, name)
}
break L
}
}
return r.Backend.CompareAndSwapIndexFile(indexFile, prevIndexFile)
}
// RebuildIndex fully rebuilds chart repository index.
//
// This method is for development/debugging or disaster-recovery cases only
// (e.g. if index gets corrupted) as it iterates over all cluster packages.
func (r *clusterRepository) RebuildIndex() error {
r.Warn("Rebuilding chart repository index.")
indexFile := repo.NewIndexFile()
err := pack.ForeachPackageInRepo(r.Packages, defaults.SystemAccountOrg,
func(e pack.PackageEnvelope) error {
// Skip not application images.
if len(e.Manifest) == 0 {
return nil
}
manifest, err := schema.ParseManifestYAMLNoValidate(e.Manifest)
if err != nil {
return trace.Wrap(err)
}
if manifest.Kind != schema.KindApplication {
return nil
}
chart, err := r.chartForLocator(e.Locator)
if err != nil {
return trace.Wrap(err)
}
digest, err := r.digest(e.Locator)
if err != nil {
return trace.Wrap(err)
}
r.Debugf("Adding to the index: %v.", e.Locator)
err = indexFile.MustAdd(chart.Metadata, r.chartURL(chart), "", digest)
if err != nil {
return trace.Wrap(err)
}
return nil
})
if err != nil {
return trace.Wrap(err)
}
indexFile.SortEntries()
return r.Backend.UpsertIndexFile(*indexFile)
}
// chartForLocator returns the specified application as a Helm chart archive.
func (r *clusterRepository) chartForLocator(locator loc.Locator) (*chart.Chart, error) {
_, reader, err := r.Packages.ReadPackage(locator)
if err != nil {
return nil, trace.Wrap(err)
}
defer reader.Close()
chart, err := loader.LoadArchive(reader)
if err != nil {
return nil, trace.Wrap(err)
}
return chart, nil
}
// chartURL returns URL of the specified chart in the repository.
func (r *clusterRepository) chartURL(chart *chart.Chart) string {
return fmt.Sprintf("%v/charts/%v", r.Packages.PortalURL(),
helmutils.ToChartFilename(chart.Metadata.Name, chart.Metadata.Version))
}
// digest returns a sha256 hash of the specified application data.
func (r *clusterRepository) digest(locator loc.Locator) (string, error) {
_, reader, err := r.Packages.ReadPackage(locator)
if err != nil {
return "", trace.Wrap(err)
}
defer reader.Close()
digest, err := provenance.Digest(reader)
if err != nil {
return "", trace.Wrap(err)
}
return digest, nil
}
const (
// BackendLocal represents cluster-local chart repository backend.
BackendLocal = "local"
)