Skip to content

Commit

Permalink
Update to func handling
Browse files Browse the repository at this point in the history
Signed-off-by: Matt Farina <matt@mattfarina.com>
  • Loading branch information
mattfarina committed Feb 3, 2023
1 parent 76157c6 commit 863bc74
Show file tree
Hide file tree
Showing 7 changed files with 78 additions and 10 deletions.
1 change: 1 addition & 0 deletions cmd/helm/install.go
Expand Up @@ -170,6 +170,7 @@ func addInstallFlags(cmd *cobra.Command, f *pflag.FlagSet, client *action.Instal
f.BoolVar(&client.Atomic, "atomic", false, "if set, the installation process deletes the installation on failure. The --wait flag will be set automatically if --atomic is used")
f.BoolVar(&client.SkipCRDs, "skip-crds", false, "if set, no CRDs will be installed. By default, CRDs are installed if not already present")
f.BoolVar(&client.SubNotes, "render-subchart-notes", false, "if set, render subchart notes along with the parent")
f.BoolVar(&client.EnableDNS, "enable-dns", false, "enable DNS lookups when rendering templates")
addValueOptionsFlags(f, valueOpts)
addChartPathOptionsFlags(f, &client.ChartPathOptions)

Expand Down
2 changes: 2 additions & 0 deletions cmd/helm/upgrade.go
Expand Up @@ -119,6 +119,7 @@ func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
instClient.SubNotes = client.SubNotes
instClient.Description = client.Description
instClient.DependencyUpdate = client.DependencyUpdate
instClient.EnableDNS = client.EnableDNS

rel, err := runInstall(args, instClient, valueOpts, out)
if err != nil {
Expand Down Expand Up @@ -232,6 +233,7 @@ func newUpgradeCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
f.BoolVar(&client.SubNotes, "render-subchart-notes", false, "if set, render subchart notes along with the parent")
f.StringVar(&client.Description, "description", "", "add a custom description")
f.BoolVar(&client.DependencyUpdate, "dependency-update", false, "update dependencies if they are missing before installing the chart")
f.BoolVar(&client.EnableDNS, "enable-dns", false, "enable DNS lookups when rendering templates")
addChartPathOptionsFlags(f, &client.ChartPathOptions)
addValueOptionsFlags(f, valueOpts)
bindOutputFlag(cmd, &outfmt)
Expand Down
13 changes: 9 additions & 4 deletions pkg/action/action.go
Expand Up @@ -101,8 +101,9 @@ type Configuration struct {
//
// TODO: This function is badly in need of a refactor.
// TODO: As part of the refactor the duplicate code in cmd/helm/template.go should be removed
// This code has to do with writing files to disk.
func (cfg *Configuration) renderResources(ch *chart.Chart, values chartutil.Values, releaseName, outputDir string, subNotes, useReleaseName, includeCrds bool, pr postrender.PostRenderer, dryRun bool) ([]*release.Hook, *bytes.Buffer, string, error) {
//
// This code has to do with writing files to disk.
func (cfg *Configuration) renderResources(ch *chart.Chart, values chartutil.Values, releaseName, outputDir string, subNotes, useReleaseName, includeCrds bool, pr postrender.PostRenderer, dryRun, enableDNS bool) ([]*release.Hook, *bytes.Buffer, string, error) {
hs := []*release.Hook{}
b := bytes.NewBuffer(nil)

Expand Down Expand Up @@ -130,9 +131,13 @@ func (cfg *Configuration) renderResources(ch *chart.Chart, values chartutil.Valu
if err != nil {
return hs, b, "", err
}
files, err2 = engine.RenderWithClient(ch, values, restConfig)
e := engine.New(restConfig)
e.EnableDNS = enableDNS
files, err2 = e.Render(ch, values)
} else {
files, err2 = engine.Render(ch, values)
var e engine.Engine
e.EnableDNS = enableDNS
files, err2 = e.Render(ch, values)
}

if err2 != nil {
Expand Down
12 changes: 7 additions & 5 deletions pkg/action/install.go
Expand Up @@ -97,6 +97,8 @@ type Install struct {
APIVersions chartutil.VersionSet
// Used by helm template to render charts with .Release.IsUpgrade. Ignored if Dry-Run is false
IsUpgrade bool
// Enable DNS lookups when rendering templates
EnableDNS bool
// Used by helm template to add the release as part of OutputDir path
// OutputDir/<ReleaseName>
UseReleaseName bool
Expand Down Expand Up @@ -257,7 +259,7 @@ func (i *Install) RunWithContext(ctx context.Context, chrt *chart.Chart, vals ma
rel := i.createRelease(chrt, vals)

var manifestDoc *bytes.Buffer
rel.Hooks, manifestDoc, rel.Info.Notes, err = i.cfg.renderResources(chrt, valuesToRender, i.ReleaseName, i.OutputDir, i.SubNotes, i.UseReleaseName, i.IncludeCRDs, i.PostRenderer, i.DryRun)
rel.Hooks, manifestDoc, rel.Info.Notes, err = i.cfg.renderResources(chrt, valuesToRender, i.ReleaseName, i.OutputDir, i.SubNotes, i.UseReleaseName, i.IncludeCRDs, i.PostRenderer, i.DryRun, i.EnableDNS)
// Even for errors, attach this if available
if manifestDoc != nil {
rel.Manifest = manifestDoc.String()
Expand Down Expand Up @@ -457,10 +459,10 @@ func (i *Install) failRelease(rel *release.Release, err error) (*release.Release
//
// Roughly, this will return an error if name is
//
// - empty
// - too long
// - already in use, and not deleted
// - used by a deleted release, and i.Replace is false
// - empty
// - too long
// - already in use, and not deleted
// - used by a deleted release, and i.Replace is false
func (i *Install) availableName() error {
start := i.ReleaseName

Expand Down
4 changes: 3 additions & 1 deletion pkg/action/upgrade.go
Expand Up @@ -103,6 +103,8 @@ type Upgrade struct {
DependencyUpdate bool
// Lock to control raceconditions when the process receives a SIGTERM
Lock sync.Mutex
// Enable DNS lookups when rendering templates
EnableDNS bool
}

type resultMessage struct {
Expand Down Expand Up @@ -231,7 +233,7 @@ func (u *Upgrade) prepareUpgrade(name string, chart *chart.Chart, vals map[strin
return nil, nil, err
}

hooks, manifestDoc, notesTxt, err := u.cfg.renderResources(chart, valuesToRender, "", "", u.SubNotes, false, false, u.PostRenderer, u.DryRun)
hooks, manifestDoc, notesTxt, err := u.cfg.renderResources(chart, valuesToRender, "", "", u.SubNotes, false, false, u.PostRenderer, u.DryRun, u.EnableDNS)
if err != nil {
return nil, nil, err
}
Expand Down
17 changes: 17 additions & 0 deletions pkg/engine/engine.go
Expand Up @@ -42,6 +42,15 @@ type Engine struct {
LintMode bool
// the rest config to connect to the kubernetes api
config *rest.Config
// EnableDNS tells the engine to allow DNS lookups when rendering templates
EnableDNS bool
}

// New creates a new instance of Engine using the passed in rest config.
func New(config *rest.Config) Engine {
return Engine{
config: config,
}
}

// Render takes a chart, optional values, and value overrides, and attempts to render the Go templates.
Expand Down Expand Up @@ -189,6 +198,14 @@ func (e Engine) initFunMap(t *template.Template, referenceTpls map[string]render
funcMap["lookup"] = NewLookupFunction(e.config)
}

// When DNS lookups are not enabled override the sprig function and return
// an empty string.
if !e.EnableDNS {
funcMap["getHostByName"] = func(name string) string {
return ""
}
}

t.Funcs(funcMap)
}

Expand Down
39 changes: 39 additions & 0 deletions pkg/engine/engine_test.go
Expand Up @@ -18,6 +18,7 @@ package engine

import (
"fmt"
"path"
"strings"
"sync"
"testing"
Expand Down Expand Up @@ -89,6 +90,7 @@ func TestRender(t *testing.T) {
{Name: "templates/test2", Data: []byte("{{.Values.global.callme | lower }}")},
{Name: "templates/test3", Data: []byte("{{.noValue}}")},
{Name: "templates/test4", Data: []byte("{{toJson .Values}}")},
{Name: "templates/test5", Data: []byte("{{getHostByName \"helm.sh\"}}")},
},
Values: map[string]interface{}{"outer": "DEFAULT", "inner": "DEFAULT"},
}
Expand Down Expand Up @@ -117,6 +119,7 @@ func TestRender(t *testing.T) {
"moby/templates/test2": "ishmael",
"moby/templates/test3": "",
"moby/templates/test4": `{"global":{"callme":"Ishmael"},"inner":"inn","outer":"spouter"}`,
"moby/templates/test5": "",
}

for name, data := range expect {
Expand Down Expand Up @@ -200,6 +203,42 @@ func TestRenderInternals(t *testing.T) {
}
}

func TestRenderWIthDNS(t *testing.T) {
c := &chart.Chart{
Metadata: &chart.Metadata{
Name: "moby",
Version: "1.2.3",
},
Templates: []*chart.File{
{Name: "templates/test1", Data: []byte("{{getHostByName \"helm.sh\"}}")},
},
Values: map[string]interface{}{},
}

vals := map[string]interface{}{
"Values": map[string]interface{}{},
}

v, err := chartutil.CoalesceValues(c, vals)
if err != nil {
t.Fatalf("Failed to coalesce values: %s", err)
}

var e Engine
e.EnableDNS = true
out, err := e.Render(c, v)
if err != nil {
t.Errorf("Failed to render templates: %s", err)
}

for _, val := range c.Templates {
fp := path.Join("moby", val.Name)
if out[fp] == "" {
t.Errorf("Expected IP address, got %q", out[fp])
}
}
}

func TestParallelRenderInternals(t *testing.T) {
// Make sure that we can use one Engine to run parallel template renders.
e := new(Engine)
Expand Down

0 comments on commit 863bc74

Please sign in to comment.