-
Notifications
You must be signed in to change notification settings - Fork 9
/
helm.go
432 lines (371 loc) · 10.3 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
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
package scaffold
import (
"bytes"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
ttpl "text/template"
"gopkg.in/yaml.v2"
"github.com/pluralsh/plural-cli/pkg/api"
"github.com/pluralsh/plural-cli/pkg/config"
"github.com/pluralsh/plural-cli/pkg/manifest"
"github.com/pluralsh/plural-cli/pkg/provider"
scftmpl "github.com/pluralsh/plural-cli/pkg/scaffold/template"
"github.com/pluralsh/plural-cli/pkg/template"
"github.com/pluralsh/plural-cli/pkg/utils"
"github.com/pluralsh/plural-cli/pkg/utils/errors"
"github.com/pluralsh/plural-cli/pkg/utils/git"
"github.com/pluralsh/plural-cli/pkg/utils/pathing"
"github.com/pluralsh/plural-cli/pkg/wkspace"
)
type dependency struct {
Name string
Version string
Repository string
Condition string
}
type chart struct {
ApiVersion string `yaml:"apiVersion"`
Name string
Description string
Version string
AppVersion string `yaml:"appVersion"`
Dependencies []dependency
}
func (s *Scaffold) handleHelm(wk *wkspace.Workspace) error {
if err := s.createChart(wk); err != nil {
return err
}
if err := s.buildChartValues(wk); err != nil {
return err
}
return nil
}
func (s *Scaffold) chartDependencies(w *wkspace.Workspace) []dependency {
dependencies := make([]dependency, len(w.Charts))
repo := w.Installation.Repository
for i, chartInstallation := range w.Charts {
dependencies[i] = dependency{
chartInstallation.Chart.Name,
chartInstallation.Version.Version,
repoUrl(w, repo.Name, chartInstallation.Chart.Name),
fmt.Sprintf("%s.enabled", chartInstallation.Chart.Name),
}
}
sort.SliceStable(dependencies, func(i, j int) bool {
return dependencies[i].Name < dependencies[j].Name
})
return dependencies
}
func Notes(installation *api.Installation) error {
repoRoot, err := git.Root()
if err != nil {
return err
}
if installation.Repository != nil && installation.Repository.Notes == "" {
return nil
}
context, err := manifest.ReadContext(manifest.ContextPath())
if err != nil {
return err
}
prov, err := provider.GetProvider()
if err != nil {
return err
}
repo := installation.Repository.Name
ctx, _ := context.Repo(installation.Repository.Name)
vals := map[string]interface{}{
"Values": ctx,
"Configuration": context.Configuration,
"License": installation.LicenseKey,
"OIDC": installation.OIDCProvider,
"Region": prov.Region(),
"Project": prov.Project(),
"Cluster": prov.Cluster(),
"Config": config.Read(),
"Provider": prov.Name(),
"Context": prov.Context(),
"Applications": BuildApplications(repoRoot),
}
if context.Globals != nil {
vals["Globals"] = context.Globals
}
if context.SMTP != nil {
vals["SMTP"] = context.SMTP.Configuration()
}
if installation.AcmeKeyId != "" {
vals["Acme"] = map[string]string{
"KeyId": installation.AcmeKeyId,
"Secret": installation.AcmeSecret,
}
}
apps := &Applications{Root: repoRoot}
values, err := apps.HelmValues(repo)
if err != nil {
return err
}
for k, v := range values {
vals[k] = v
}
tmpl, err := template.MakeTemplate(installation.Repository.Notes)
if err != nil {
return err
}
var buf bytes.Buffer
buf.Grow(5 * 1024)
if err := tmpl.Execute(&buf, vals); err != nil {
return err
}
fmt.Println(buf.String())
return nil
}
func (s *Scaffold) buildChartValues(w *wkspace.Workspace) error {
ctx, _ := w.Context.Repo(w.Installation.Repository.Name)
valuesFile := pathing.SanitizeFilepath(filepath.Join(s.Root, "values.yaml"))
defaultValuesFile := pathing.SanitizeFilepath(filepath.Join(s.Root, "default-values.yaml"))
defaultPrevVals, _ := prevValues(defaultValuesFile)
prevVals, _ := prevValues(valuesFile)
if !utils.Exists(valuesFile) {
if err := os.WriteFile(valuesFile, []byte("{}\n"), 0644); err != nil {
return err
}
}
conf := config.Read()
apps, err := NewApplications()
if err != nil {
return err
}
proj, err := manifest.FetchProject()
if err != nil {
return err
}
vals := map[string]interface{}{
"Values": ctx,
"Configuration": w.Context.Configuration,
"License": w.Installation.LicenseKey,
"OIDC": w.Installation.OIDCProvider,
"Region": w.Provider.Region(),
"Project": w.Provider.Project(),
"Cluster": w.Provider.Cluster(),
"Config": conf,
"Provider": w.Provider.Name(),
"Context": w.Provider.Context(),
"ClusterAPI": proj.ClusterAPI,
"Network": proj.Network,
"Applications": apps,
}
if proj.AvailabilityZones != nil {
vals["AvailabilityZones"] = proj.AvailabilityZones
}
if w.Context.SMTP != nil {
vals["SMTP"] = w.Context.SMTP.Configuration()
}
if w.Context.Globals != nil {
vals["Globals"] = w.Context.Globals
}
if w.Installation.AcmeKeyId != "" {
vals["Acme"] = map[string]string{
"KeyId": w.Installation.AcmeKeyId,
"Secret": w.Installation.AcmeSecret,
}
}
// get previous values from default-values.yaml if exists otherwise from values.yaml
if utils.Exists(defaultValuesFile) {
for k, v := range defaultPrevVals {
vals[k] = v
}
} else {
for k, v := range prevVals {
vals[k] = v
}
}
defaultValues, err := scftmpl.BuildValuesFromTemplate(vals, w)
if err != nil {
return err
}
io, err := yaml.Marshal(defaultValues)
if err != nil {
return err
}
// TODO: Remove this after testing. It is deprecated as values.yaml migration should not longer be required.
// mapValues, err := getValues(valuesFile)
// if err != nil {
// return err
// }
// patchValues, err := utils.PatchInterfaceMap(defaultValues, mapValues)
// if err != nil {
// return err
// }
//
// values, err := yaml.Marshal(patchValues)
// if err != nil {
// return err
// }
// if err := utils.WriteFile(valuesFile, values); err != nil {
// return err
// }
return utils.WriteFile(defaultValuesFile, io)
}
//nolint:golint,unused
func getValues(path string) (map[string]map[string]interface{}, error) {
values := map[string]map[string]interface{}{}
valuesFromFile, err := os.ReadFile(path)
if err != nil {
return nil, err
}
if err := yaml.Unmarshal(valuesFromFile, &values); err != nil {
return nil, err
}
return values, nil
}
func prevValues(filename string) (map[string]map[string]interface{}, error) {
vals := make(map[string]map[interface{}]interface{})
parsed := make(map[string]map[string]interface{})
if !utils.Exists(filename) {
return parsed, nil
}
contents, err := os.ReadFile(filename)
if err != nil {
return parsed, err
}
if err := yaml.Unmarshal(contents, &vals); err != nil {
return parsed, err
}
for k, v := range vals {
parsed[k] = utils.CleanUpInterfaceMap(v)
}
return parsed, nil
}
func (s *Scaffold) createChart(w *wkspace.Workspace) error {
repo := w.Installation.Repository
if len(w.Charts) == 0 {
return utils.HighlightError(fmt.Errorf("No charts installed for this repository. You might need to run `plural bundle install %s <bundle-name>`.", repo.Name))
}
version := "0.1.0"
filename := pathing.SanitizeFilepath(filepath.Join(s.Root, ChartfileName))
if utils.Exists(filename) {
content, err := os.ReadFile(filename)
if err != nil {
return errors.ErrorWrap(err, "Failed to read existing Chart.yaml")
}
chart := chart{}
if err := yaml.Unmarshal(content, &chart); err != nil {
return errors.ErrorWrap(err, "Existing Chart.yaml has invalid yaml formatting")
}
version = chart.Version
}
appVersion := appVersion(w.Charts)
chart := &chart{
ApiVersion: "v2",
Name: repo.Name,
Description: fmt.Sprintf("A helm chart for %s", repo.Name),
Version: version,
AppVersion: appVersion,
Dependencies: s.chartDependencies(w),
}
chartFile, err := yaml.Marshal(chart)
if err != nil {
return err
}
if err := utils.WriteFile(filename, chartFile); err != nil {
return err
}
files := []struct {
path string
content []byte
force bool
}{
{
// .helmignore
path: pathing.SanitizeFilepath(filepath.Join(s.Root, IgnorefileName)),
content: []byte(defaultIgnore),
},
{
// NOTES.txt
path: pathing.SanitizeFilepath(filepath.Join(s.Root, NotesName)),
content: []byte(defaultNotes),
force: true,
},
{
// templates/secret.yaml
path: pathing.SanitizeFilepath(filepath.Join(s.Root, LicenseSecretName)),
content: []byte(licenseSecret),
force: true,
},
{
// templates/licnse.yaml
path: pathing.SanitizeFilepath(filepath.Join(s.Root, LicenseCrdName)),
content: []byte(fmt.Sprintf(license, repo.Name)),
force: true,
},
}
for _, file := range files {
if !file.force {
if _, err := os.Stat(file.path); err == nil {
// File exists and is okay. Skip it.
continue
}
}
if err := utils.WriteFile(file.path, file.content); err != nil {
return err
}
}
// remove old requirements.yaml files to fully migrate to helm v3
reqsFile := pathing.SanitizeFilepath(filepath.Join(s.Root, "requirements.yaml"))
if utils.Exists(reqsFile) {
if err := os.Remove(reqsFile); err != nil {
return err
}
}
tpl, err := ttpl.New("gotpl").Parse(defaultApplication)
if err != nil {
return err
}
var appBuffer bytes.Buffer
vars := map[string]string{
"Name": repo.Name,
"Version": appVersion,
"Description": repo.Description,
"Icon": repo.Icon,
"DarkIcon": repo.DarkIcon,
}
if err := tpl.Execute(&appBuffer, vars); err != nil {
return err
}
appBuffer.WriteString(appTemplate)
if err := utils.WriteFile(pathing.SanitizeFilepath(filepath.Join(s.Root, ApplicationName)), appBuffer.Bytes()); err != nil {
return err
}
// Need to add the ChartsDir explicitly as it does not contain any file OOTB
if err := os.MkdirAll(pathing.SanitizeFilepath(filepath.Join(s.Root, ChartsDir)), 0755); err != nil {
return err
}
return nil
}
func repoUrl(w *wkspace.Workspace, repo string, chart string) string {
if w.Links != nil {
if path, ok := w.Links.Helm[chart]; ok {
return fmt.Sprintf("file://%s", path)
}
}
url := strings.ReplaceAll(w.Config.BaseUrl(), "https", "cm")
return fmt.Sprintf("%s/cm/%s", url, repo)
}
func appVersion(charts []*api.ChartInstallation) string {
for _, inst := range charts {
if inst.Chart.Dependencies.Application {
if inst.Version.Helm != nil {
if vsn, ok := inst.Version.Helm["appVersion"]; ok {
if v, ok := vsn.(string); ok {
return v
}
}
}
return inst.Version.Version
}
}
return "0.1.0"
}