/
helm.go
320 lines (262 loc) · 7.75 KB
/
helm.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
package helm
import (
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/181192/ops-cli/pkg/cmd/cmdutils"
"github.com/gofrs/flock"
"github.com/pkg/errors"
logger "github.com/sirupsen/logrus"
"helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/chart/loader"
"helm.sh/helm/v3/pkg/cli"
"helm.sh/helm/v3/pkg/cli/values"
"helm.sh/helm/v3/pkg/getter"
"helm.sh/helm/v3/pkg/repo"
"helm.sh/helm/v3/pkg/storage/driver"
"sigs.k8s.io/yaml"
)
var (
settings = cli.New()
)
type repoAddOptions struct {
name string
url string
username string
password string
noUpdate bool
certFile string
keyFile string
caFile string
repoFile string
repoCache string
}
func debug(format string, v ...interface{}) {
if settings.Debug {
format = fmt.Sprintf("[debug] %s\n", format)
logger.Debug(fmt.Sprintf(format, v...))
}
}
// PullChart pulls a chart from helm registry
func PullChart(chartName string, chartVersion string) error {
logger.Debug("New pull client")
actionConfig := new(action.Configuration)
actionConfig.Init(settings.RESTClientGetter(), settings.Namespace(), os.Getenv("HELM_DRIVER"), debug)
client := action.NewPull()
client.Settings = settings
if chartVersion != "" {
client.Version = chartVersion
}
logger.Debugf("Pulling %s:%s...", chartName, chartVersion)
res, err := client.Run(chartName)
if err != nil {
return err
}
logger.Infof("Pulled %s:%s %s", chartName, chartVersion, res)
return nil
}
// PullChartUntarToDir pulls a helm chart, untar and output to a directory
func PullChartUntarToDir(chartName string, chartVersion string, dirName string) error {
logger.Debug("New pull client")
actionConfig := new(action.Configuration)
helmDriver := os.Getenv("HELM_DRIVER")
if err := actionConfig.Init(settings.RESTClientGetter(), settings.Namespace(), helmDriver, debug); err != nil {
logger.Fatal(err)
}
client := NewPull()
client.Settings = settings
client.UntarDir = dirName
client.Untar = true
if chartVersion != "" {
client.Version = chartVersion
}
logger.Debugf("Pulling %s...", chartName)
res, err := client.Run(chartName)
if err != nil {
return err
}
logger.Infof("Pulled %s %s", chartName, res)
return nil
}
// AddRepository adds a repository to helm
func AddRepository(repoName string, repoURL string) error {
logger.Debug("New repository client")
actionConfig := new(action.Configuration)
helmDriver := os.Getenv("HELM_DRIVER")
if err := actionConfig.Init(settings.RESTClientGetter(), settings.Namespace(), helmDriver, debug); err != nil {
logger.Fatal(err)
}
opts := &repoAddOptions{}
opts.name = repoName
opts.url = repoURL
opts.repoFile = settings.RepositoryConfig
opts.repoCache = settings.RepositoryCache
return opts.run()
}
func (opts *repoAddOptions) run() error {
//Ensure the file directory exists as it is required for file locking
err := os.MkdirAll(filepath.Dir(opts.repoFile), os.ModePerm)
if err != nil && !os.IsExist(err) {
return err
}
// Acquire a file lock for process synchronization
fileLock := flock.New(strings.Replace(opts.repoFile, filepath.Ext(opts.repoFile), ".lock", 1))
lockCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
locked, err := fileLock.TryLockContext(lockCtx, time.Second)
if err == nil && locked {
defer fileLock.Unlock()
}
if err != nil {
return err
}
b, err := ioutil.ReadFile(opts.repoFile)
if err != nil && !os.IsNotExist(err) {
return err
}
var f repo.File
if err := yaml.Unmarshal(b, &f); err != nil {
return err
}
if opts.noUpdate && f.Has(opts.name) {
return errors.Errorf("repository name (%s) already exists, please specify a different name", opts.name)
}
c := repo.Entry{
Name: opts.name,
URL: opts.url,
Username: opts.username,
Password: opts.password,
CertFile: opts.certFile,
KeyFile: opts.keyFile,
CAFile: opts.caFile,
}
r, err := repo.NewChartRepository(&c, getter.All(settings))
if err != nil {
return err
}
if opts.repoCache != "" {
r.CachePath = opts.repoCache
}
if _, err := r.DownloadIndexFile(); err != nil {
return errors.Wrapf(err, "looks like %q is not a valid chart repository or cannot be reached", opts.url)
}
f.Update(&c)
if err := f.WriteFile(opts.repoFile, 0644); err != nil {
return err
}
logger.Infof("%q has been added to your repositories\n", opts.name)
return nil
}
func envOr(name, def string) string {
if v, ok := os.LookupEnv(name); ok {
return v
}
return def
}
// UpgradeInstallChart upgrades a existing release or creates it
func UpgradeInstallChart(releaseName string, chartPath string, valueOpts *values.Options, opts *cmdutils.InstallOpts) error {
logger.Debug("New upgrade-install client")
actionConfig := new(action.Configuration)
namespace := opts.KubernetesOpts.Namespace
helmDriver := os.Getenv("HELM_DRIVER")
if err := actionConfig.Init(settings.RESTClientGetter(), namespace, helmDriver, debug); err != nil {
logger.Fatal(err)
}
client := action.NewUpgrade(actionConfig)
client.Namespace = namespace
p := getter.All(settings)
vals, err := valueOpts.MergeValues(p)
if err != nil {
return err
}
chartPath, err = client.ChartPathOptions.LocateChart(chartPath, settings)
if err != nil {
return err
}
// If a release does not exist, install it. If another error occurs during
// the check, ignore the error and continue with the upgrade.
histClient := action.NewHistory(actionConfig)
histClient.Max = 1
if _, err := histClient.Run(releaseName); err == driver.ErrReleaseNotFound {
logger.Infof("Release %q does not exist. Installing it now.\n", releaseName)
instClient := action.NewInstall(actionConfig)
instClient.ReleaseName = releaseName
instClient.ChartPathOptions = client.ChartPathOptions
instClient.DryRun = client.DryRun
instClient.DisableHooks = client.DisableHooks
instClient.Timeout = client.Timeout
instClient.Wait = client.Wait
instClient.Devel = client.Devel
instClient.Namespace = client.Namespace
instClient.Atomic = client.Atomic
err := runInstall(instClient, releaseName, chartPath, valueOpts)
if err != nil {
return err
}
return nil
}
// Check chart dependencies to make sure all are present in /charts
ch, err := loader.Load(chartPath)
if err != nil {
return err
}
if req := ch.Metadata.Dependencies; req != nil {
if err := action.CheckDependencies(ch, req); err != nil {
return err
}
}
if ch.Metadata.Deprecated {
logger.Warning("WARNING: This chart is deprecated")
}
logger.Infof("Upgrading %s in %s", releaseName, client.Namespace)
_, err = client.Run(releaseName, ch, vals)
if err != nil {
return errors.Wrap(err, "UPGRADE FAILED")
}
return nil
}
// runInstall installs a helm chart in current context
func runInstall(client *action.Install, releaseName string, chartPath string, valueOpts *values.Options) error {
logger.Debug("New install client")
cp, err := client.ChartPathOptions.LocateChart(chartPath, settings)
if err != nil {
return err
}
p := getter.All(settings)
vals, err := valueOpts.MergeValues(p)
if err != nil {
return err
}
// Check chart dependencies to make sure all are present in /charts
chartRequested, err := loader.Load(cp)
if err != nil {
return err
}
validInstallableChart, err := isChartInstallable(chartRequested)
if !validInstallableChart {
return err
}
if chartRequested.Metadata.Deprecated {
logger.Warning("This chart is deprecated")
}
_, err = client.Run(chartRequested, vals)
if err != nil {
return err
}
return nil
}
// isChartInstallable validates if a chart can be installed
//
// Application chart type is only installable
func isChartInstallable(ch *chart.Chart) (bool, error) {
switch ch.Metadata.Type {
case "", "application":
return true, nil
}
return false, errors.Errorf("%s charts are not installable", ch.Metadata.Type)
}