-
Notifications
You must be signed in to change notification settings - Fork 222
/
Copy pathchart.go
933 lines (802 loc) · 28.2 KB
/
chart.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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
// Copyright The Helm 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 chart
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/Masterminds/semver"
"github.com/helm/chart-testing/v3/pkg/config"
"github.com/helm/chart-testing/v3/pkg/exec"
"github.com/helm/chart-testing/v3/pkg/tool"
"github.com/helm/chart-testing/v3/pkg/util"
"github.com/pkg/errors"
)
const maxNameLength = 63
// Git is the Interface that wraps Git operations.
//
// FileExistsOnBranch checks whether file exists on the specified remote/branch.
//
// Show returns the contents of file on the specified remote/branch.
//
// AddWorktree checks out the contents of the repository at a commit ref into the specified path.
//
// RemoveWorktree removes the working tree at the specified path.
//
// MergeBase returns the SHA1 of the merge base of commit1 and commit2.
//
// ListChangedFilesInDirs diffs commit against HEAD and returns changed files for the specified dirs.
//
// GetUrlForRemote returns the repo URL for the specified remote.
//
// ValidateRepository checks that the current working directory is a valid git repository,
// and returns nil if valid.
type Git interface {
FileExistsOnBranch(file string, remote string, branch string) bool
Show(file string, remote string, branch string) (string, error)
AddWorktree(path string, ref string) error
RemoveWorktree(path string) error
MergeBase(commit1 string, commit2 string) (string, error)
ListChangedFilesInDirs(commit string, dirs ...string) ([]string, error)
GetUrlForRemote(remote string) (string, error)
ValidateRepository() error
}
// Helm is the interface that wraps Helm operations
//
// AddRepo adds a chart repository to the local Helm configuration
//
// BuildDependencies builds the chart's dependencies
//
// LintWithValues runs `helm lint` for the given chart using the specified values file.
// Pass a zero value for valuesFile in order to run lint without specifying a values file.
//
// InstallWithValues runs `helm install` for the given chart using the specified values file.
// Pass a zero value for valuesFile in order to run install without specifying a values file.
//
// Upgrade runs `helm upgrade` against an existing release, and re-uses the previously computed values.
//
// Test runs `helm test` against an existing release. Set the cleanup argument to true in order
// to clean up test pods created by helm after the test command completes.
//
// DeleteRelease purges the specified Helm release.
type Helm interface {
AddRepo(name string, url string, extraArgs []string) error
BuildDependencies(chart string) error
LintWithValues(chart string, valuesFile string) error
InstallWithValues(chart string, valuesFile string, namespace string, release string) error
Upgrade(chart string, namespace string, release string) error
Test(namespace string, release string) error
DeleteRelease(namespace string, release string)
Version() (string, error)
}
// Kubectl is the interface that wraps kubectl operations
//
// DeleteNamespace deletes a namespace
//
// WaitForDeployments waits for a deployment to become ready
//
// GetPodsforDeployment gets all pods for a deployment
//
// GetPods gets pods for the given args
//
// GetEvents prints all events for namespace
//
// DescribePod prints the pod's description
//
// Logs prints the logs of container
//
// GetInitContainers gets all init containers of pod
//
// GetContainers gets all containers of pod
type Kubectl interface {
CreateNamespace(namespace string) error
DeleteNamespace(namespace string)
WaitForDeployments(namespace string, selector string) error
GetPodsforDeployment(namespace string, deployment string) ([]string, error)
GetPods(args ...string) ([]string, error)
GetEvents(namespace string) error
DescribePod(namespace string, pod string) error
Logs(namespace string, pod string, container string) error
GetInitContainers(namespace string, pod string) ([]string, error)
GetContainers(namespace string, pod string) ([]string, error)
}
// Linter is the interface that wrap linting operations
//
// YamlLint runs `yamllint` on the specified file with the specified configuration
//
// Yamale runs `yamale` on the specified file with the specified schema file
type Linter interface {
YamlLint(yamlFile string, configFile string) error
Yamale(yamlFile string, schemaFile string) error
}
// CmdExecutor is the interface
//
// RunCommand renders cmdTemplate as go template using data and executes the resulting command
type CmdExecutor interface {
RunCommand(cmdTemplate string, data interface{}) error
}
// DirectoryLister is the interface
//
// ListChildDirs lists direct child directories of parentDir given they pass the test function
type DirectoryLister interface {
ListChildDirs(parentDir string, test func(string) bool) ([]string, error)
}
// ChartUtils is the interface that wraps chart-related methods
//
// LookupChartDir looks up the chart's root directory based on some chart file that has changed
type ChartUtils interface {
LookupChartDir(chartDirs []string, dir string) (string, error)
}
// AccountValidator is the interface that wraps Git account validation
//
// Validate checks if account is valid on repoDomain
type AccountValidator interface {
Validate(repoDomain string, account string) error
}
// Chart represents a Helm chart, and can be initialized with the NewChart method.
type Chart struct {
path string
yaml *util.ChartYaml
ciValuesPaths []string
}
// Yaml returns the Chart metadata
func (c *Chart) Yaml() *util.ChartYaml {
return c.yaml
}
// Path returns the chart's directory path
func (c *Chart) Path() string {
return c.path
}
func (c *Chart) String() string {
return fmt.Sprintf(`%s => (version: "%s", path: "%s")`, c.yaml.Name, c.yaml.Version, c.Path())
}
// ValuesFilePathsForCI returns all file paths in the 'ci' subfolder of the chart directory matching the pattern '*-values.yaml'
func (c *Chart) ValuesFilePathsForCI() []string {
return c.ciValuesPaths
}
// HasCIValuesFile checks whether a given CI values file is present.
func (c *Chart) HasCIValuesFile(path string) bool {
fileName := filepath.Base(path)
for _, file := range c.ValuesFilePathsForCI() {
if fileName == filepath.Base(file) {
return true
}
}
return false
}
// CreateInstallParams generates a randomized release name and namespace based on the chart path
// and optional buildID. If a buildID is specified, it will be part of the generated namespace.
func (c *Chart) CreateInstallParams(buildID string) (release string, namespace string) {
release = filepath.Base(c.Path())
if release == "." || release == "/" {
yaml := c.Yaml()
release = yaml.Name
}
namespace = release
if buildID != "" {
namespace = fmt.Sprintf("%s-%s", namespace, buildID)
}
randomSuffix := util.RandomString(10)
release = util.SanitizeName(fmt.Sprintf("%s-%s", release, randomSuffix), maxNameLength)
namespace = util.SanitizeName(fmt.Sprintf("%s-%s", namespace, randomSuffix), maxNameLength)
return
}
// NewChart parses the path to a chart directory and allocates a new Chart object. If chartPath is
// not a valid chart directory an error is returned.
func NewChart(chartPath string) (*Chart, error) {
yaml, err := util.ReadChartYaml(chartPath)
if err != nil {
return nil, err
}
matches, _ := filepath.Glob(filepath.Join(chartPath, "ci", "*-values.yaml"))
return &Chart{chartPath, yaml, matches}, nil
}
type Testing struct {
config config.Configuration
helm Helm
kubectl Kubectl
git Git
linter Linter
cmdExecutor CmdExecutor
accountValidator AccountValidator
directoryLister DirectoryLister
chartUtils ChartUtils
previousRevisionWorktree string
}
// TestResults holds results and overall status
type TestResults struct {
OverallSuccess bool
TestResults []TestResult
}
// TestResult holds test results for a specific chart
type TestResult struct {
Chart *Chart
Error error
}
// NewTesting creates a new Testing struct with the given config.
func NewTesting(config config.Configuration) (Testing, error) {
procExec := exec.NewProcessExecutor(config.Debug)
extraArgs := strings.Fields(config.HelmExtraArgs)
testing := Testing{
config: config,
helm: tool.NewHelm(procExec, extraArgs),
git: tool.NewGit(procExec),
kubectl: tool.NewKubectl(procExec),
linter: tool.NewLinter(procExec),
cmdExecutor: tool.NewCmdTemplateExecutor(procExec),
accountValidator: tool.AccountValidator{},
directoryLister: util.DirectoryLister{},
chartUtils: util.ChartUtils{},
}
versionString, err := testing.helm.Version()
if err != nil {
return testing, err
}
version, err := semver.NewVersion(versionString)
if err != nil {
return testing, err
}
if version.Major() < 3 {
return testing, fmt.Errorf("minimum required Helm version is v3.0.0; found: %s", version)
}
return testing, nil
}
// computePreviousRevisionPath converts any file or directory path to the same path in the
// previous revision's working tree.
func (t *Testing) computePreviousRevisionPath(fileOrDirPath string) string {
return filepath.Join(t.previousRevisionWorktree, fileOrDirPath)
}
func (t *Testing) processCharts(action func(chart *Chart) TestResult) ([]TestResult, error) {
var results []TestResult
chartDirs, err := t.FindChartDirsToBeProcessed()
if err != nil {
return nil, errors.Wrap(err, "Error identifying charts to process")
} else if len(chartDirs) == 0 {
return results, nil
}
var charts []*Chart
for _, dir := range chartDirs {
chart, err := NewChart(dir)
if err != nil {
return nil, err
}
if t.config.ExcludeDeprecated && chart.yaml.Deprecated {
fmt.Printf("Chart '%s' is deprecated and will be ignored because '--exclude-deprecated' is set\n", chart.String())
} else {
charts = append(charts, chart)
}
}
fmt.Println()
util.PrintDelimiterLine("-")
fmt.Println(" Charts to be processed:")
util.PrintDelimiterLine("-")
for _, chart := range charts {
fmt.Printf(" %s\n", chart)
}
util.PrintDelimiterLine("-")
fmt.Println()
repoArgs := map[string][]string{}
for _, repo := range t.config.HelmRepoExtraArgs {
repoSlice := strings.SplitN(repo, "=", 2)
name := repoSlice[0]
repoExtraArgs := strings.Fields(repoSlice[1])
repoArgs[name] = repoExtraArgs
}
for _, repo := range t.config.ChartRepos {
repoSlice := strings.SplitN(repo, "=", 2)
name := repoSlice[0]
url := repoSlice[1]
repoExtraArgs := repoArgs[name]
if err := t.helm.AddRepo(name, url, repoExtraArgs); err != nil {
return nil, errors.Wrapf(err, "Error adding repo: %s=%s", name, url)
}
}
testResults := TestResults{
OverallSuccess: true,
TestResults: results,
}
// Checkout previous chart revisions and build their dependencies
if t.config.Upgrade {
mergeBase, err := t.computeMergeBase()
if err != nil {
return results, errors.Wrap(err, "Error identifying merge base")
}
// Add worktree for the target revision
worktreePath, err := ioutil.TempDir("./", "ct_previous_revision")
if err != nil {
return results, errors.Wrap(err, "Could not create previous revision directory")
}
t.previousRevisionWorktree = worktreePath
err = t.git.AddWorktree(worktreePath, mergeBase)
if err != nil {
return results, errors.Wrap(err, "Could not create worktree for previous revision")
}
defer t.git.RemoveWorktree(worktreePath)
for _, chart := range charts {
if err := t.helm.BuildDependencies(t.computePreviousRevisionPath(chart.Path())); err != nil {
// Only print error (don't exit) if building dependencies for previous revision fails.
fmt.Println(errors.Wrapf(err, "Error building dependencies for previous revision of chart '%s'\n", chart))
}
}
}
for _, chart := range charts {
if err := t.helm.BuildDependencies(chart.Path()); err != nil {
return nil, errors.Wrapf(err, "Error building dependencies for chart '%s'", chart)
}
result := action(chart)
if result.Error != nil {
testResults.OverallSuccess = false
}
results = append(results, result)
}
if testResults.OverallSuccess {
return results, nil
}
return results, errors.New("Error processing charts")
}
// LintCharts lints charts (changed, all, specific) depending on the configuration.
func (t *Testing) LintCharts() ([]TestResult, error) {
return t.processCharts(t.LintChart)
}
// InstallCharts install charts (changed, all, specific) depending on the configuration.
func (t *Testing) InstallCharts() ([]TestResult, error) {
return t.processCharts(t.InstallChart)
}
// LintAndInstallCharts first lints and then installs charts (changed, all, specific) depending on the configuration.
func (t *Testing) LintAndInstallCharts() ([]TestResult, error) {
return t.processCharts(t.LintAndInstallChart)
}
// PrintResults writes test results to stdout.
func (t *Testing) PrintResults(results []TestResult) {
util.PrintDelimiterLine("-")
if results != nil {
for _, result := range results {
err := result.Error
if err != nil {
fmt.Printf(" %s %s > %s\n", "✖︎", result.Chart, err)
} else {
fmt.Printf(" %s %s\n", "✔︎", result.Chart)
}
}
} else {
fmt.Println("No chart changes detected.")
}
util.PrintDelimiterLine("-")
}
// LintChart lints the specified chart.
func (t *Testing) LintChart(chart *Chart) TestResult {
fmt.Printf("Linting chart '%s'\n", chart)
result := TestResult{Chart: chart}
if t.config.CheckVersionIncrement {
if err := t.CheckVersionIncrement(chart); err != nil {
result.Error = err
return result
}
}
chartYaml := filepath.Join(chart.Path(), "Chart.yaml")
valuesYaml := filepath.Join(chart.Path(), "values.yaml")
valuesFiles := chart.ValuesFilePathsForCI()
if t.config.ValidateChartSchema {
if err := t.linter.Yamale(chartYaml, t.config.ChartYamlSchema); err != nil {
result.Error = err
return result
}
}
if t.config.ValidateYaml {
yamlFiles := append([]string{chartYaml, valuesYaml}, valuesFiles...)
for _, yamlFile := range yamlFiles {
if err := t.linter.YamlLint(yamlFile, t.config.LintConf); err != nil {
result.Error = err
return result
}
}
}
if t.config.ValidateMaintainers {
if err := t.ValidateMaintainers(chart); err != nil {
result.Error = err
return result
}
}
for _, cmd := range t.config.AdditionalCommands {
if err := t.cmdExecutor.RunCommand(cmd, chart); err != nil {
result.Error = err
return result
}
}
// Lint with defaults if no values files are specified.
if len(valuesFiles) == 0 {
valuesFiles = append(valuesFiles, "")
}
for _, valuesFile := range valuesFiles {
if valuesFile != "" {
fmt.Printf("\nLinting chart with values file '%s'...\n\n", valuesFile)
}
if err := t.helm.LintWithValues(chart.Path(), valuesFile); err != nil {
result.Error = err
break
}
}
return result
}
// InstallChart installs the specified chart into a new namespace, waits for resources to become ready, and eventually
// uninstalls it and deletes the namespace again.
func (t *Testing) InstallChart(chart *Chart) TestResult {
var result TestResult
if t.config.Upgrade {
// Test upgrade from previous version
result = t.UpgradeChart(chart)
if result.Error != nil {
return result
}
// Test upgrade of current version (related: https://github.com/helm/chart-testing/issues/19)
if err := t.doUpgrade(chart, chart, true); err != nil {
result.Error = err
return result
}
}
result = TestResult{Chart: chart}
if err := t.doInstall(chart); err != nil {
result.Error = err
}
return result
}
// UpgradeChart tests in-place upgrades of the specified chart relative to its previous revisions. If the
// initial install or helm test of a previous revision of the chart fails, that release is ignored and no
// error will be returned. If the latest revision of the chart introduces a potentially breaking change
// according to the SemVer specification, upgrade testing will be skipped.
func (t *Testing) UpgradeChart(chart *Chart) TestResult {
result := TestResult{Chart: chart}
breakingChangeAllowed, err := t.checkBreakingChangeAllowed(chart)
if breakingChangeAllowed {
if err != nil {
fmt.Println(errors.Wrap(err, fmt.Sprintf("Skipping upgrade test of '%s' because", chart)))
}
return result
} else if err != nil {
fmt.Printf("Error comparing chart versions for '%s'\n", chart)
result.Error = err
return result
}
if oldChart, err := NewChart(t.computePreviousRevisionPath(chart.Path())); err == nil {
result.Error = t.doUpgrade(oldChart, chart, false)
}
return result
}
func (t *Testing) doInstall(chart *Chart) error {
fmt.Printf("Installing chart '%s'...\n", chart)
valuesFiles := chart.ValuesFilePathsForCI()
// Test with defaults if no values files are specified.
if len(valuesFiles) == 0 {
valuesFiles = append(valuesFiles, "")
}
for _, valuesFile := range valuesFiles {
if valuesFile != "" {
fmt.Printf("\nInstalling chart with values file '%s'...\n\n", valuesFile)
}
// Use anonymous function. Otherwise deferred calls would pile up
// and be executed in reverse order after the loop.
fun := func() error {
namespace, release, releaseSelector, cleanup := t.generateInstallConfig(chart)
defer cleanup()
if t.config.Namespace == "" {
if err := t.kubectl.CreateNamespace(namespace); err != nil {
return err
}
}
if err := t.helm.InstallWithValues(chart.Path(), valuesFile, namespace, release); err != nil {
return err
}
return t.testRelease(namespace, release, releaseSelector)
}
if err := fun(); err != nil {
return err
}
}
return nil
}
func (t *Testing) doUpgrade(oldChart, newChart *Chart, oldChartMustPass bool) error {
fmt.Printf("Testing upgrades of chart '%s' relative to previous revision '%s'...\n", newChart, oldChart)
valuesFiles := oldChart.ValuesFilePathsForCI()
if len(valuesFiles) == 0 {
valuesFiles = append(valuesFiles, "")
}
for _, valuesFile := range valuesFiles {
if valuesFile != "" {
if t.config.SkipMissingValues && !newChart.HasCIValuesFile(valuesFile) {
fmt.Printf("Upgrade testing for values file '%s' skipped because a corresponding values file was not found in %s/ci", valuesFile, newChart.Path())
continue
}
fmt.Printf("\nInstalling chart '%s' with values file '%s'...\n\n", oldChart, valuesFile)
}
// Use anonymous function. Otherwise deferred calls would pile up
// and be executed in reverse order after the loop.
fun := func() error {
namespace, release, releaseSelector, cleanup := t.generateInstallConfig(oldChart)
defer cleanup()
if t.config.Namespace == "" {
if err := t.kubectl.CreateNamespace(namespace); err != nil {
return err
}
}
// Install previous version of chart. If installation fails, ignore this release.
if err := t.helm.InstallWithValues(oldChart.Path(), valuesFile, namespace, release); err != nil {
if oldChartMustPass {
return err
}
fmt.Println(errors.Wrap(err, fmt.Sprintf("Upgrade testing for release '%s' skipped because of previous revision installation error", release)))
return nil
}
if err := t.testRelease(namespace, release, releaseSelector); err != nil {
if oldChartMustPass {
return err
}
fmt.Println(errors.Wrap(err, fmt.Sprintf("Upgrade testing for release '%s' skipped because of previous revision testing error", release)))
return nil
}
if err := t.helm.Upgrade(oldChart.Path(), namespace, release); err != nil {
return err
}
return t.testRelease(namespace, release, releaseSelector)
}
if err := fun(); err != nil {
return err
}
}
return nil
}
func (t *Testing) testRelease(namespace, release, releaseSelector string) error {
if err := t.kubectl.WaitForDeployments(namespace, releaseSelector); err != nil {
return err
}
if err := t.helm.Test(namespace, release); err != nil {
return err
}
return nil
}
func (t *Testing) generateInstallConfig(chart *Chart) (namespace, release, releaseSelector string, cleanup func()) {
if t.config.Namespace != "" {
namespace = t.config.Namespace
release, _ = chart.CreateInstallParams(t.config.BuildId)
releaseSelector = fmt.Sprintf("%s=%s", t.config.ReleaseLabel, release)
cleanup = func() {
t.PrintEventsPodDetailsAndLogs(namespace, releaseSelector)
t.helm.DeleteRelease(namespace, release)
}
} else {
release, namespace = chart.CreateInstallParams(t.config.BuildId)
cleanup = func() {
t.PrintEventsPodDetailsAndLogs(namespace, releaseSelector)
t.helm.DeleteRelease(namespace, release)
t.kubectl.DeleteNamespace(namespace)
}
}
return
}
// LintAndInstallChart first lints and then installs the specified chart.
func (t *Testing) LintAndInstallChart(chart *Chart) TestResult {
result := t.LintChart(chart)
if result.Error != nil {
return result
}
return t.InstallChart(chart)
}
// FindChartDirsToBeProcessed identifies charts to be processed depending on the configuration
// (changed charts, all charts, or specific charts).
func (t *Testing) FindChartDirsToBeProcessed() ([]string, error) {
cfg := t.config
if cfg.ProcessAllCharts {
return t.ReadAllChartDirectories()
} else if len(cfg.Charts) > 0 {
return t.config.Charts, nil
}
return t.ComputeChangedChartDirectories()
}
func (t *Testing) computeMergeBase() (string, error) {
err := t.git.ValidateRepository()
if err != nil {
return "", errors.New("Must be in a git repository")
}
return t.git.MergeBase(fmt.Sprintf("%s/%s", t.config.Remote, t.config.TargetBranch), t.config.Since)
}
// ComputeChangedChartDirectories takes the merge base of HEAD and the configured remote and target branch and computes a
// slice of changed charts from that in the configured chart directories excluding those configured to be excluded.
func (t *Testing) ComputeChangedChartDirectories() ([]string, error) {
cfg := t.config
mergeBase, err := t.computeMergeBase()
if err != nil {
return nil, err
}
allChangedChartFiles, err := t.git.ListChangedFilesInDirs(mergeBase, cfg.ChartDirs...)
if err != nil {
return nil, errors.Wrap(err, "Error creating diff")
}
var changedChartDirs []string
for _, file := range allChangedChartFiles {
pathElements := strings.SplitN(filepath.ToSlash(file), "/", 3)
if len(pathElements) < 2 || util.StringSliceContains(cfg.ExcludedCharts, pathElements[1]) {
continue
}
dir := filepath.Dir(file)
// Make sure directory is really a chart directory
chartDir, err := t.chartUtils.LookupChartDir(cfg.ChartDirs, dir)
if err == nil {
// Only add it if not already in the list
if !util.StringSliceContains(changedChartDirs, chartDir) {
changedChartDirs = append(changedChartDirs, chartDir)
}
} else {
fmt.Fprintf(os.Stderr, "Directory '%s' is not a valid chart directory. Skipping...\n", dir)
}
}
return changedChartDirs, nil
}
// ReadAllChartDirectories returns a slice of all charts in the configured chart directories except those
// configured to be excluded.
func (t *Testing) ReadAllChartDirectories() ([]string, error) {
cfg := t.config
var chartDirs []string
for _, chartParentDir := range cfg.ChartDirs {
dirs, err := t.directoryLister.ListChildDirs(chartParentDir,
func(dir string) bool {
_, err := t.chartUtils.LookupChartDir(cfg.ChartDirs, dir)
return err == nil && !util.StringSliceContains(cfg.ExcludedCharts, filepath.Base(dir))
})
if err != nil {
return nil, errors.Wrap(err, "Error reading chart directories")
}
chartDirs = append(chartDirs, dirs...)
}
return chartDirs, nil
}
// CheckVersionIncrement checks that the new chart version is greater than the old one using semantic version comparison.
func (t *Testing) CheckVersionIncrement(chart *Chart) error {
fmt.Printf("Checking chart '%s' for a version bump...\n", chart)
oldVersion, err := t.GetOldChartVersion(chart.Path())
if err != nil {
return err
}
if oldVersion == "" {
// new chart, skip version check
return nil
}
fmt.Println("Old chart version:", oldVersion)
chartYaml := chart.Yaml()
newVersion := chartYaml.Version
fmt.Println("New chart version:", newVersion)
result, err := util.CompareVersions(oldVersion, newVersion)
if err != nil {
return err
}
if result >= 0 {
return errors.New("Chart version not ok. Needs a version bump!")
}
fmt.Println("Chart version ok.")
return nil
}
func (t *Testing) checkBreakingChangeAllowed(chart *Chart) (allowed bool, err error) {
oldVersion, err := t.GetOldChartVersion(chart.Path())
if err != nil {
return false, err
}
if oldVersion == "" {
// new chart, skip upgrade check
return true, fmt.Errorf("chart has no previous revision")
}
newVersion := chart.Yaml().Version
return util.BreakingChangeAllowed(oldVersion, newVersion)
}
// GetOldChartVersion gets the version of the old Chart.yaml file from the target branch.
func (t *Testing) GetOldChartVersion(chartPath string) (string, error) {
cfg := t.config
chartYamlFile := filepath.Join(chartPath, "Chart.yaml")
if !t.git.FileExistsOnBranch(chartYamlFile, cfg.Remote, cfg.TargetBranch) {
fmt.Printf("Unable to find chart on %s. New chart detected.\n", cfg.TargetBranch)
return "", nil
}
chartYamlContents, err := t.git.Show(chartYamlFile, cfg.Remote, cfg.TargetBranch)
if err != nil {
return "", errors.Wrap(err, "Error reading old Chart.yaml")
}
chartYaml, err := util.UnmarshalChartYaml([]byte(chartYamlContents))
if err != nil {
return "", errors.Wrap(err, "Error reading old chart version")
}
return chartYaml.Version, nil
}
// ValidateMaintainers validates maintainers in the Chart.yaml file. Maintainer names must be valid accounts
// (GitHub, Bitbucket, GitLab) names. Deprecated charts must not have maintainers.
func (t *Testing) ValidateMaintainers(chart *Chart) error {
fmt.Println("Validating maintainers...")
chartYaml := chart.Yaml()
if chartYaml.Deprecated {
if len(chartYaml.Maintainers) > 0 {
return errors.New("Deprecated chart must not have maintainers")
}
return nil
}
if len(chartYaml.Maintainers) == 0 {
return errors.New("Chart doesn't have maintainers")
}
repoUrl, err := t.git.GetUrlForRemote(t.config.Remote)
if err != nil {
return err
}
for _, maintainer := range chartYaml.Maintainers {
if err := t.accountValidator.Validate(repoUrl, maintainer.Name); err != nil {
return err
}
}
return nil
}
func (t *Testing) PrintEventsPodDetailsAndLogs(namespace string, selector string) {
util.PrintDelimiterLine("=")
printDetails(namespace, "Events of namespace", ".", func(item string) error {
return t.kubectl.GetEvents(namespace)
}, namespace)
pods, err := t.kubectl.GetPods(
"--no-headers",
"--namespace",
namespace,
"--selector",
selector,
"--output",
"jsonpath={.items[*].metadata.name}",
)
if err != nil {
fmt.Println("Error printing logs:", err)
return
}
for _, pod := range pods {
printDetails(pod, "Description of pod", "~", func(item string) error {
return t.kubectl.DescribePod(namespace, pod)
}, pod)
initContainers, err := t.kubectl.GetInitContainers(namespace, pod)
if err != nil {
fmt.Println("Error printing logs:", err)
return
}
printDetails(pod, "Logs of init container", "-",
func(item string) error {
return t.kubectl.Logs(namespace, pod, item)
}, initContainers...)
containers, err := t.kubectl.GetContainers(namespace, pod)
if err != nil {
fmt.Println("Error printing logs:", err)
return
}
printDetails(pod, "Logs of container", "-",
func(item string) error {
return t.kubectl.Logs(namespace, pod, item)
},
containers...)
}
util.PrintDelimiterLine("=")
}
func printDetails(resource string, text string, delimiterChar string, printFunc func(item string) error, items ...string) {
for _, item := range items {
item = strings.Trim(item, "'")
util.PrintDelimiterLine(delimiterChar)
fmt.Printf("==> %s %s\n", text, resource)
util.PrintDelimiterLine(delimiterChar)
if err := printFunc(item); err != nil {
fmt.Println("Error printing details:", err)
return
}
util.PrintDelimiterLine(delimiterChar)
fmt.Printf("<== %s %s\n", text, resource)
util.PrintDelimiterLine(delimiterChar)
}
}