forked from operator-framework/operator-sdk
/
chart.go
295 lines (261 loc) · 9.08 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
// Copyright 2018 The Operator-SDK 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 helm
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/operator-framework/operator-sdk/internal/pkg/scaffold"
"github.com/iancoleman/strcase"
log "github.com/sirupsen/logrus"
"k8s.io/helm/pkg/chartutil"
"k8s.io/helm/pkg/downloader"
"k8s.io/helm/pkg/getter"
"k8s.io/helm/pkg/helm/environment"
"k8s.io/helm/pkg/helm/helmpath"
"k8s.io/helm/pkg/proto/hapi/chart"
"k8s.io/helm/pkg/repo"
)
const (
// HelmChartsDir is the relative directory within an SDK project where Helm
// charts are stored.
HelmChartsDir string = "helm-charts"
// DefaultAPIVersion is the Kubernetes CRD API Version used for fetched
// charts when the --api-version flag is not specified
DefaultAPIVersion string = "charts.helm.k8s.io/v1alpha1"
)
// CreateChartOptions is used to configure how a Helm chart is scaffolded
// for a new Helm operator project.
type CreateChartOptions struct {
// ResourceAPIVersion defines the Kubernetes GroupVersion to be associated
// with the created chart.
ResourceAPIVersion string
// ResourceKind defines the Kubernetes Kind to be associated with the
// created chart.
ResourceKind string
// Chart is a chart reference for a local or remote chart.
Chart string
// Repo is a URL to a custom chart repository.
Repo string
// Version is the version of the chart to fetch.
Version string
}
// CreateChart scaffolds a new helm chart for the project rooted in projectDir
// based on the passed opts.
//
// It returns a scaffold.Resource that can be used by the caller to create
// other related files. opts.ResourceAPIVersion and opts.ResourceKind are
// used to create the resource and must be specified if opts.Chart is empty.
//
// If opts.Chart is not empty, opts.ResourceAPIVersion and opts.Kind can be
// left unset: opts.ResourceAPIVersion defaults to "charts.helm.k8s.io/v1alpha1"
// and opts.ResourceKind is deduced from the specified opts.Chart.
//
// CreateChart also returns a chart.Chart that references the newly created
// chart.
//
// If opts.Chart is empty, CreateChart scaffolds the default chart from helm's
// default template.
//
// If opts.Chart is a local file, CreateChart verifies that it is a valid helm
// chart archive and unpacks it into the project's helm charts directory.
//
// If opts.Chart is a local directory, CreateChart verifies that it is a valid
// helm chart directory and copies it into the project's helm charts directory.
//
// For any other value of opts.Chart, CreateChart attempts to fetch the helm chart
// from a remote repository.
//
// If opts.Repo is not specified, the following chart reference formats are supported:
//
// - <repoName>/<chartName>: Fetch the helm chart named chartName from the helm
// chart repository named repoName, as specified in the
// $HELM_HOME/repositories/repositories.yaml file.
//
// - <url>: Fetch the helm chart archive at the specified URL.
//
// If opts.Repo is specified, only one chart reference format is supported:
//
// - <chartName>: Fetch the helm chart named chartName in the helm chart repository
// specified by opts.Repo
//
// If opts.Version is not set, CreateChart will fetch the latest available version of
// the helm chart. Otherwise, CreateChart will fetch the specified version.
// opts.Version is not used when opts.Chart itself refers to a specific version, for
// example when it is a local path or a URL.
//
// CreateChart returns an error if an error occurs creating the scaffold.Resource or
// creating the chart.
func CreateChart(projectDir string, opts CreateChartOptions) (*scaffold.Resource, *chart.Chart, error) {
chartsDir := filepath.Join(projectDir, HelmChartsDir)
err := os.MkdirAll(chartsDir, 0755)
if err != nil {
return nil, nil, fmt.Errorf("failed to create helm-charts directory: %s", err)
}
var (
r *scaffold.Resource
c *chart.Chart
)
// If we don't have a helm chart reference, scaffold the default chart
// from Helm's default template. Otherwise, fetch it.
if len(opts.Chart) == 0 {
r, c, err = scaffoldChart(chartsDir, opts.ResourceAPIVersion, opts.ResourceKind)
if err != nil {
return nil, nil, fmt.Errorf("failed to scaffold default chart: %s", err)
}
} else {
r, c, err = fetchChart(chartsDir, opts)
if err != nil {
return nil, nil, fmt.Errorf("failed to fetch chart: %s", err)
}
}
relChartPath := filepath.Join(HelmChartsDir, c.GetMetadata().GetName())
absChartPath := filepath.Join(projectDir, relChartPath)
if err := fetchChartDependencies(absChartPath); err != nil {
return nil, nil, fmt.Errorf("failed to fetch chart dependencies: %s", err)
}
// Reload chart in case dependencies changed
c, err = chartutil.Load(absChartPath)
if err != nil {
return nil, nil, fmt.Errorf("failed to load chart: %s", err)
}
log.Infof("Created %s", relChartPath)
return r, c, nil
}
func scaffoldChart(destDir, apiVersion, kind string) (*scaffold.Resource, *chart.Chart, error) {
r, err := scaffold.NewResource(apiVersion, kind)
if err != nil {
return nil, nil, err
}
chartfile := &chart.Metadata{
// Many helm charts use hyphenated names, but we chose not to because
// of the issues related to how hyphens are interpreted in templates.
// See https://github.com/helm/helm/issues/2192
Name: r.LowerKind,
Description: "A Helm chart for Kubernetes",
Version: "0.1.0",
AppVersion: "1.0",
ApiVersion: chartutil.ApiVersionV1,
}
chartPath, err := chartutil.Create(chartfile, destDir)
if err != nil {
return nil, nil, err
}
chart, err := chartutil.Load(chartPath)
if err != nil {
return nil, nil, err
}
return r, chart, nil
}
func fetchChart(destDir string, opts CreateChartOptions) (*scaffold.Resource, *chart.Chart, error) {
var (
stat os.FileInfo
chart *chart.Chart
err error
)
if stat, err = os.Stat(opts.Chart); err == nil {
chart, err = createChartFromDisk(destDir, opts.Chart, stat.IsDir())
} else {
chart, err = createChartFromRemote(destDir, opts)
}
if err != nil {
return nil, nil, err
}
chartName := chart.GetMetadata().GetName()
if len(opts.ResourceAPIVersion) == 0 {
opts.ResourceAPIVersion = DefaultAPIVersion
}
if len(opts.ResourceKind) == 0 {
opts.ResourceKind = strcase.ToCamel(chartName)
}
r, err := scaffold.NewResource(opts.ResourceAPIVersion, opts.ResourceKind)
if err != nil {
return nil, nil, err
}
return r, chart, nil
}
func createChartFromDisk(destDir, source string, isDir bool) (*chart.Chart, error) {
chart, err := chartutil.Load(source)
if err != nil {
return nil, err
}
// Save it into our project's helm-charts directory.
if err := chartutil.SaveDir(chart, destDir); err != nil {
return nil, err
}
return chart, nil
}
func createChartFromRemote(destDir string, opts CreateChartOptions) (*chart.Chart, error) {
helmHome, ok := os.LookupEnv(environment.HomeEnvVar)
if !ok {
helmHome = environment.DefaultHelmHome
}
getters := getter.All(environment.EnvSettings{})
c := downloader.ChartDownloader{
HelmHome: helmpath.Home(helmHome),
Out: os.Stderr,
Getters: getters,
}
if opts.Repo != "" {
chartURL, err := repo.FindChartInRepoURL(opts.Repo, opts.Chart, opts.Version, "", "", "", getters)
if err != nil {
return nil, err
}
opts.Chart = chartURL
}
tmpDir, err := ioutil.TempDir("", "osdk-helm-chart")
if err != nil {
return nil, err
}
defer func() {
if err := os.RemoveAll(tmpDir); err != nil {
log.Errorf("Failed to remove temporary directory %s: %s", tmpDir, err)
}
}()
chartArchive, _, err := c.DownloadTo(opts.Chart, opts.Version, tmpDir)
if err != nil {
// One of Helm's error messages directs users to run `helm init`, which
// installs tiller in a remote cluster. Since that's unnecessary and
// unhelpful, modify the error message to be relevant for operator-sdk.
if strings.Contains(err.Error(), "Couldn't load repositories file") {
return nil, fmt.Errorf("failed to load repositories file %s "+
"(you might need to run `helm init --client-only` "+
"to create and initialize it)", c.HelmHome.RepositoryFile())
}
return nil, err
}
return createChartFromDisk(destDir, chartArchive, false)
}
func fetchChartDependencies(chartPath string) error {
helmHome, ok := os.LookupEnv(environment.HomeEnvVar)
if !ok {
helmHome = environment.DefaultHelmHome
}
getters := getter.All(environment.EnvSettings{})
out := &bytes.Buffer{}
man := &downloader.Manager{
Out: out,
ChartPath: chartPath,
HelmHome: helmpath.Home(helmHome),
Getters: getters,
}
if err := man.Build(); err != nil {
fmt.Println(out.String())
return err
}
return nil
}