github.com/canthefason/helm@v2.2.1-0.20170221172616-16b043b8d505+incompatible/pkg/engine/engine.go (about) 1 /* 2 Copyright 2016 The Kubernetes Authors All rights reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package engine 18 19 import ( 20 "bytes" 21 "fmt" 22 "path" 23 "strings" 24 "text/template" 25 26 "github.com/Masterminds/sprig" 27 28 "k8s.io/helm/pkg/chartutil" 29 "k8s.io/helm/pkg/proto/hapi/chart" 30 ) 31 32 // Engine is an implementation of 'cmd/tiller/environment'.Engine that uses Go templates. 33 type Engine struct { 34 // FuncMap contains the template functions that will be passed to each 35 // render call. This may only be modified before the first call to Render. 36 FuncMap template.FuncMap 37 // If strict is enabled, template rendering will fail if a template references 38 // a value that was not passed in. 39 Strict bool 40 } 41 42 // New creates a new Go template Engine instance. 43 // 44 // The FuncMap is initialized here. You may modify the FuncMap _prior to_ the 45 // first invocation of Render. 46 // 47 // The FuncMap sets all of the Sprig functions except for those that provide 48 // access to the underlying OS (env, expandenv). 49 func New() *Engine { 50 f := FuncMap() 51 return &Engine{ 52 FuncMap: f, 53 } 54 } 55 56 // FuncMap returns a mapping of all of the functions that Engine has. 57 // 58 // Because some functions are late-bound (e.g. contain context-sensitive 59 // data), the functions may not all perform identically outside of an 60 // Engine as they will inside of an Engine. 61 // 62 // Known late-bound functions: 63 // 64 // - "include": This is late-bound in Engine.Render(). The version 65 // included in the FuncMap is a placeholder. 66 func FuncMap() template.FuncMap { 67 f := sprig.TxtFuncMap() 68 delete(f, "env") 69 delete(f, "expandenv") 70 71 // Add some extra functionality 72 extra := template.FuncMap{ 73 "toYaml": chartutil.ToYaml, 74 "fromYaml": chartutil.FromYaml, 75 76 // This is a placeholder for the "include" function, which is 77 // late-bound to a template. By declaring it here, we preserve the 78 // integrity of the linter. 79 "include": func(string, interface{}) string { return "not implemented" }, 80 } 81 82 for k, v := range extra { 83 f[k] = v 84 } 85 86 return f 87 } 88 89 // Render takes a chart, optional values, and value overrides, and attempts to render the Go templates. 90 // 91 // Render can be called repeatedly on the same engine. 92 // 93 // This will look in the chart's 'templates' data (e.g. the 'templates/' directory) 94 // and attempt to render the templates there using the values passed in. 95 // 96 // Values are scoped to their templates. A dependency template will not have 97 // access to the values set for its parent. If chart "foo" includes chart "bar", 98 // "bar" will not have access to the values for "foo". 99 // 100 // Values should be prepared with something like `chartutils.ReadValues`. 101 // 102 // Values are passed through the templates according to scope. If the top layer 103 // chart includes the chart foo, which includes the chart bar, the values map 104 // will be examined for a table called "foo". If "foo" is found in vals, 105 // that section of the values will be passed into the "foo" chart. And if that 106 // section contains a value named "bar", that value will be passed on to the 107 // bar chart during render time. 108 func (e *Engine) Render(chrt *chart.Chart, values chartutil.Values) (map[string]string, error) { 109 // Render the charts 110 tmap := allTemplates(chrt, values) 111 return e.render(tmap) 112 } 113 114 // renderable is an object that can be rendered. 115 type renderable struct { 116 // tpl is the current template. 117 tpl string 118 // vals are the values to be supplied to the template. 119 vals chartutil.Values 120 } 121 122 // alterFuncMap takes the Engine's FuncMap and adds context-specific functions. 123 // 124 // The resulting FuncMap is only valid for the passed-in template. 125 func (e *Engine) alterFuncMap(t *template.Template) template.FuncMap { 126 // Clone the func map because we are adding context-specific functions. 127 var funcMap template.FuncMap = map[string]interface{}{} 128 for k, v := range e.FuncMap { 129 funcMap[k] = v 130 } 131 132 // Add the 'include' function here so we can close over t. 133 funcMap["include"] = func(name string, data interface{}) string { 134 buf := bytes.NewBuffer(nil) 135 if err := t.ExecuteTemplate(buf, name, data); err != nil { 136 buf.WriteString(err.Error()) 137 } 138 return buf.String() 139 } 140 141 return funcMap 142 } 143 144 // render takes a map of templates/values and renders them. 145 func (e *Engine) render(tpls map[string]renderable) (map[string]string, error) { 146 // Basically, what we do here is start with an empty parent template and then 147 // build up a list of templates -- one for each file. Once all of the templates 148 // have been parsed, we loop through again and execute every template. 149 // 150 // The idea with this process is to make it possible for more complex templates 151 // to share common blocks, but to make the entire thing feel like a file-based 152 // template engine. 153 t := template.New("gotpl") 154 if e.Strict { 155 t.Option("missingkey=error") 156 } else { 157 // Not that zero will attempt to add default values for types it knows, 158 // but will still emit <no value> for others. We mitigate that later. 159 t.Option("missingkey=zero") 160 } 161 162 funcMap := e.alterFuncMap(t) 163 164 files := []string{} 165 for fname, r := range tpls { 166 t = t.New(fname).Funcs(funcMap) 167 if _, err := t.Parse(r.tpl); err != nil { 168 return map[string]string{}, fmt.Errorf("parse error in %q: %s", fname, err) 169 } 170 files = append(files, fname) 171 } 172 173 rendered := make(map[string]string, len(files)) 174 var buf bytes.Buffer 175 for _, file := range files { 176 // At render time, add information about the template that is being rendered. 177 vals := tpls[file].vals 178 vals["Template"] = map[string]interface{}{"Name": file} 179 if err := t.ExecuteTemplate(&buf, file, vals); err != nil { 180 return map[string]string{}, fmt.Errorf("render error in %q: %s", file, err) 181 } 182 183 // Work around the issue where Go will emit "<no value>" even if Options(missing=zero) 184 // is set. Since missing=error will never get here, we do not need to handle 185 // the Strict case. 186 rendered[file] = strings.Replace(buf.String(), "<no value>", "", -1) 187 buf.Reset() 188 } 189 190 return rendered, nil 191 } 192 193 // allTemplates returns all templates for a chart and its dependencies. 194 // 195 // As it goes, it also prepares the values in a scope-sensitive manner. 196 func allTemplates(c *chart.Chart, vals chartutil.Values) map[string]renderable { 197 templates := map[string]renderable{} 198 recAllTpls(c, templates, vals, true, "") 199 return templates 200 } 201 202 // recAllTpls recurses through the templates in a chart. 203 // 204 // As it recurses, it also sets the values to be appropriate for the template 205 // scope. 206 func recAllTpls(c *chart.Chart, templates map[string]renderable, parentVals chartutil.Values, top bool, parentID string) { 207 // This should never evaluate to a nil map. That will cause problems when 208 // values are appended later. 209 cvals := chartutil.Values{} 210 if top { 211 // If this is the top of the rendering tree, assume that parentVals 212 // is already resolved to the authoritative values. 213 cvals = parentVals 214 } else if c.Metadata != nil && c.Metadata.Name != "" { 215 // If there is a {{.Values.ThisChart}} in the parent metadata, 216 // copy that into the {{.Values}} for this template. 217 newVals := chartutil.Values{} 218 if vs, err := parentVals.Table("Values"); err == nil { 219 if tmp, err := vs.Table(c.Metadata.Name); err == nil { 220 newVals = tmp 221 } 222 } 223 224 cvals = map[string]interface{}{ 225 "Values": newVals, 226 "Release": parentVals["Release"], 227 "Chart": c.Metadata, 228 "Files": chartutil.NewFiles(c.Files), 229 "Capabilities": parentVals["Capabilities"], 230 } 231 } 232 233 newParentID := c.Metadata.Name 234 if parentID != "" { 235 // We artificially reconstruct the chart path to child templates. This 236 // creates a namespaced filename that can be used to track down the source 237 // of a particular template declaration. 238 newParentID = path.Join(parentID, "charts", newParentID) 239 } 240 241 for _, child := range c.Dependencies { 242 recAllTpls(child, templates, cvals, false, newParentID) 243 } 244 for _, t := range c.Templates { 245 templates[path.Join(newParentID, t.Name)] = renderable{ 246 tpl: string(t.Data), 247 vals: cvals, 248 } 249 } 250 }