-
Notifications
You must be signed in to change notification settings - Fork 0
/
helm.go
222 lines (202 loc) · 5.88 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
// SPDX-FileCopyrightText: 2024 Karl Theil @karlderkaefer
// SPDX-FileContributor: Karl Theil @karlderkaefer
//
// SPDX-License-Identifier: MIT-Modern-Variant
package main
import (
"bytes"
"fmt"
"log"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"sync"
"helm.sh/helm/v3/pkg/chart/loader"
)
type ChartInfo struct {
Path string
Level int
NestedCharts []ChartInfo
Registries map[string]*RegistryInfo
}
type HelmUpdater struct {
registryHelper *RegistryHelper
config *HelmUpdateConfig
}
type HelmUpdateConfig struct {
SkipRepoOverwrite bool // ENV: HELM_DEPS_SKIP_REPO_OVERWRITE
SkipDepdencyRefresh bool // ENV: HELM_DEPS_SKIP_REFRESH
FetchArgocdRepoSecrets bool // ENV: HELM_DEPS_FETCH_ARGOCD_REPO_SECRETS
UseRandomHelmCacheDir bool // ENV: HELM_DEPS_RANDOM_CACHE_DIR
}
func (c *ChartInfo) AddDependencyUrl(depdencyUrl string) error {
if depdencyUrl == "" {
return nil
}
hostnameKey := sanitizeHostname(depdencyUrl)
parsedURL, err := url.Parse(depdencyUrl)
if err != nil {
return fmt.Errorf("failed to parse URL: %s in Chart %s : %w", depdencyUrl, c.Path, err)
}
if parsedURL.Scheme == "file" {
return nil
}
if !(parsedURL.Scheme == "oci" || parsedURL.Scheme == "https") {
log.Printf("Unsupported scheme %s in URL: %s in Chart %s. Skipping adding registry", parsedURL.Scheme, depdencyUrl, c.Path)
return nil
}
registry := &RegistryInfo{
Hostname: parsedURL.String(),
SecretName: hostnameKey,
EnableOCI: false,
}
if parsedURL.Scheme == "oci" {
registry.EnableOCI = true
}
c.Registries[hostnameKey] = registry
return nil
}
func (updater *HelmUpdater) UpdateChart(chartPath string) error {
chartInfo, err := loadChartInfo(chartPath, 1)
if err != nil {
return err
}
// we login to all collected registries before updating dependencies
if updater.config.SkipDepdencyRefresh {
for _, registry := range chartInfo.Registries {
err := updater.registryHelper.LoginIfExists(registry)
if err != nil {
return err
}
}
// update helm repo after adding all registries
_, reposAvailable, err := helmRepoExists(&RegistryInfo{Hostname: ""}, updater.config)
if err != nil {
return err
}
if reposAvailable {
err := runHelmCommand("repo", "update")
if err != nil {
return err
}
}
}
return updater.updateDependencies(chartInfo)
}
// sanitizeHostname replaces all non-alphanumeric characters with hyphens
func sanitizeHostname(input string) string {
re := regexp.MustCompile(`[^a-zA-Z0-9]+`)
return re.ReplaceAllString(input, "-")
}
func loadChartInfo(chartPath string, level int) (ChartInfo, error) {
chart, err := loader.Load(chartPath)
if err != nil {
return ChartInfo{}, err
}
chartInfo := ChartInfo{Path: chartPath, Level: level, Registries: make(map[string]*RegistryInfo)}
regex := regexp.MustCompile("file://(.*)")
// Collect URLs of dependencies
for _, dep := range chart.Metadata.Dependencies {
_ = chartInfo.AddDependencyUrl(dep.Repository)
if regex.MatchString(dep.Repository) {
relativePath := strings.TrimPrefix(dep.Repository, "file://")
depPath := filepath.Join(chartPath, relativePath)
nestedChart, err := loadChartInfo(depPath, level+1)
if err != nil {
return ChartInfo{}, err
}
chartInfo.NestedCharts = append(chartInfo.NestedCharts, nestedChart)
// Merge URLs from nested charts
for _, registry := range nestedChart.Registries {
err := chartInfo.AddDependencyUrl(registry.Hostname)
if err != nil {
log.Printf("Failed to add registry: %s", err)
}
}
}
}
return chartInfo, nil
}
func (updater *HelmUpdater) updateDependencies(chartInfo ChartInfo) error {
// Update dependencies for nested charts
var wg sync.WaitGroup
errChan := make(chan error, len(chartInfo.NestedCharts))
for _, nestedChart := range chartInfo.NestedCharts {
wg.Add(1)
go func(nestedChart ChartInfo) {
defer wg.Done()
fmt.Printf("Updating chart dependencies for %s at level %d\n", nestedChart.Path, nestedChart.Level)
if err := updater.updateDependencies(nestedChart); err != nil {
errChan <- err
}
}(nestedChart)
}
wg.Wait()
close(errChan)
// Check for any errors that occurred during the dependency updates
for err := range errChan {
if err != nil {
return err
}
}
return updater.helmDepUpdate(chartInfo.Path)
}
// Remove lock file to allow to rebuild dependencies on helm build command
func cleanupLockFiles(chartPath string) error {
lockFiles := []string{"Chart.lock", "requirements.lock"}
for _, lockFile := range lockFiles {
path := filepath.Join(chartPath, lockFile)
if _, err := os.Stat(path); err == nil {
if err := os.Remove(path); err != nil {
return err
}
}
}
return nil
}
func runHelmCommand(args ...string) error {
cmd := exec.Command("helm", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
// helmRepoExists checks if a helm repository already exists with helm repo ls command
func helmRepoExists(registry *RegistryInfo, config *HelmUpdateConfig) (bool, bool, error) {
if !config.SkipRepoOverwrite {
return false, false, nil
}
cmd := exec.Command("helm", "repo", "ls")
var out bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &out
err := cmd.Run()
if err != nil {
// Check if the error is due to no repositories existing
if strings.Contains(out.String(), "no repositories to show") {
return false, false, nil
}
return false, false, fmt.Errorf("failed to run helm repo ls: %w", err)
}
output := out.String()
lines := strings.Split(output, "\n")
for _, line := range lines {
if strings.Contains(line, registry.Hostname) {
return true, true, nil
}
}
return false, true, nil
}
func (updater *HelmUpdater) helmDepUpdate(chartPath string) error {
err := cleanupLockFiles(chartPath)
if err != nil {
return err
}
args := []string{"dependency", "update", chartPath}
if updater.config.SkipDepdencyRefresh {
args = append(args, "--skip-refresh")
}
return runHelmCommand(args...)
}