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