-
Notifications
You must be signed in to change notification settings - Fork 874
/
helm_helper.go
353 lines (323 loc) · 10.9 KB
/
helm_helper.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
/*
Copyright 2021 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 helm
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"path"
"path/filepath"
"strings"
"time"
"github.com/pkg/errors"
"helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/chart/loader"
"helm.sh/helm/v3/pkg/chartutil"
"helm.sh/helm/v3/pkg/kube"
"helm.sh/helm/v3/pkg/release"
relutil "helm.sh/helm/v3/pkg/releaseutil"
"helm.sh/helm/v3/pkg/repo"
"helm.sh/helm/v3/pkg/storage"
"helm.sh/helm/v3/pkg/storage/driver"
appsv1 "k8s.io/api/apps/v1"
crdv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
kyaml "k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/rest"
k8scmdutil "k8s.io/kubectl/pkg/cmd/util"
"sigs.k8s.io/yaml"
utils2 "github.com/oam-dev/kubevela/pkg/apiserver/utils"
"github.com/oam-dev/kubevela/pkg/utils"
"github.com/oam-dev/kubevela/pkg/utils/common"
cmdutil "github.com/oam-dev/kubevela/pkg/utils/util"
)
const (
repoPatten = " repoUrl: %s"
valuesPatten = "repoUrl: %s, chart: %s, version: %s"
)
// Helper provides helper functions for common Helm operations
type Helper struct {
cache *utils2.MemoryCacheStore
}
// NewHelper creates a Helper
func NewHelper() *Helper {
return &Helper{}
}
// NewHelperWithCache creates a Helper with cache usually used by apiserver
func NewHelperWithCache() *Helper {
return &Helper{
cache: utils2.NewMemoryCacheStore(context.Background()),
}
}
// LoadCharts load helm chart from local or remote
func (h *Helper) LoadCharts(chartRepoURL string, opts *common.HTTPOption) (*chart.Chart, error) {
var err error
var chart *chart.Chart
if utils.IsValidURL(chartRepoURL) {
chartBytes, err := common.HTTPGetWithOption(context.Background(), chartRepoURL, opts)
if err != nil {
return nil, errors.New("error retrieving Helm Chart at " + chartRepoURL + ": " + err.Error())
}
ch, err := loader.LoadArchive(bytes.NewReader(chartBytes))
if err != nil {
return nil, errors.New("error retrieving Helm Chart at " + chartRepoURL + ": " + err.Error())
}
return ch, err
}
chart, err = loader.Load(chartRepoURL)
if err != nil {
return nil, err
}
return chart, nil
}
// UpgradeChartOptions options for upgrade chart
type UpgradeChartOptions struct {
Config *rest.Config
Detail bool
Logging cmdutil.IOStreams
Wait bool
ReuseValues bool
}
// UpgradeChart install or upgrade helm chart
func (h *Helper) UpgradeChart(ch *chart.Chart, releaseName, namespace string, values map[string]interface{}, config UpgradeChartOptions) (*release.Release, error) {
if ch == nil || len(ch.Templates) == 0 {
return nil, fmt.Errorf("empty chart provided for %s", releaseName)
}
config.Logging.Infof("Start upgrading Helm Chart %s in namespace %s\n", releaseName, namespace)
cfg, err := newActionConfig(config.Config, namespace, config.Detail, config.Logging)
if err != nil {
return nil, err
}
histClient := action.NewHistory(cfg)
var newRelease *release.Release
timeoutInMinutes := 18
releases, err := histClient.Run(releaseName)
if err != nil || len(releases) == 0 {
if errors.Is(err, driver.ErrReleaseNotFound) {
// fresh install
install := action.NewInstall(cfg)
install.Namespace = namespace
install.ReleaseName = releaseName
install.Wait = config.Wait
install.Timeout = time.Duration(timeoutInMinutes) * time.Minute
newRelease, err = install.Run(ch, values)
} else {
return nil, fmt.Errorf("could not retrieve history of releases associated to %s: %w", releaseName, err)
}
} else {
config.Logging.Infof("Found existing installation, overwriting...")
// check if the previous installation is still pending (e.g., waiting to complete)
for _, r := range releases {
if r.Info.Status == release.StatusPendingInstall || r.Info.Status == release.StatusPendingUpgrade ||
r.Info.Status == release.StatusPendingRollback {
return nil, fmt.Errorf("previous installation (e.g., using vela install or helm upgrade) is still in progress. Please try again in %d minutes", timeoutInMinutes)
}
}
// merge un-existing values into the values as user-input, because the helm chart upgrade didn't handle the new default values in the chart.
// the new default values <= the old custom values <= the new custom values
if config.ReuseValues {
// sort will sort the release by revision from old to new
relutil.SortByRevision(releases)
rel := releases[len(releases)-1]
// merge new values as the user input, follow the new user input for --set
values = chartutil.CoalesceTables(values, rel.Config)
}
// overwrite existing installation
install := action.NewUpgrade(cfg)
install.Namespace = namespace
install.Wait = config.Wait
install.Timeout = time.Duration(timeoutInMinutes) * time.Minute
// use the new default value set.
install.ReuseValues = false
newRelease, err = install.Run(releaseName, ch, values)
}
// check if install/upgrade worked
if err != nil {
return nil, fmt.Errorf("error when installing/upgrading Helm Chart %s in namespace %s: %w",
releaseName, namespace, err)
}
if newRelease == nil {
return nil, fmt.Errorf("failed to install release %s", releaseName)
}
return newRelease, nil
}
// UninstallRelease uninstalls the provided release
func (h *Helper) UninstallRelease(releaseName, namespace string, config *rest.Config, showDetail bool, logging cmdutil.IOStreams) error {
cfg, err := newActionConfig(config, namespace, showDetail, logging)
if err != nil {
return err
}
iCli := action.NewUninstall(cfg)
_, err = iCli.Run(releaseName)
if err != nil {
return fmt.Errorf("error when uninstalling Helm release %s in namespace %s: %w",
releaseName, namespace, err)
}
return nil
}
// ListVersions list available versions from repo
func (h *Helper) ListVersions(repoURL string, chartName string, skipCache bool, opts *common.HTTPOption) (repo.ChartVersions, error) {
i, err := h.GetIndexInfo(repoURL, skipCache, opts)
if err != nil {
return nil, err
}
return i.Entries[chartName], nil
}
// GetIndexInfo get index.yaml form given repo url
func (h *Helper) GetIndexInfo(repoURL string, skipCache bool, opts *common.HTTPOption) (*repo.IndexFile, error) {
repoURL = utils.Sanitize(repoURL)
if h.cache != nil && !skipCache {
if i := h.cache.Get(fmt.Sprintf(repoPatten, repoURL)); i != nil {
return i.(*repo.IndexFile), nil
}
}
var body []byte
if utils.IsValidURL(repoURL) {
indexURL, err := utils.JoinURL(repoURL, "index.yaml")
if err != nil {
return nil, err
}
body, err = common.HTTPGetWithOption(context.Background(), indexURL, opts)
if err != nil {
return nil, fmt.Errorf("download index file from %s failure %w", repoURL, err)
}
} else {
var err error
body, err = ioutil.ReadFile(path.Join(filepath.Clean(repoURL), "index.yaml"))
if err != nil {
return nil, fmt.Errorf("read index file from %s failure %w", repoURL, err)
}
}
i := &repo.IndexFile{}
if err := yaml.UnmarshalStrict(body, i); err != nil {
return nil, fmt.Errorf("parse index file from %s failure", repoURL)
}
if h.cache != nil {
h.cache.Put(fmt.Sprintf(repoPatten, repoURL), i, calculateCacheTimeFromIndex(len(i.Entries)))
}
return i, nil
}
// GetDeploymentsFromManifest get deployment from helm manifest
func GetDeploymentsFromManifest(helmManifest string) []*appsv1.Deployment {
deployments := []*appsv1.Deployment{}
dec := kyaml.NewYAMLToJSONDecoder(strings.NewReader(helmManifest))
for {
var deployment appsv1.Deployment
err := dec.Decode(&deployment)
if errors.Is(err, io.EOF) {
break
}
if err != nil {
continue
}
if strings.EqualFold(deployment.Kind, "deployment") {
deployments = append(deployments, &deployment)
}
}
return deployments
}
// GetCRDFromChart get crd from helm chart
func GetCRDFromChart(chart *chart.Chart) []*crdv1.CustomResourceDefinition {
crds := []*crdv1.CustomResourceDefinition{}
for _, crdFile := range chart.CRDs() {
var crd crdv1.CustomResourceDefinition
err := kyaml.Unmarshal(crdFile.Data, &crd)
if err != nil {
continue
}
crds = append(crds, &crd)
}
return crds
}
func newActionConfig(config *rest.Config, namespace string, showDetail bool, logging cmdutil.IOStreams) (*action.Configuration, error) {
restClientGetter := cmdutil.NewRestConfigGetterByConfig(config, namespace)
log := func(format string, a ...interface{}) {
if showDetail {
logging.Infof(format+"\n", a...)
}
}
kubeClient := &kube.Client{
Factory: k8scmdutil.NewFactory(restClientGetter),
Log: log,
}
client, err := kubeClient.Factory.KubernetesClientSet()
if err != nil {
return nil, err
}
s := driver.NewSecrets(client.CoreV1().Secrets(namespace))
s.Log = log
return &action.Configuration{
RESTClientGetter: restClientGetter,
Releases: storage.Init(s),
KubeClient: kubeClient,
Log: log,
}, nil
}
// ListChartsFromRepo list available helm charts in a repo
func (h *Helper) ListChartsFromRepo(repoURL string, skipCache bool, opts *common.HTTPOption) ([]string, error) {
i, err := h.GetIndexInfo(repoURL, skipCache, opts)
if err != nil {
return nil, err
}
res := make([]string, len(i.Entries))
j := 0
for s := range i.Entries {
res[j] = s
j++
}
return res, nil
}
// GetValuesFromChart will extract the parameter from a helm chart
func (h *Helper) GetValuesFromChart(repoURL string, chartName string, version string, skipCache bool, opts *common.HTTPOption) (map[string]interface{}, error) {
if h.cache != nil && !skipCache {
if v := h.cache.Get(fmt.Sprintf(valuesPatten, repoURL, chartName, version)); v != nil {
return v.(map[string]interface{}), nil
}
}
i, err := h.GetIndexInfo(repoURL, skipCache, opts)
if err != nil {
return nil, err
}
chartVersions, ok := i.Entries[chartName]
if !ok {
return nil, fmt.Errorf("cannot find chart %s in this repo", chartName)
}
var urls []string
for _, chartVersion := range chartVersions {
if chartVersion.Version == version {
urls = chartVersion.URLs
}
}
for _, u := range urls {
c, err := h.LoadCharts(u, opts)
if err != nil {
continue
}
if h.cache != nil {
h.cache.Put(fmt.Sprintf(valuesPatten, repoURL, chartName, version), c.Values, calculateCacheTimeFromIndex(len(i.Entries)))
}
return c.Values, nil
}
return nil, fmt.Errorf("cannot load chart from chart repo")
}
func calculateCacheTimeFromIndex(length int) time.Duration {
cacheTime := 3 * time.Minute
if length > 20 {
// huge helm repo like https://charts.bitnami.com/bitnami have too many(106) charts, generally user cannot modify it.
// need more cache time
cacheTime = 1 * time.Hour
}
return cacheTime
}