github.com/zoumo/helm@v2.5.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  	// path is the path of chart
   131  	path string
   132  	// vals are the values to be supplied to the template.
   133  	vals chartutil.Values
   134  	// namespace prefix to the templates of the current chart
   135  	basePath string
   136  }
   137  
   138  // alterFuncMap takes the Engine's FuncMap and adds context-specific functions.
   139  //
   140  // The resulting FuncMap is only valid for the passed-in template.
   141  func (e *Engine) alterFuncMap(t *template.Template) template.FuncMap {
   142  	// Clone the func map because we are adding context-specific functions.
   143  	var funcMap template.FuncMap = map[string]interface{}{}
   144  	for k, v := range e.FuncMap {
   145  		funcMap[k] = v
   146  	}
   147  
   148  	// Add the 'include' function here so we can close over t.
   149  	funcMap["include"] = func(name string, data interface{}) (string, error) {
   150  		buf := bytes.NewBuffer(nil)
   151  		if err := t.ExecuteTemplate(buf, name, data); err != nil {
   152  			return "", err
   153  		}
   154  		return buf.String(), nil
   155  	}
   156  
   157  	// Add the 'required' function here
   158  	funcMap["required"] = func(warn string, val interface{}) (interface{}, error) {
   159  		if val == nil {
   160  			return val, fmt.Errorf(warn)
   161  		} else if _, ok := val.(string); ok {
   162  			if val == "" {
   163  				return val, fmt.Errorf(warn)
   164  			}
   165  		}
   166  		return val, nil
   167  	}
   168  
   169  	// Add the 'tpl' function here
   170  	funcMap["tpl"] = func(tpl string, vals chartutil.Values) (string, error) {
   171  		r := renderable{
   172  			tpl:  tpl,
   173  			vals: vals,
   174  		}
   175  
   176  		templates := map[string]renderable{}
   177  		templates["aaa_template"] = r
   178  
   179  		result, err := e.render(templates)
   180  		if err != nil {
   181  			return "", fmt.Errorf("Error during tpl function execution for %q: %s", tpl, err.Error())
   182  		}
   183  		return result["aaa_template"], nil
   184  	}
   185  
   186  	return funcMap
   187  }
   188  
   189  // render takes a map of templates/values and renders them.
   190  func (e *Engine) render(tpls map[string]renderable) (map[string]string, error) {
   191  	// Basically, what we do here is start with an empty parent template and then
   192  	// build up a list of templates -- one for each file. Once all of the templates
   193  	// have been parsed, we loop through again and execute every template.
   194  	//
   195  	// The idea with this process is to make it possible for more complex templates
   196  	// to share common blocks, but to make the entire thing feel like a file-based
   197  	// template engine.
   198  	t := template.New("gotpl")
   199  	if e.Strict {
   200  		t.Option("missingkey=error")
   201  	} else {
   202  		// Not that zero will attempt to add default values for types it knows,
   203  		// but will still emit <no value> for others. We mitigate that later.
   204  		t.Option("missingkey=zero")
   205  	}
   206  
   207  	funcMap := e.alterFuncMap(t)
   208  
   209  	// We want to parse the templates in a predictable order. The order favors
   210  	// higher-level (in file system) templates over deeply nested templates.
   211  	keys := sortTemplates(tpls)
   212  
   213  	files := []string{}
   214  
   215  	for _, fname := range keys {
   216  		r := tpls[fname]
   217  		t = t.New(fname).Funcs(funcMap)
   218  		if _, err := t.Parse(r.tpl); err != nil {
   219  			return map[string]string{}, fmt.Errorf("parse error in %q: %s", fname, err)
   220  		}
   221  		files = append(files, fname)
   222  	}
   223  
   224  	// Adding the engine's currentTemplates to the template context
   225  	// so they can be referenced in the tpl function
   226  	for fname, r := range e.CurrentTemplates {
   227  		if t.Lookup(fname) == nil {
   228  			t = t.New(fname).Funcs(funcMap)
   229  			if _, err := t.Parse(r.tpl); err != nil {
   230  				return map[string]string{}, fmt.Errorf("parse error in %q: %s", fname, err)
   231  			}
   232  		}
   233  	}
   234  
   235  	rendered := make(map[string]string, len(files))
   236  	var buf bytes.Buffer
   237  	for _, file := range files {
   238  		// Don't render partials. We don't care out the direct output of partials.
   239  		// They are only included from other templates.
   240  		if strings.HasPrefix(path.Base(file), "_") {
   241  			continue
   242  		}
   243  		// At render time, add information about the template that is being rendered.
   244  		tpl := tpls[file]
   245  		vals := tpl.vals
   246  		vals["Template"] = map[string]interface{}{"Name": file, "BasePath": tpls[file].basePath}
   247  		if err := t.ExecuteTemplate(&buf, file, vals); err != nil {
   248  			return map[string]string{}, fmt.Errorf("render error in %q: %s", file, err)
   249  		}
   250  
   251  		// Work around the issue where Go will emit "<no value>" even if Options(missing=zero)
   252  		// is set. Since missing=error will never get here, we do not need to handle
   253  		// the Strict case.
   254  		data := strings.Replace(buf.String(), "<no value>", "", -1)
   255  		data = pollute(data, &tpl)
   256  		rendered[file] = data
   257  		buf.Reset()
   258  	}
   259  
   260  	return rendered, nil
   261  }
   262  
   263  func sortTemplates(tpls map[string]renderable) []string {
   264  	keys := make([]string, len(tpls))
   265  	i := 0
   266  	for key := range tpls {
   267  		keys[i] = key
   268  		i++
   269  	}
   270  	sort.Sort(sort.Reverse(byPathLen(keys)))
   271  	return keys
   272  }
   273  
   274  type byPathLen []string
   275  
   276  func (p byPathLen) Len() int      { return len(p) }
   277  func (p byPathLen) Swap(i, j int) { p[j], p[i] = p[i], p[j] }
   278  func (p byPathLen) Less(i, j int) bool {
   279  	a, b := p[i], p[j]
   280  	ca, cb := strings.Count(a, "/"), strings.Count(b, "/")
   281  	if ca == cb {
   282  		return strings.Compare(a, b) == -1
   283  	}
   284  	return ca < cb
   285  }
   286  
   287  // allTemplates returns all templates for a chart and its dependencies.
   288  //
   289  // As it goes, it also prepares the values in a scope-sensitive manner.
   290  func allTemplates(c *chart.Chart, vals chartutil.Values) map[string]renderable {
   291  	templates := map[string]renderable{}
   292  	recAllTpls(c, templates, vals, true, "", "")
   293  	return templates
   294  }
   295  
   296  // recAllTpls recurses through the templates in a chart.
   297  //
   298  // As it recurses, it also sets the values to be appropriate for the template
   299  // scope.
   300  func recAllTpls(c *chart.Chart, templates map[string]renderable, parentVals chartutil.Values, top bool, parentPath string, parentID string) {
   301  	// This should never evaluate to a nil map. That will cause problems when
   302  	// values are appended later.
   303  	cvals := chartutil.Values{}
   304  	if top {
   305  		// If this is the top of the rendering tree, assume that parentVals
   306  		// is already resolved to the authoritative values.
   307  		cvals = parentVals
   308  	} else if c.Metadata != nil && c.Metadata.Name != "" {
   309  		// If there is a {{.Values.ThisChart}} in the parent metadata,
   310  		// copy that into the {{.Values}} for this template.
   311  		newVals := chartutil.Values{}
   312  		if vs, err := parentVals.Table("Values"); err == nil {
   313  			if tmp, err := vs.Table(c.Metadata.Name); err == nil {
   314  				newVals = tmp
   315  			}
   316  		}
   317  
   318  		cvals = map[string]interface{}{
   319  			"Values":       newVals,
   320  			"Release":      parentVals["Release"],
   321  			"Chart":        c.Metadata,
   322  			"Files":        chartutil.NewFiles(c.Files),
   323  			"Capabilities": parentVals["Capabilities"],
   324  		}
   325  	}
   326  
   327  	newParentID := c.Metadata.Name
   328  	parentPath = path.Join(parentPath, newParentID)
   329  	if parentID != "" {
   330  		// We artificially reconstruct the chart path to child templates. This
   331  		// creates a namespaced filename that can be used to track down the source
   332  		// of a particular template declaration.
   333  		newParentID = path.Join(parentID, "charts", newParentID)
   334  	}
   335  
   336  	for _, child := range c.Dependencies {
   337  		recAllTpls(child, templates, cvals, false, parentPath, newParentID)
   338  	}
   339  	for _, t := range c.Templates {
   340  		templates[path.Join(newParentID, t.Name)] = renderable{
   341  			tpl:      string(t.Data),
   342  			path:     parentPath,
   343  			vals:     cvals,
   344  			basePath: path.Join(newParentID, "templates"),
   345  		}
   346  	}
   347  }