github.com/felipejfc/helm@v2.1.2+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  
    75  		// This is a placeholder for the "include" function, which is
    76  		// late-bound to a template. By declaring it here, we preserve the
    77  		// integrity of the linter.
    78  		"include": func(string, interface{}) string { return "not implemented" },
    79  	}
    80  
    81  	for k, v := range extra {
    82  		f[k] = v
    83  	}
    84  
    85  	return f
    86  }
    87  
    88  // Render takes a chart, optional values, and value overrides, and attempts to render the Go templates.
    89  //
    90  // Render can be called repeatedly on the same engine.
    91  //
    92  // This will look in the chart's 'templates' data (e.g. the 'templates/' directory)
    93  // and attempt to render the templates there using the values passed in.
    94  //
    95  // Values are scoped to their templates. A dependency template will not have
    96  // access to the values set for its parent. If chart "foo" includes chart "bar",
    97  // "bar" will not have access to the values for "foo".
    98  //
    99  // Values should be prepared with something like `chartutils.ReadValues`.
   100  //
   101  // Values are passed through the templates according to scope. If the top layer
   102  // chart includes the chart foo, which includes the chart bar, the values map
   103  // will be examined for a table called "foo". If "foo" is found in vals,
   104  // that section of the values will be passed into the "foo" chart. And if that
   105  // section contains a value named "bar", that value will be passed on to the
   106  // bar chart during render time.
   107  func (e *Engine) Render(chrt *chart.Chart, values chartutil.Values) (map[string]string, error) {
   108  	// Render the charts
   109  	tmap := allTemplates(chrt, values)
   110  	return e.render(tmap)
   111  }
   112  
   113  // renderable is an object that can be rendered.
   114  type renderable struct {
   115  	// tpl is the current template.
   116  	tpl string
   117  	// vals are the values to be supplied to the template.
   118  	vals chartutil.Values
   119  }
   120  
   121  // alterFuncMap takes the Engine's FuncMap and adds context-specific functions.
   122  //
   123  // The resulting FuncMap is only valid for the passed-in template.
   124  func (e *Engine) alterFuncMap(t *template.Template) template.FuncMap {
   125  	// Clone the func map because we are adding context-specific functions.
   126  	var funcMap template.FuncMap = map[string]interface{}{}
   127  	for k, v := range e.FuncMap {
   128  		funcMap[k] = v
   129  	}
   130  
   131  	// Add the 'include' function here so we can close over t.
   132  	funcMap["include"] = func(name string, data interface{}) string {
   133  		buf := bytes.NewBuffer(nil)
   134  		if err := t.ExecuteTemplate(buf, name, data); err != nil {
   135  			buf.WriteString(err.Error())
   136  		}
   137  		return buf.String()
   138  	}
   139  
   140  	return funcMap
   141  }
   142  
   143  // render takes a map of templates/values and renders them.
   144  func (e *Engine) render(tpls map[string]renderable) (map[string]string, error) {
   145  	// Basically, what we do here is start with an empty parent template and then
   146  	// build up a list of templates -- one for each file. Once all of the templates
   147  	// have been parsed, we loop through again and execute every template.
   148  	//
   149  	// The idea with this process is to make it possible for more complex templates
   150  	// to share common blocks, but to make the entire thing feel like a file-based
   151  	// template engine.
   152  	t := template.New("gotpl")
   153  	if e.Strict {
   154  		t.Option("missingkey=error")
   155  	} else {
   156  		// Not that zero will attempt to add default values for types it knows,
   157  		// but will still emit <no value> for others. We mitigate that later.
   158  		t.Option("missingkey=zero")
   159  	}
   160  
   161  	funcMap := e.alterFuncMap(t)
   162  
   163  	files := []string{}
   164  	for fname, r := range tpls {
   165  		t = t.New(fname).Funcs(funcMap)
   166  		if _, err := t.Parse(r.tpl); err != nil {
   167  			return map[string]string{}, fmt.Errorf("parse error in %q: %s", fname, err)
   168  		}
   169  		files = append(files, fname)
   170  	}
   171  
   172  	rendered := make(map[string]string, len(files))
   173  	var buf bytes.Buffer
   174  	for _, file := range files {
   175  		// At render time, add information about the template that is being rendered.
   176  		vals := tpls[file].vals
   177  		vals["Template"] = map[string]interface{}{"Name": file}
   178  		if err := t.ExecuteTemplate(&buf, file, vals); err != nil {
   179  			return map[string]string{}, fmt.Errorf("render error in %q: %s", file, err)
   180  		}
   181  
   182  		// Work around the issue where Go will emit "<no value>" even if Options(missing=zero)
   183  		// is set. Since missing=error will never get here, we do not need to handle
   184  		// the Strict case.
   185  		rendered[file] = strings.Replace(buf.String(), "<no value>", "", -1)
   186  		buf.Reset()
   187  	}
   188  
   189  	return rendered, nil
   190  }
   191  
   192  // allTemplates returns all templates for a chart and its dependencies.
   193  //
   194  // As it goes, it also prepares the values in a scope-sensitive manner.
   195  func allTemplates(c *chart.Chart, vals chartutil.Values) map[string]renderable {
   196  	templates := map[string]renderable{}
   197  	recAllTpls(c, templates, vals, true, "")
   198  	return templates
   199  }
   200  
   201  // recAllTpls recurses through the templates in a chart.
   202  //
   203  // As it recurses, it also sets the values to be appropriate for the template
   204  // scope.
   205  func recAllTpls(c *chart.Chart, templates map[string]renderable, parentVals chartutil.Values, top bool, parentID string) {
   206  	// This should never evaluate to a nil map. That will cause problems when
   207  	// values are appended later.
   208  	cvals := chartutil.Values{}
   209  	if top {
   210  		// If this is the top of the rendering tree, assume that parentVals
   211  		// is already resolved to the authoritative values.
   212  		cvals = parentVals
   213  	} else if c.Metadata != nil && c.Metadata.Name != "" {
   214  		// If there is a {{.Values.ThisChart}} in the parent metadata,
   215  		// copy that into the {{.Values}} for this template.
   216  		newVals := chartutil.Values{}
   217  		if vs, err := parentVals.Table("Values"); err == nil {
   218  			if tmp, err := vs.Table(c.Metadata.Name); err == nil {
   219  				newVals = tmp
   220  			}
   221  		}
   222  
   223  		cvals = map[string]interface{}{
   224  			"Values":  newVals,
   225  			"Release": parentVals["Release"],
   226  			"Chart":   c.Metadata,
   227  			"Files":   chartutil.NewFiles(c.Files),
   228  		}
   229  	}
   230  
   231  	newParentID := c.Metadata.Name
   232  	if parentID != "" {
   233  		// We artificially reconstruct the chart path to child templates. This
   234  		// creates a namespaced filename that can be used to track down the source
   235  		// of a particular template declaration.
   236  		newParentID = path.Join(parentID, "charts", newParentID)
   237  	}
   238  
   239  	for _, child := range c.Dependencies {
   240  		recAllTpls(child, templates, cvals, false, newParentID)
   241  	}
   242  	for _, t := range c.Templates {
   243  		templates[path.Join(newParentID, t.Name)] = renderable{
   244  			tpl:  string(t.Data),
   245  			vals: cvals,
   246  		}
   247  	}
   248  }