github.com/y-taka-23/helm@v2.8.0+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 "sort" 24 "strings" 25 "text/template" 26 27 "github.com/Masterminds/sprig" 28 29 "k8s.io/helm/pkg/chartutil" 30 "k8s.io/helm/pkg/proto/hapi/chart" 31 ) 32 33 // Engine is an implementation of 'cmd/tiller/environment'.Engine that uses Go templates. 34 type Engine struct { 35 // FuncMap contains the template functions that will be passed to each 36 // render call. This may only be modified before the first call to Render. 37 FuncMap template.FuncMap 38 // If strict is enabled, template rendering will fail if a template references 39 // a value that was not passed in. 40 Strict bool 41 CurrentTemplates map[string]renderable 42 } 43 44 // New creates a new Go template Engine instance. 45 // 46 // The FuncMap is initialized here. You may modify the FuncMap _prior to_ the 47 // first invocation of Render. 48 // 49 // The FuncMap sets all of the Sprig functions except for those that provide 50 // access to the underlying OS (env, expandenv). 51 func New() *Engine { 52 f := FuncMap() 53 return &Engine{ 54 FuncMap: f, 55 } 56 } 57 58 // FuncMap returns a mapping of all of the functions that Engine has. 59 // 60 // Because some functions are late-bound (e.g. contain context-sensitive 61 // data), the functions may not all perform identically outside of an 62 // Engine as they will inside of an Engine. 63 // 64 // Known late-bound functions: 65 // 66 // - "include": This is late-bound in Engine.Render(). The version 67 // included in the FuncMap is a placeholder. 68 // - "required": This is late-bound in Engine.Render(). The version 69 // included in the FuncMap is a placeholder. 70 // - "tpl": This is late-bound in Engine.Render(). The version 71 // included in the FuncMap is a placeholder. 72 func FuncMap() template.FuncMap { 73 f := sprig.TxtFuncMap() 74 delete(f, "env") 75 delete(f, "expandenv") 76 77 // Add some extra functionality 78 extra := template.FuncMap{ 79 "toToml": chartutil.ToToml, 80 "toYaml": chartutil.ToYaml, 81 "fromYaml": chartutil.FromYaml, 82 "toJson": chartutil.ToJson, 83 "fromJson": chartutil.FromJson, 84 85 // This is a placeholder for the "include" function, which is 86 // late-bound to a template. By declaring it here, we preserve the 87 // integrity of the linter. 88 "include": func(string, interface{}) string { return "not implemented" }, 89 "required": func(string, interface{}) interface{} { return "not implemented" }, 90 "tpl": func(string, interface{}) interface{} { return "not implemented" }, 91 } 92 93 for k, v := range extra { 94 f[k] = v 95 } 96 97 return f 98 } 99 100 // Render takes a chart, optional values, and value overrides, and attempts to render the Go templates. 101 // 102 // Render can be called repeatedly on the same engine. 103 // 104 // This will look in the chart's 'templates' data (e.g. the 'templates/' directory) 105 // and attempt to render the templates there using the values passed in. 106 // 107 // Values are scoped to their templates. A dependency template will not have 108 // access to the values set for its parent. If chart "foo" includes chart "bar", 109 // "bar" will not have access to the values for "foo". 110 // 111 // Values should be prepared with something like `chartutils.ReadValues`. 112 // 113 // Values are passed through the templates according to scope. If the top layer 114 // chart includes the chart foo, which includes the chart bar, the values map 115 // will be examined for a table called "foo". If "foo" is found in vals, 116 // that section of the values will be passed into the "foo" chart. And if that 117 // section contains a value named "bar", that value will be passed on to the 118 // bar chart during render time. 119 func (e *Engine) Render(chrt *chart.Chart, values chartutil.Values) (map[string]string, error) { 120 // Render the charts 121 tmap := allTemplates(chrt, values) 122 e.CurrentTemplates = tmap 123 return e.render(tmap) 124 } 125 126 // renderable is an object that can be rendered. 127 type renderable struct { 128 // tpl is the current template. 129 tpl string 130 // vals are the values to be supplied to the template. 131 vals chartutil.Values 132 // namespace prefix to the templates of the current chart 133 basePath string 134 } 135 136 // alterFuncMap takes the Engine's FuncMap and adds context-specific functions. 137 // 138 // The resulting FuncMap is only valid for the passed-in template. 139 func (e *Engine) alterFuncMap(t *template.Template) template.FuncMap { 140 // Clone the func map because we are adding context-specific functions. 141 var funcMap template.FuncMap = map[string]interface{}{} 142 for k, v := range e.FuncMap { 143 funcMap[k] = v 144 } 145 146 // Add the 'include' function here so we can close over t. 147 funcMap["include"] = func(name string, data interface{}) (string, error) { 148 buf := bytes.NewBuffer(nil) 149 if err := t.ExecuteTemplate(buf, name, data); err != nil { 150 return "", err 151 } 152 return buf.String(), nil 153 } 154 155 // Add the 'required' function here 156 funcMap["required"] = func(warn string, val interface{}) (interface{}, error) { 157 if val == nil { 158 return val, fmt.Errorf(warn) 159 } else if _, ok := val.(string); ok { 160 if val == "" { 161 return val, fmt.Errorf(warn) 162 } 163 } 164 return val, nil 165 } 166 167 // Add the 'tpl' function here 168 funcMap["tpl"] = func(tpl string, vals chartutil.Values) (string, error) { 169 basePath, err := vals.PathValue("Template.BasePath") 170 if err != nil { 171 return "", fmt.Errorf("Cannot retrieve Template.Basepath from values inside tpl function: %s (%s)", tpl, err.Error()) 172 } 173 174 r := renderable{ 175 tpl: tpl, 176 vals: vals, 177 basePath: basePath.(string), 178 } 179 180 templates := map[string]renderable{} 181 templateName, err := vals.PathValue("Template.Name") 182 if err != nil { 183 return "", fmt.Errorf("Cannot retrieve Template.Name from values inside tpl function: %s (%s)", tpl, err.Error()) 184 } 185 186 templates[templateName.(string)] = r 187 188 result, err := e.render(templates) 189 if err != nil { 190 return "", fmt.Errorf("Error during tpl function execution for %q: %s", tpl, err.Error()) 191 } 192 return result[templateName.(string)], nil 193 } 194 195 return funcMap 196 } 197 198 // render takes a map of templates/values and renders them. 199 func (e *Engine) render(tpls map[string]renderable) (map[string]string, error) { 200 // Basically, what we do here is start with an empty parent template and then 201 // build up a list of templates -- one for each file. Once all of the templates 202 // have been parsed, we loop through again and execute every template. 203 // 204 // The idea with this process is to make it possible for more complex templates 205 // to share common blocks, but to make the entire thing feel like a file-based 206 // template engine. 207 t := template.New("gotpl") 208 if e.Strict { 209 t.Option("missingkey=error") 210 } else { 211 // Not that zero will attempt to add default values for types it knows, 212 // but will still emit <no value> for others. We mitigate that later. 213 t.Option("missingkey=zero") 214 } 215 216 funcMap := e.alterFuncMap(t) 217 218 // We want to parse the templates in a predictable order. The order favors 219 // higher-level (in file system) templates over deeply nested templates. 220 keys := sortTemplates(tpls) 221 222 files := []string{} 223 224 for _, fname := range keys { 225 r := tpls[fname] 226 t = t.New(fname).Funcs(funcMap) 227 if _, err := t.Parse(r.tpl); err != nil { 228 return map[string]string{}, fmt.Errorf("parse error in %q: %s", fname, err) 229 } 230 files = append(files, fname) 231 } 232 233 // Adding the engine's currentTemplates to the template context 234 // so they can be referenced in the tpl function 235 for fname, r := range e.CurrentTemplates { 236 if t.Lookup(fname) == nil { 237 t = t.New(fname).Funcs(funcMap) 238 if _, err := t.Parse(r.tpl); err != nil { 239 return map[string]string{}, fmt.Errorf("parse error in %q: %s", fname, err) 240 } 241 } 242 } 243 244 rendered := make(map[string]string, len(files)) 245 var buf bytes.Buffer 246 for _, file := range files { 247 // Don't render partials. We don't care out the direct output of partials. 248 // They are only included from other templates. 249 if strings.HasPrefix(path.Base(file), "_") { 250 continue 251 } 252 // At render time, add information about the template that is being rendered. 253 vals := tpls[file].vals 254 vals["Template"] = map[string]interface{}{"Name": file, "BasePath": tpls[file].basePath} 255 if err := t.ExecuteTemplate(&buf, file, vals); err != nil { 256 return map[string]string{}, fmt.Errorf("render error in %q: %s", file, err) 257 } 258 259 // Work around the issue where Go will emit "<no value>" even if Options(missing=zero) 260 // is set. Since missing=error will never get here, we do not need to handle 261 // the Strict case. 262 rendered[file] = strings.Replace(buf.String(), "<no value>", "", -1) 263 buf.Reset() 264 } 265 266 return rendered, nil 267 } 268 269 func sortTemplates(tpls map[string]renderable) []string { 270 keys := make([]string, len(tpls)) 271 i := 0 272 for key := range tpls { 273 keys[i] = key 274 i++ 275 } 276 sort.Sort(sort.Reverse(byPathLen(keys))) 277 return keys 278 } 279 280 type byPathLen []string 281 282 func (p byPathLen) Len() int { return len(p) } 283 func (p byPathLen) Swap(i, j int) { p[j], p[i] = p[i], p[j] } 284 func (p byPathLen) Less(i, j int) bool { 285 a, b := p[i], p[j] 286 ca, cb := strings.Count(a, "/"), strings.Count(b, "/") 287 if ca == cb { 288 return strings.Compare(a, b) == -1 289 } 290 return ca < cb 291 } 292 293 // allTemplates returns all templates for a chart and its dependencies. 294 // 295 // As it goes, it also prepares the values in a scope-sensitive manner. 296 func allTemplates(c *chart.Chart, vals chartutil.Values) map[string]renderable { 297 templates := map[string]renderable{} 298 recAllTpls(c, templates, vals, true, "") 299 return templates 300 } 301 302 // recAllTpls recurses through the templates in a chart. 303 // 304 // As it recurses, it also sets the values to be appropriate for the template 305 // scope. 306 func recAllTpls(c *chart.Chart, templates map[string]renderable, parentVals chartutil.Values, top bool, parentID string) { 307 // This should never evaluate to a nil map. That will cause problems when 308 // values are appended later. 309 cvals := chartutil.Values{} 310 if top { 311 // If this is the top of the rendering tree, assume that parentVals 312 // is already resolved to the authoritative values. 313 cvals = parentVals 314 } else if c.Metadata != nil && c.Metadata.Name != "" { 315 // If there is a {{.Values.ThisChart}} in the parent metadata, 316 // copy that into the {{.Values}} for this template. 317 newVals := chartutil.Values{} 318 if vs, err := parentVals.Table("Values"); err == nil { 319 if tmp, err := vs.Table(c.Metadata.Name); err == nil { 320 newVals = tmp 321 } 322 } 323 324 cvals = map[string]interface{}{ 325 "Values": newVals, 326 "Release": parentVals["Release"], 327 "Chart": c.Metadata, 328 "Files": chartutil.NewFiles(c.Files), 329 "Capabilities": parentVals["Capabilities"], 330 } 331 } 332 333 newParentID := c.Metadata.Name 334 if parentID != "" { 335 // We artificially reconstruct the chart path to child templates. This 336 // creates a namespaced filename that can be used to track down the source 337 // of a particular template declaration. 338 newParentID = path.Join(parentID, "charts", newParentID) 339 } 340 341 for _, child := range c.Dependencies { 342 recAllTpls(child, templates, cvals, false, newParentID) 343 } 344 for _, t := range c.Templates { 345 templates[path.Join(newParentID, t.Name)] = renderable{ 346 tpl: string(t.Data), 347 vals: cvals, 348 basePath: path.Join(newParentID, "templates"), 349 } 350 } 351 }