-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathinstall.go
More file actions
328 lines (311 loc) · 10 KB
/
install.go
File metadata and controls
328 lines (311 loc) · 10 KB
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
/*
* Copyright 2024 Marc Nuri
*
* 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"
"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/cli"
"helm.sh/helm/v3/pkg/cli/values"
"helm.sh/helm/v3/pkg/getter"
"helm.sh/helm/v3/pkg/release"
"net/url"
"os"
"os/signal"
"slices"
"strings"
"syscall"
"time"
)
type InstallOptions struct {
CertOptions
Name string
GenerateName bool
NameTemplate string
Version string
Chart string
Namespace string
KubeVersion string
Atomic bool
CreateNamespace bool
Description string
Devel bool
DependencyUpdate bool
DisableOpenApiValidation bool
DryRun bool
DryRunOption string
SkipCRDs bool
Wait bool
Timeout time.Duration
Values string
SetFiles string
ValuesFiles string
KubeConfig string
KubeConfigContents string
Debug bool
// For testing purposes only, prevents connecting to Kubernetes (happens even with DryRun=true and DryRunOption=client)
ClientOnly bool
RepositoryConfig string
}
type installOutputs struct {
updateOutput string
getRegistryClientOut func() *bytes.Buffer
kubeOut *bytes.Buffer
}
func Install(options *InstallOptions) (string, error) {
rel, outputs, err := install(options)
// Generate report
out := StatusReport(rel, false, options.Debug)
return appendToOutOrErr(concat(cStr(outputs.updateOutput), cBuf(outputs.getRegistryClientOut()), cBuf(outputs.kubeOut)), out, err)
}
func install(options *InstallOptions) (*release.Release, *installOutputs, error) {
outputs := &installOutputs{
kubeOut: bytes.NewBuffer(make([]byte, 0)),
}
if options.Version == "" && options.Devel {
options.Version = ">0.0.0-0"
}
registryClient, getRegistryClientOut, err := newRegistryClient(
options.CertFile,
options.KeyFile,
options.CaFile,
options.InsecureSkipTLSverify,
options.PlainHttp,
options.Debug,
)
outputs.getRegistryClientOut = getRegistryClientOut
if err != nil {
return nil, outputs, err
}
cfgOptions := &CfgOptions{
RegistryClient: registryClient,
KubeConfig: options.KubeConfig,
KubeConfigContents: options.KubeConfigContents,
Namespace: options.Namespace,
}
if options.Debug {
cfgOptions.KubeOut = outputs.kubeOut
}
cfg, err := NewCfg(cfgOptions)
if err != nil {
return nil, outputs, err
}
client := action.NewInstall(cfg)
client.GenerateName = options.GenerateName
client.NameTemplate = options.NameTemplate
client.Version = options.Version
var name, chartReference string
if options.GenerateName {
// Generate name if applicable
name, chartReference, _ = client.NameAndChart([]string{options.Chart})
} else {
name = options.Name
chartReference = options.Chart
}
client.ReleaseName = name
client.Namespace = options.Namespace
if options.KubeVersion != "" {
client.KubeVersion, err = chartutil.ParseKubeVersion(options.KubeVersion)
if err != nil {
return nil, outputs, err
}
}
client.Atomic = options.Atomic
client.CreateNamespace = options.CreateNamespace
client.Description = options.Description
client.Devel = options.Devel
client.DryRun = options.DryRun
client.DryRunOption = dryRunOption(options.DryRunOption)
client.SkipCRDs = options.SkipCRDs
client.Wait = options.Wait
client.Timeout = options.Timeout
client.ClientOnly = options.ClientOnly
client.CertFile = options.CertFile
client.KeyFile = options.KeyFile
client.CaFile = options.CaFile
client.DisableOpenAPIValidation = options.DisableOpenApiValidation
client.InsecureSkipTLSverify = options.InsecureSkipTLSverify
client.PlainHTTP = options.PlainHttp
chartRequested, chartPath, err := loadChart(client.ChartPathOptions, options.RepositoryConfig, chartReference)
if err != nil {
return nil, outputs, err
}
if notInstallable := checkIfInstallable(chartRequested); notInstallable != nil {
return nil, outputs, notInstallable
}
// Dependency management
chartRequested, updateOutput, err := updateDependencies(&updateDependenciesOptions{
DependencyUpdate: options.DependencyUpdate,
Keyring: options.Keyring,
Debug: options.Debug,
}, chartRequested, chartPath)
if err != nil {
return nil, outputs, err
}
outputs.updateOutput = updateOutput
// Dry Run options
if invalidDryRun := validateDryRunOptionFlag(client.DryRunOption); invalidDryRun != nil {
return nil, outputs, invalidDryRun
}
// Values
vals, err := mergeValues(options.Values, options.SetFiles, options.ValuesFiles)
if err != nil {
return nil, outputs, err
}
// Create context that handles SIGINT, SIGTERM
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
// Set up channel on which to send signal notifications.
// We must use a buffered channel or risk missing the signal
// if we're not ready to receive when the signal is sent.
cSignal := make(chan os.Signal, 4)
signal.Notify(cSignal, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL, syscall.SIGQUIT)
go func() {
<-cSignal
cancel()
}()
// Run
rel, err := client.RunWithContext(ctx, chartRequested, vals)
return rel, outputs, err
}
// https://github.com/helm/helm/blob/ef02cafdd0a0be75b1f83f1b2c9ca4d1ac3edda5/cmd/helm/install.go#L309-L318
// checkIfInstallable validates if a chart can be installed
//
// Application chart type is only installable
func checkIfInstallable(ch *chart.Chart) error {
switch ch.Metadata.Type {
case "", "application":
return nil
}
return errors.Errorf("%s charts are not installable", ch.Metadata.Type)
}
// https://github.com/helm/helm/blob/ef02cafdd0a0be75b1f83f1b2c9ca4d1ac3edda5/cmd/helm/install.go#L332-L346
func validateDryRunOptionFlag(dryRunOptionFlagValue string) error {
// Validate dry-run flag value with a set of allowed value
allowedDryRunValues := []string{"false", "true", "none", "client", "server"}
isAllowed := false
for _, v := range allowedDryRunValues {
if dryRunOptionFlagValue == v {
isAllowed = true
break
}
}
if !isAllowed {
return errors.New("Invalid dry-run flag. Flag must one of the following: false, true, none, client, server")
}
return nil
}
type updateDependenciesOptions struct {
DependencyUpdate bool
Keyring string
Debug bool
}
func loadChart(chartPathOptions action.ChartPathOptions, repositoryConfig string, chartReference string) (*chart.Chart, string, error) {
settings := cli.New()
if repositoryConfig != "" {
settings.RepositoryConfig = repositoryConfig
}
chartPath, err := chartPathOptions.LocateChart(chartReference, settings)
if err != nil {
return nil, "", err
}
chartRequested, err := loader.Load(chartPath)
return chartRequested, chartPath, err
}
func updateDependencies(options *updateDependenciesOptions, chart *chart.Chart, chartPath string) (*chart.Chart, string, error) {
dependencies := chart.Metadata.Dependencies
if dependencies == nil {
return chart, "", nil
}
invalidDependencies := action.CheckDependencies(chart, dependencies)
if invalidDependencies == nil {
return chart, "", nil
}
// Dependencies are invalid, try to update them
invalidDependencies = errors.Wrap(invalidDependencies, "An error occurred while checking for chart dependencies. You may need to run `helm dependency build` to fetch missing dependencies")
if options.DependencyUpdate {
updateOutput, updateError := DependencyUpdate(&DependencyOptions{
Path: chartPath,
Keyring: options.Keyring,
SkipRefresh: false,
Debug: options.Debug,
})
if updateError != nil {
return nil, updateOutput, errors.Wrap(updateError, "An error occurred while updating chart dependencies")
}
reloadedChart, reloadError := loader.Load(chartPath)
if reloadError != nil {
return nil, updateOutput, errors.Wrap(reloadError, "An error occurred while reloading chart dependencies")
}
return reloadedChart, updateOutput, nil
}
return chart, "", invalidDependencies
}
func dryRunOption(dryRunOption string) string {
if dryRunOption == "" {
return "none"
} else {
return dryRunOption
}
}
var escapedChars = []rune("\"'\\={[,.]}")
func parseValuesSet(values string) ([]string, error) {
result := make([]string, 0)
if values != "" {
params, err := url.ParseQuery(values)
if err != nil {
return nil, err
}
for key, value := range params {
escapedValue := bytes.NewBuffer(make([]byte, 0))
for _, char := range value[0] {
if slices.Contains(escapedChars, char) {
escapedValue.WriteString("\\")
}
escapedValue.WriteRune(char)
}
result = append(result, fmt.Sprintf("%s=%s", key, escapedValue))
}
}
return result, nil
}
// mergeValues returns a map[string]interface{} with the provided processed values
func mergeValues(encodedValuesMap, encodedSetFiles, encodedValuesFiles string) (map[string]interface{}, error) {
valuesSet, err := parseValuesSet(encodedValuesMap)
if err != nil {
return nil, err
}
setFiles, err := parseValuesSet(encodedSetFiles)
if err != nil {
return nil, err
}
valueFiles := make([]string, 0)
if encodedValuesFiles != "" {
for _, valuesFile := range strings.Split(encodedValuesFiles, ",") {
valueFiles = append(valueFiles, valuesFile)
}
}
return (&values.Options{
Values: valuesSet,
FileValues: setFiles,
ValueFiles: valueFiles,
}).MergeValues(make(getter.Providers, 0))
}