This repository has been archived by the owner on Sep 25, 2020. It is now read-only.
/
helm3.go
150 lines (129 loc) · 4.3 KB
/
helm3.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
/*
Copyright 2020 The Crossplane 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 helm3
import (
"bytes"
"fmt"
"io"
"github.com/pkg/errors"
"helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chart/loader"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/yaml"
"github.com/crossplane/crossplane-runtime/pkg/logging"
"github.com/crossplane/templating-controller/pkg/resource"
)
const (
defaultRootPath = "resources"
errSpecCast = "parent resource spec could not be casted into a map[string]interface{}"
errParse = "could not parse the generated YAMLs"
errHelm3Template = "helm3 template call failed"
)
// WithResourcePath returns an Option that changes the resource path of the Engine.
func WithResourcePath(path string) Option {
return func(e *Engine) {
e.ResourcePath = path
}
}
// WithLogger returns an Option that changes the logger of the Engine.
func WithLogger(l logging.Logger) Option {
return func(e *Engine) {
// NOTE(muvaf): Even though l.Debug seems to satisfy action.DebugLog interface,
// they are completely different given that former user the first argument
// as context while the latter uses it as format string.
e.debugLog = func(format string, v ...interface{}) {
l.Debug("Helm3", "debuglog", fmt.Sprintf(format, v...))
}
}
}
// NewHelm3Engine returns a new Helm3 Engine to be used as resource.TemplatingEngine.
func NewHelm3Engine(o ...Option) *Engine {
h := &Engine{
ResourcePath: defaultRootPath,
}
for _, f := range o {
f(h)
}
return h
}
// Engine is used to do the templating operation via Helm3.
type Engine struct {
// ResourcePath is the folder that the base resources reside in the
// filesystem. It should be given as absolute path.
ResourcePath string
// debugLog is used by helm library to debugLog the debugging level logs.
debugLog action.DebugLog
}
// Run returns the result of the templating operation.
func (e *Engine) Run(cr resource.ParentResource) ([]resource.ChildResource, error) {
values := map[string]interface{}{}
valuesMap, exists := cr.UnstructuredContent()["spec"]
if exists {
valuesCasted, ok := valuesMap.(map[string]interface{})
if !ok {
return nil, errors.New(errSpecCast)
}
values = valuesCasted
}
rawResult, err := e.template(cr.GetName(), values)
if err != nil {
return nil, errors.Wrap(err, errHelm3Template)
}
resources, err := parse([]byte(rawResult))
return resources, errors.Wrap(err, errParse)
}
func (e *Engine) template(releaseName string, values map[string]interface{}) (string, error) {
chart, err := loader.Load(e.ResourcePath)
if err != nil {
return "", err
}
config := action.Configuration{}
// NOTE(muvaf): RESTGetter is skipped because we don't need to talk with cluster.
// namespace is skipped because we use "memory" as storage rather than actual
// ConfigMap or Secret objects.
if err := config.Init(nil, "", "memory", e.debugLog); err != nil {
return "", err
}
i := action.NewInstall(&config)
i.ReleaseName = releaseName
// NOTE(muvaf): These settings are same with `helm template`'s call settings.
i.DryRun = true
i.Replace = true
i.ClientOnly = true
release, err := i.Run(chart, values)
if err != nil {
return "", err
}
return release.Manifest, nil
}
func parse(source []byte) ([]resource.ChildResource, error) {
dec := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(source), 4096)
var result []resource.ChildResource
for {
u := &unstructured.Unstructured{}
err := dec.Decode(u)
if err != nil && err != io.EOF {
return nil, errors.Wrap(err, errParse)
}
if err == io.EOF {
break
}
// Helm does not have any built-in validation like Kustomize, so, we
// have to do some basic sanity check to skip empty templates.
if u.GetName() == "" || u.GetAPIVersion() == "" || u.GetKind() == "" {
continue
}
result = append(result, u)
}
return result, nil
}