-
Notifications
You must be signed in to change notification settings - Fork 102
/
client.go
522 lines (431 loc) · 14 KB
/
client.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
package helmclient
import (
"bytes"
"encoding/json"
"fmt"
"log"
"os"
"github.com/spf13/pflag"
"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/downloader"
"helm.sh/helm/v3/pkg/getter"
"helm.sh/helm/v3/pkg/repo"
"helm.sh/helm/v3/pkg/storage/driver"
apiextensionsV1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
"k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/cli-runtime/pkg/genericclioptions"
)
var storage = repo.File{}
const (
defaultCachePath = "/tmp/.helmcache"
defaultRepositoryConfigPath = "/tmp/.helmrepo"
)
// New returns a new Helm client with the provided options
func New(options *Options) (*Client, error) {
settings := cli.New()
err := setEnvSettings(options, settings)
if err != nil {
return nil, err
}
return newClient(options, settings.RESTClientGetter(), settings)
}
// NewClientFromKubeConf returns a new Helm client constructed with the provided kubeconfig options
func NewClientFromKubeConf(options *KubeConfClientOptions) (*Client, error) {
settings := cli.New()
if options.KubeConfig == nil {
return nil, fmt.Errorf("kubeconfig missing")
}
clientGetter := NewRESTClientGetter(options.Namespace, options.KubeConfig, nil)
err := setEnvSettings(options.Options, settings)
if err != nil {
return nil, err
}
if options.KubeContext != "" {
settings.KubeContext = options.KubeContext
}
return newClient(options.Options, clientGetter, settings)
}
// NewClientFromRestConf returns a new Helm client constructed with the provided REST config options
func NewClientFromRestConf(options *RestConfClientOptions) (*Client, error) {
settings := cli.New()
clientGetter := NewRESTClientGetter(options.Namespace, nil, options.RestConfig)
err := setEnvSettings(options.Options, settings)
if err != nil {
return nil, err
}
return newClient(options.Options, clientGetter, settings)
}
// newClient returns a new Helm client via the provided options and REST config
func newClient(options *Options, clientGetter genericclioptions.RESTClientGetter, settings *cli.EnvSettings) (*Client, error) {
err := setEnvSettings(options, settings)
if err != nil {
return nil, err
}
actionConfig := new(action.Configuration)
err = actionConfig.Init(
clientGetter,
settings.Namespace(),
os.Getenv("HELM_DRIVER"),
func(format string, v ...interface{}) {
log.Printf(format, v)
},
)
if err != nil {
return nil, err
}
return &Client{
Settings: settings,
Providers: getter.All(settings),
storage: &storage,
ActionConfig: actionConfig,
linting: options.Linting,
}, nil
}
// setEnvSettings sets the client's environment settings based on the provided client configuration
func setEnvSettings(options *Options, settings *cli.EnvSettings) error {
if options == nil {
options = &Options{
RepositoryConfig: defaultRepositoryConfigPath,
RepositoryCache: defaultCachePath,
Linting: true,
}
}
// set the namespace with this ugly workaround because cli.EnvSettings.namespace is private
// thank you helm!
if options.Namespace != "" {
pflags := pflag.NewFlagSet("", pflag.ContinueOnError)
settings.AddFlags(pflags)
err := pflags.Parse([]string{"-n", options.Namespace})
if err != nil {
return err
}
}
if options.RepositoryConfig == "" {
options.RepositoryConfig = defaultRepositoryConfigPath
}
if options.RepositoryCache == "" {
options.RepositoryCache = defaultCachePath
}
settings.RepositoryCache = options.RepositoryCache
settings.RepositoryConfig = defaultRepositoryConfigPath
settings.Debug = options.Debug
return nil
}
// AddOrUpdateChartRepo adds or updates the provided helm chart repository
func (c *Client) AddOrUpdateChartRepo(entry repo.Entry) error {
chartRepo, err := repo.NewChartRepository(&entry, c.Providers)
if err != nil {
return err
}
chartRepo.CachePath = c.Settings.RepositoryCache
_, err = chartRepo.DownloadIndexFile()
if err != nil {
return err
}
if c.storage.Has(entry.Name) {
log.Printf("WARNING: repository name %q already exists", entry.Name)
return nil
}
c.storage.Update(&entry)
err = c.storage.WriteFile(c.Settings.RepositoryConfig, 0644)
if err != nil {
return err
}
return nil
}
// UpdateChartRepos updates the list of chart repositories stored in the client's cache
func (c *Client) UpdateChartRepos() error {
for _, entry := range c.storage.Repositories {
chartRepo, err := repo.NewChartRepository(entry, c.Providers)
if err != nil {
return err
}
chartRepo.CachePath = c.Settings.RepositoryCache
_, err = chartRepo.DownloadIndexFile()
if err != nil {
return err
}
c.storage.Update(entry)
}
return c.storage.WriteFile(c.Settings.RepositoryConfig, 0644)
}
// InstallOrUpgradeChart triggers the installation of the provided chart.
// If the chart is already installed, trigger an upgrade instead
func (c *Client) InstallOrUpgradeChart(spec *ChartSpec) error {
installed, err := c.chartIsInstalled(spec.ReleaseName)
if err != nil {
return err
}
if installed {
return c.upgrade(spec)
}
return c.install(spec)
}
// DeleteChartFromCache deletes the provided chart from the client's cache
func (c *Client) DeleteChartFromCache(spec *ChartSpec) error {
return c.deleteChartFromCache(spec)
}
// UninstallRelease uninstalls the provided release
func (c *Client) UninstallRelease(spec *ChartSpec) error {
return c.uninstallRelease(spec)
}
// install lints and installs the provided chart
func (c *Client) install(spec *ChartSpec) error {
client := action.NewInstall(c.ActionConfig)
c.mergeInstallOptions(spec, client)
if client.Version == "" {
client.Version = ">0.0.0-0"
}
helmChart, chartPath, err := c.getChart(spec.ChartName, &client.ChartPathOptions)
if err != nil {
return err
}
if helmChart.Metadata.Type != "" && helmChart.Metadata.Type != "application" {
return fmt.Errorf(
"chart %q has an unsupported type and is not installable: %q",
helmChart.Metadata.Name,
helmChart.Metadata.Type,
)
}
if req := helmChart.Metadata.Dependencies; req != nil {
if err := action.CheckDependencies(helmChart, req); err != nil {
if client.DependencyUpdate {
man := &downloader.Manager{
ChartPath: chartPath,
Keyring: client.ChartPathOptions.Keyring,
SkipUpdate: false,
Getters: c.Providers,
RepositoryConfig: c.Settings.RepositoryConfig,
RepositoryCache: c.Settings.RepositoryCache,
}
if err := man.Update(); err != nil {
return err
}
} else {
return err
}
}
}
values, err := spec.GetValuesMap()
if err != nil {
return err
}
if c.linting {
err = c.lint(chartPath, values)
if err != nil {
return err
}
}
rel, err := client.Run(helmChart, values)
if err != nil {
return err
}
log.Printf("release installed successfully: %s/%s-%s", rel.Name, rel.Name, rel.Chart.Metadata.Version)
return nil
}
// upgrade upgrades a chart and CRDs
func (c *Client) upgrade(spec *ChartSpec) error {
client := action.NewUpgrade(c.ActionConfig)
c.mergeUpgradeOptions(spec, client)
if client.Version == "" {
client.Version = ">0.0.0-0"
}
helmChart, chartPath, err := c.getChart(spec.ChartName, &client.ChartPathOptions)
if err != nil {
return err
}
if req := helmChart.Metadata.Dependencies; req != nil {
if err := action.CheckDependencies(helmChart, req); err != nil {
return err
}
}
values, err := spec.GetValuesMap()
if err != nil {
return err
}
if c.linting {
err = c.lint(chartPath, values)
if err != nil {
return err
}
}
if !spec.SkipCRDs && spec.UpgradeCRDs {
log.Printf("updating crds")
err = c.upgradeCRDs(helmChart)
if err != nil {
return err
}
}
rel, err := client.Run(spec.ReleaseName, helmChart, values)
if err != nil {
return err
}
log.Printf("release upgrade successfully: %s/%s-%s", rel.Name, rel.Name, rel.Chart.Metadata.Version)
return nil
}
// deleteChartFromCache deletes the provided chart from the client's cache
func (c *Client) deleteChartFromCache(spec *ChartSpec) error {
client := action.NewChartRemove(c.ActionConfig)
helmChart, _, err := c.getChart(spec.ChartName, &action.ChartPathOptions{})
if err != nil {
return err
}
var deleteOutputBuffer bytes.Buffer
err = client.Run(&deleteOutputBuffer, helmChart.Name())
if err != nil {
return err
}
log.Printf("chart removed successfully: %s/%s-%s", helmChart.Name(), spec.ReleaseName, helmChart.AppVersion())
return nil
}
// uninstallRelease uninstalls the provided release
func (c *Client) uninstallRelease(spec *ChartSpec) error {
client := action.NewUninstall(c.ActionConfig)
c.mergeUninstallReleaseOptions(spec, client)
resp, err := client.Run(spec.ReleaseName)
if err != nil {
return err
}
log.Printf("release removed, response: %v", resp)
return nil
}
// lint lints a chart's values
func (c *Client) lint(chartPath string, values map[string]interface{}) error {
client := action.NewLint()
result := client.Run([]string{chartPath}, values)
for _, err := range result.Errors {
log.Printf("Error %s", err)
}
if len(result.Errors) > 0 {
return fmt.Errorf("linting for chartpath %q failed", chartPath)
}
return nil
}
// upgradeCRDs upgrades the CRDs of the provided chart
func (c *Client) upgradeCRDs(chartInstance *chart.Chart) error {
cfg, err := c.Settings.RESTClientGetter().ToRESTConfig()
if err != nil {
return err
}
k8sClient, err := clientset.NewForConfig(cfg)
if err != nil {
return err
}
for _, crd := range chartInstance.CRDObjects() {
// use this ugly detour to parse the crdYaml to a CustomResourceDefinitions-Object because direct
// yaml-unmarshalling does not find the correct keys
jsonCRD, err := yaml.ToJSON(crd.File.Data)
if err != nil {
return err
}
var meta metaV1.TypeMeta
err = json.Unmarshal(jsonCRD, &meta)
if err != nil {
return err
}
switch meta.APIVersion {
case "apiextensions.k8s.io/apiextensionsV1":
var crdObj apiextensionsV1.CustomResourceDefinition
err = json.Unmarshal(jsonCRD, &crdObj)
if err != nil {
return err
}
existingCRDObj, err := k8sClient.ApiextensionsV1().CustomResourceDefinitions().Get(crdObj.Name, metaV1.GetOptions{})
if err != nil {
return err
}
crdObj.ResourceVersion = existingCRDObj.ResourceVersion
_, err = k8sClient.ApiextensionsV1().CustomResourceDefinitions().Update(&crdObj)
if err != nil {
return err
}
case "apiextensions.k8s.io/v1beta1":
var crdObj v1beta1.CustomResourceDefinition
err = json.Unmarshal(jsonCRD, &crdObj)
if err != nil {
return err
}
existingCRDObj, err := k8sClient.ApiextensionsV1beta1().CustomResourceDefinitions().Get(crdObj.Name, metaV1.GetOptions{})
if err != nil {
return err
}
crdObj.ResourceVersion = existingCRDObj.ResourceVersion
_, err = k8sClient.ApiextensionsV1beta1().CustomResourceDefinitions().Update(&crdObj)
if err != nil {
return err
}
default:
return fmt.Errorf("failed to update crd %q: unsupported api-version %q", crd.Name, meta.APIVersion)
}
}
return nil
}
// getChart returns a chart matching the provided chart name and options
func (c *Client) getChart(chartName string, chartPathOptions *action.ChartPathOptions) (*chart.Chart, string, error) {
chartPath, err := chartPathOptions.LocateChart(chartName, c.Settings)
if err != nil {
return nil, "", err
}
helmChart, err := loader.Load(chartPath)
if err != nil {
return nil, "", err
}
if helmChart.Metadata.Deprecated {
log.Printf("WARNING: This chart (%q) is deprecated", helmChart.Metadata.Name)
}
return helmChart, chartPath, err
}
// chartIsInstalled checks whether a chart is already installed or not by the provided release name
func (c *Client) chartIsInstalled(release string) (bool, error) {
histClient := action.NewHistory(c.ActionConfig)
histClient.Max = 1
if _, err := histClient.Run(release); err == driver.ErrReleaseNotFound {
return false, nil
} else if err != nil {
return false, err
}
return true, nil
}
// mergeInstallOptions merges values of the provided chart to helm install options used by the client
func (c *Client) mergeInstallOptions(chartSpec *ChartSpec, installOptions *action.Install) {
installOptions.DisableHooks = chartSpec.DisableHooks
installOptions.Replace = chartSpec.Replace
installOptions.Wait = chartSpec.Wait
installOptions.DependencyUpdate = chartSpec.DependencyUpdate
installOptions.Timeout = chartSpec.Timeout
installOptions.Namespace = chartSpec.Namespace
installOptions.ReleaseName = chartSpec.ReleaseName
installOptions.Version = chartSpec.Version
installOptions.GenerateName = chartSpec.GenerateName
installOptions.NameTemplate = chartSpec.NameTemplate
installOptions.Atomic = chartSpec.Atomic
installOptions.SkipCRDs = chartSpec.SkipCRDs
installOptions.SubNotes = chartSpec.SubNotes
}
// mergeUpgradeOptions merges values of the provided chart to helm upgrade options used by the client
func (c *Client) mergeUpgradeOptions(chartSpec *ChartSpec, upgradeOptions *action.Upgrade) {
upgradeOptions.Version = chartSpec.Version
upgradeOptions.Namespace = chartSpec.Namespace
upgradeOptions.Timeout = chartSpec.Timeout
upgradeOptions.Wait = chartSpec.Wait
upgradeOptions.DisableHooks = chartSpec.DisableHooks
upgradeOptions.Force = chartSpec.Force
upgradeOptions.ResetValues = chartSpec.ResetValues
upgradeOptions.ReuseValues = chartSpec.ReuseValues
upgradeOptions.Recreate = chartSpec.Recreate
upgradeOptions.MaxHistory = chartSpec.MaxHistory
upgradeOptions.Atomic = chartSpec.Atomic
upgradeOptions.CleanupOnFail = chartSpec.CleanupOnFail
upgradeOptions.SubNotes = chartSpec.SubNotes
}
// mergeUninstallReleaseOptions merges values of the provided chart to helm uninstall options used by the client
func (c *Client) mergeUninstallReleaseOptions(chartSpec *ChartSpec, uninstallReleaseOptions *action.Uninstall) {
uninstallReleaseOptions.DisableHooks = chartSpec.DisableHooks
uninstallReleaseOptions.Timeout = chartSpec.Timeout
}