-
Notifications
You must be signed in to change notification settings - Fork 0
/
helm.go
339 lines (296 loc) · 9.92 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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*
Copyright 2020 Testutil 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 provides utility to leverage helm in tests without requiring
// the CLI.
package helm
import (
"net/url"
"os"
"path/filepath"
"github.com/kubism/testutil/pkg/fs"
"github.com/kubism/testutil/pkg/rand"
"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/cli"
"helm.sh/helm/v3/pkg/cli/values"
"helm.sh/helm/v3/pkg/getter"
"helm.sh/helm/v3/pkg/release"
"helm.sh/helm/v3/pkg/repo"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/client-go/discovery"
"k8s.io/client-go/discovery/cached/memory"
"k8s.io/client-go/rest"
"k8s.io/client-go/restmapper"
"k8s.io/client-go/tools/clientcmd"
)
// TODO: Currently the implementation lacks a lot of helm functionality.
// One interesting one would be: support for plugins
// We are not using the CLI environment, so we make the relevant providers
// available here.
var getters = getter.Providers{
getter.Provider{
Schemes: []string{"http", "https"},
New: getter.NewHTTPGetter,
},
}
// DebugLog is the function declaration required to capture log output from
// the Client.
type DebugLog = action.DebugLog
// RepositoryEntry represents the collection of parameters to define a new
// entry of a helm repository.
type RepositoryEntry = repo.Entry
// Chart is a helm package that contains metadata, a default config, zero or
// more optionally parameterizable templates, and zero or more charts (dependencies).
type Chart = chart.Chart
// ValuesOptions provides several options to provide values configuration for
// helm. All contained values can then be conveniently merged.
type ValuesOptions = values.Options
// Release describes a deployment of a chart, together with the chart and
// the variables used to deploy that chart.
type Release = release.Release
// restClientGetter a simple wrapper providing the RESTClientGetter-interface
// using only the raw kubeconfig.
type restClientGetter struct {
Namespace string
KubeConfig string
}
func (c *restClientGetter) ToRESTConfig() (*rest.Config, error) {
return clientcmd.RESTConfigFromKubeConfig([]byte(c.KubeConfig))
}
func (c *restClientGetter) ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error) {
config, err := c.ToRESTConfig()
if err != nil {
return nil, err
}
discoveryClient, _ := discovery.NewDiscoveryClientForConfig(config)
return memory.NewMemCacheClient(discoveryClient), nil
}
func (c *restClientGetter) ToRESTMapper() (meta.RESTMapper, error) {
discoveryClient, err := c.ToDiscoveryClient()
if err != nil {
return nil, err
}
mapper := restmapper.NewDeferredDiscoveryRESTMapper(discoveryClient)
expander := restmapper.NewShortcutExpander(mapper, discoveryClient)
return expander, nil
}
func (c *restClientGetter) ToRawKubeConfigLoader() clientcmd.ClientConfig {
clientConfig, err := clientcmd.NewClientConfigFromBytes([]byte(c.KubeConfig))
if err != nil {
panic(err) // TODO: is there a way to avoid this panic?
}
return clientConfig
}
// clientOptions represents the internal configuration state.
type clientOptions struct {
Namespace string
Driver string
DebugLog DebugLog
}
// ClientOption interface is implemented by all possible options to instantiate
// a new helm client.
type ClientOption interface {
apply(*clientOptions)
}
type clientOptionAdapter func(*clientOptions)
func (c clientOptionAdapter) apply(o *clientOptions) {
c(o)
}
// ClientWithNamespace will adapt the default namespace used as a fallback
// by the helm client.
func ClientWithNamespace(namespace string) ClientOption {
return clientOptionAdapter(func(o *clientOptions) {
o.Namespace = namespace
})
}
// ClientWithDriver will change the helm storage driver. By default it will
// be 'secret', but 'configmap' and 'memory' are other sensible values.
func ClientWithDriver(driver string) ClientOption {
return clientOptionAdapter(func(o *clientOptions) {
o.Driver = driver
})
}
// ClientWithDebugLog will use the provided function to output debug logs of helm.
func ClientWithDebugLog(debugLog DebugLog) ClientOption {
return clientOptionAdapter(func(o *clientOptions) {
o.DebugLog = debugLog
})
}
// Client represents the temporary helm environment.
type Client struct {
kubeConfig string
options clientOptions
actionConfig *action.Configuration
tempDir *fs.TempDir
repoFile *repo.File
}
// NewClient will create a new helm client providing an isolated helm environment.
// Only a valid kubeconfig is required. Make sure to properly clean up temporary
// files by calling Close once finished.
func NewClient(kubeConfig string, opts ...ClientOption) (*Client, error) {
options := clientOptions{ // Default options
Namespace: "default",
Driver: "secrets",
DebugLog: func(format string, v ...interface{}) {},
}
for _, opt := range opts {
opt.apply(&options)
}
// Create actionConfig, which will be used for all actions of this helm client.
actionConfig := new(action.Configuration)
clientGetter := &restClientGetter{
Namespace: options.Namespace,
KubeConfig: kubeConfig,
}
if err := actionConfig.Init(clientGetter, options.Namespace, options.Driver, options.DebugLog); err != nil {
return nil, err
}
c := &Client{
kubeConfig: kubeConfig,
options: options,
actionConfig: actionConfig,
repoFile: repo.NewFile(),
}
if err := c.setupDirs(); err != nil {
c.Close()
return nil, err
}
return c, nil
}
// setupDirs is a small helper, which will setup all directories and files used
// by this instance. Should only be called once by NewClient!
func (c *Client) setupDirs() error {
var err error
c.tempDir, err = fs.NewTempDir()
if err != nil {
return err
}
if err := os.Mkdir(c.getCacheDir(), 0755); err != nil {
return err
}
if err := c.writeRepoFile(); err != nil {
return err
}
return nil
}
func (c *Client) getCacheDir() string {
return filepath.Join(c.tempDir.Path, "cache")
}
func (c *Client) getRepoFilePath() string {
return filepath.Join(c.tempDir.Path, "repositories.yaml")
}
func (c *Client) writeRepoFile() error {
return c.repoFile.WriteFile(c.getRepoFilePath(), 0755)
}
// List will retrieve all installed releases from the cluster.
func (c *Client) List() ([]*release.Release, error) {
list := action.NewList(c.actionConfig)
return list.Run()
}
// AddRepository will append the RepositoryEntry to the temporary
// repositories-file. It will also block until the index-file was downloaded.
func (c *Client) AddRepository(cfg *RepositoryEntry) error {
u, err := url.Parse(cfg.URL)
if err != nil {
return errors.Errorf("invalid chart URL format: %s", cfg.URL)
}
client, err := getters.ByScheme(u.Scheme)
if err != nil {
return errors.Errorf("could not find protocol handler for: %s", u.Scheme)
}
r := &repo.ChartRepository{
Config: cfg,
IndexFile: repo.NewIndexFile(),
Client: client,
CachePath: c.getCacheDir(),
}
_, err = r.DownloadIndexFile()
if err != nil {
return err
}
c.repoFile.Add(cfg)
return c.writeRepoFile()
}
// There is currently some helm functionality, where the environment variables
// can not be avoided. This function sets the necessary env-variables to get a
// valid cli.EnvSettings.
func (c *Client) createEnvSettings(namespace string) *cli.EnvSettings {
os.Setenv("HELM_NAMESPACE", namespace)
os.Setenv("HELM_PLUGINS", filepath.Join(c.tempDir.Path, "plugins"))
os.Setenv("HELM_REGISTRY_CONFIG", filepath.Join(c.tempDir.Path, "registry.json"))
os.Setenv("HELM_REPOSITORY_CONFIG", c.getRepoFilePath())
os.Setenv("HELM_REPOSITORY_CACHE", c.getCacheDir())
return cli.New()
}
type installOptions struct {
*action.Install
}
// ClientOption interface is implemented by all possible options to install charts.
type InstallOption interface {
apply(*installOptions)
}
type installOptionAdapter func(*installOptions)
func (c installOptionAdapter) apply(o *installOptions) {
c(o)
}
// InstallWithReleaseName will override the release name, which will be a
// random string by default.
func InstallWithReleaseName(name string) InstallOption {
return installOptionAdapter(func(o *installOptions) {
o.ReleaseName = name
})
}
// Install will try to locate the chart and download the specified version.
// If the chartName is a local path, it will try to load the local chart instead.
// With the chart locally available it will install it using the provided
// values and options.
func (c *Client) Install(chartName, version string, valuesOptions ValuesOptions, opts ...InstallOption) (*Release, error) {
options := installOptions{action.NewInstall(c.actionConfig)}
options.ReleaseName = rand.String(5)
options.Namespace = "default"
options.Version = version
for _, opt := range opts {
opt.apply(&options)
}
settings := c.createEnvSettings(options.Namespace)
fname, err := options.LocateChart(chartName, settings)
if err != nil {
return nil, err
}
chart, err := loader.Load(fname)
if err != nil {
return nil, err
}
values, err := valuesOptions.MergeValues(getters)
if err != nil {
return nil, err
}
return options.Run(chart, values)
}
// Uninstall will remove the release from the cluster.
func (c *Client) Uninstall(releaseName string) error {
uninstall := action.NewUninstall(c.actionConfig)
_, err := uninstall.Run(releaseName)
return err
}
// Close will release all filesystem resources of the helm client instance.
// Make sure to always call this function if the helm client is not required
// anymore.
func (c *Client) Close() error {
if c.tempDir != nil {
return c.tempDir.Close()
}
return nil
}