forked from PrasadG193/helm-clientgo-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
237 lines (205 loc) · 6.03 KB
/
main.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
// Example to demonstrate helm chart installation using helm client-go
// Most of the code is copied from https://github.com/helm/helm repo
package main
import (
"context"
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/gofrs/flock"
"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/downloader"
"helm.sh/helm/v3/pkg/getter"
"helm.sh/helm/v3/pkg/repo"
"helm.sh/helm/v3/pkg/strvals"
)
var settings *cli.EnvSettings
var (
url = "https://charts.helm.sh/stable"
repoName = "stable"
chartName = "mysql"
releaseName = "mysql-dev"
namespace = "mysql-test"
args = map[string]string{
// comma seperated values to set
"set": "mysqlRootPassword=admin@123,persistence.enabled=false,imagePullPolicy=Always",
}
)
func main() {
os.Setenv("HELM_NAMESPACE", namespace)
settings = cli.New()
// Add helm repo
RepoAdd(repoName, url)
// Update charts from the helm repo
RepoUpdate()
// Install charts
InstallChart(releaseName, repoName, chartName, args)
}
// RepoAdd adds repo with given name and url
func RepoAdd(name, url string) {
repoFile := settings.RepositoryConfig
//Ensure the file directory exists as it is required for file locking
err := os.MkdirAll(filepath.Dir(repoFile), os.ModePerm)
if err != nil && !os.IsExist(err) {
log.Fatal(err)
}
// Acquire a file lock for process synchronization
fileLock := flock.New(strings.Replace(repoFile, filepath.Ext(repoFile), ".lock", 1))
lockCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
locked, err := fileLock.TryLockContext(lockCtx, time.Second)
if err == nil && locked {
defer fileLock.Unlock()
}
if err != nil {
log.Fatal(err)
}
b, err := ioutil.ReadFile(repoFile)
if err != nil && !os.IsNotExist(err) {
log.Fatal(err)
}
var f repo.File
if err := yaml.Unmarshal(b, &f); err != nil {
log.Fatal(err)
}
if f.Has(name) {
fmt.Printf("repository name (%s) already exists\n", name)
return
}
c := repo.Entry{
Name: name,
URL: url,
}
r, err := repo.NewChartRepository(&c, getter.All(settings))
if err != nil {
log.Fatal(err)
}
if _, err := r.DownloadIndexFile(); err != nil {
err := errors.Wrapf(err, "looks like %q is not a valid chart repository or cannot be reached", url)
log.Fatal(err)
}
f.Update(&c)
if err := f.WriteFile(repoFile, 0644); err != nil {
log.Fatal(err)
}
fmt.Printf("%q has been added to your repositories\n", name)
}
// RepoUpdate updates charts for all helm repos
func RepoUpdate() {
repoFile := settings.RepositoryConfig
f, err := repo.LoadFile(repoFile)
if os.IsNotExist(errors.Cause(err)) || len(f.Repositories) == 0 {
log.Fatal(errors.New("no repositories found. You must add one before updating"))
}
var repos []*repo.ChartRepository
for _, cfg := range f.Repositories {
r, err := repo.NewChartRepository(cfg, getter.All(settings))
if err != nil {
log.Fatal(err)
}
repos = append(repos, r)
}
fmt.Printf("Hang tight while we grab the latest from your chart repositories...\n")
var wg sync.WaitGroup
for _, re := range repos {
wg.Add(1)
go func(re *repo.ChartRepository) {
defer wg.Done()
if _, err := re.DownloadIndexFile(); err != nil {
fmt.Printf("...Unable to get an update from the %q chart repository (%s):\n\t%s\n", re.Config.Name, re.Config.URL, err)
} else {
fmt.Printf("...Successfully got an update from the %q chart repository\n", re.Config.Name)
}
}(re)
}
wg.Wait()
fmt.Printf("Update Complete. ⎈ Happy Helming!⎈\n")
}
// InstallChart
func InstallChart(name, repo, chart string, args map[string]string) {
actionConfig := new(action.Configuration)
if err := actionConfig.Init(settings.RESTClientGetter(), settings.Namespace(), os.Getenv("HELM_DRIVER"), debug); err != nil {
log.Fatal(err)
}
client := action.NewInstall(actionConfig)
if client.Version == "" && client.Devel {
client.Version = ">0.0.0-0"
}
//name, chart, err := client.NameAndChart(args)
client.ReleaseName = name
cp, err := client.ChartPathOptions.LocateChart(fmt.Sprintf("%s/%s", repo, chart), settings)
if err != nil {
log.Fatal(err)
}
debug("CHART PATH: %s\n", cp)
p := getter.All(settings)
valueOpts := &values.Options{}
vals, err := valueOpts.MergeValues(p)
if err != nil {
log.Fatal(err)
}
// Add args
if err := strvals.ParseInto(args["set"], vals); err != nil {
log.Fatal(errors.Wrap(err, "failed parsing --set data"))
}
// Check chart dependencies to make sure all are present in /charts
chartRequested, err := loader.Load(cp)
if err != nil {
log.Fatal(err)
}
validInstallableChart, err := isChartInstallable(chartRequested)
if !validInstallableChart {
log.Fatal(err)
}
if req := chartRequested.Metadata.Dependencies; req != nil {
// If CheckDependencies returns an error, we have unfulfilled dependencies.
// As of Helm 2.4.0, this is treated as a stopping condition:
// https://github.com/helm/helm/issues/2209
if err := action.CheckDependencies(chartRequested, req); err != nil {
if client.DependencyUpdate {
man := &downloader.Manager{
Out: os.Stdout,
ChartPath: cp,
Keyring: client.ChartPathOptions.Keyring,
SkipUpdate: false,
Getters: p,
RepositoryConfig: settings.RepositoryConfig,
RepositoryCache: settings.RepositoryCache,
}
if err := man.Update(); err != nil {
log.Fatal(err)
}
} else {
log.Fatal(err)
}
}
}
client.Namespace = settings.Namespace()
release, err := client.Run(chartRequested, vals)
if err != nil {
log.Fatal(err)
}
fmt.Println(release.Manifest)
}
func isChartInstallable(ch *chart.Chart) (bool, error) {
switch ch.Metadata.Type {
case "", "application":
return true, nil
}
return false, errors.Errorf("%s charts are not installable", ch.Metadata.Type)
}
func debug(format string, v ...interface{}) {
format = fmt.Sprintf("[debug] %s\n", format)
log.Output(2, fmt.Sprintf(format, v...))
}