Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add constraints #77

Merged
merged 9 commits into from
Mar 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cmd/helmify/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ func ReadFlags() config.Config {
flag.BoolVar(&result.VeryVerbose, "vv", false, "Enable very verbose output. Same as verbose but with DEBUG. Example: helmify -vv")
flag.BoolVar(&crd, "crd-dir", false, "Enable crd install into 'crds' directory.\nWarning: CRDs placed in 'crds' directory will not be templated by Helm.\nSee https://helm.sh/docs/chart_best_practices/custom_resource_definitions/#some-caveats-and-explanations\nExample: helmify -crd-dir")
flag.BoolVar(&result.ImagePullSecrets, "image-pull-secrets", false, "Allows the user to use existing secrets as imagePullSecrets in values.yaml")
flag.BoolVar(&result.GenerateDefaults, "generate-defaults", false, "Allows the user to add empty placeholders for tipical customization options in values.yaml. Currently covers: topology constraints, node selectors, tolerances")

flag.Parse()
if h || help {
Expand Down
13 changes: 13 additions & 0 deletions examples/operator/templates/_helpers.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,16 @@ Create the name of the service account to use
{{- default "default" .Values.serviceAccount.name }}
{{- end }}
{{- end }}

{{/*
Renders a value that contains template.
Usage:
{{ include "tplvalues.render" ( dict "value" .Values.path.to.the.Value "context" $) }}
*/}}
{{- define "tplvalues.render" -}}
{{- if typeIs "string" .value }}
{{- tpl .value .context }}
{{- else }}
{{- tpl (.value | toYaml) .context }}
{{- end }}
{{- end -}}
9 changes: 8 additions & 1 deletion examples/operator/templates/deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,17 @@ spec:
runAsNonRoot: true
serviceAccountName: {{ include "operator.fullname" . }}-controller-manager
terminationGracePeriodSeconds: 10
topologySpreadConstraints:
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: DoNotSchedule
volumes:
- configMap:
name: {{ include "operator.fullname" . }}-manager-config
name: manager-config
- name: secret-volume
secret:
secretName: {{ include "operator.fullname" . }}-secret-ca
secretName: {{ include "operator.fullname" . }}-secret-ca
{{- if .Values.topologySpreadConstraints }}
topologySpreadConstraints: {{- include "tplvalues.render" (dict "value" .Values.topologySpreadConstraints "context" $) | nindent 8 }}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are 2 topologySpreadConstraints. Here and on line 107

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @RealAnna i had to revert constraints feature in this commit because of duplicates in specs. Commit also contains a template for nodeSelector which can be used as an example for other specs.

{{- end }}
4 changes: 4 additions & 0 deletions examples/operator/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ controllerManager:
cpu: 100m
memory: 20Mi
replicas: 1
topologySpreadConstraints:
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: DoNotSchedule
kubernetesClusterDomain: cluster.local
managerConfig:
controllerManagerConfigYaml:
Expand Down
3 changes: 3 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ type Config struct {
Crd bool
// ImagePullSecrets flag
ImagePullSecrets bool
// GenerateDefaults enables the generation of empty values placeholders for common customization options of helm chart
// current generated values: tolerances, node selectors, topology constraints
GenerateDefaults bool
}

func (c *Config) Validate() error {
Expand Down
13 changes: 13 additions & 0 deletions pkg/helm/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,19 @@ Create the name of the service account to use
{{- default "default" .Values.serviceAccount.name }}
{{- end }}
{{- end }}

{{/*
Renders a value that contains template.
Usage:
{{ include "tplvalues.render" ( dict "value" .Values.path.to.the.Value "context" $) }}
*/}}
{{- define "tplvalues.render" -}}
{{- if typeIs "string" .value }}
{{- tpl .value .context }}
{{- else }}
{{- tpl (.value | toYaml) .context }}
{{- end }}
{{- end -}}
`

const defaultChartfile = `apiVersion: v2
Expand Down
67 changes: 67 additions & 0 deletions pkg/processor/constraints/constraint.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package constraints

import (
"github.com/arttor/helmify/pkg/helmify"
yamlformat "github.com/arttor/helmify/pkg/yaml"
)

const tolerations = "tolerations"
const topology = "topologySpreadConstraints"
const nodeSelector = "nodeSelector"

const topologyExpression = "\n{{- if .Values.topologySpreadConstraints }}\n" +
" topologySpreadConstraints: {{- include \"tplvalues.render\" (dict \"value\" .Values.topologySpreadConstraints \"context\" $) | nindent 8 }}\n" +
"{{- end }}\n"

const nodeSelectorExpression = "{{- if .Values.nodeSelector }}\n" +
" nodeSelector: {{- include \"tplvalues.render\" ( dict \"value\" .Values.nodeSelector \"context\" $) | nindent 8 }}\n" +
"{{- end }}\n"

const tolerationsExpression = "{{- if .Values.tolerations }}\n" +
" tolerations: {{- include \"tplvalues.render\" (dict \"value\" .Values.tolerations \"context\" .) | nindent 8 }}\n" +
"{{- end }}\n"

// ProcessSpecMap adds 'topologyConstraints' to the podSpec in specMap, if it doesn't
// already has one defined.
func ProcessSpecMap(name string, specMap map[string]interface{}, values *helmify.Values, defaultEmpty bool) string {

spec, err := yamlformat.Marshal(specMap, 6)
if err != nil {
return ""
}

if defaultEmpty {
mapConstraintWithEmpty(name, specMap, topology, []interface{}{}, values)
mapConstraintWithEmpty(name, specMap, tolerations, []interface{}{}, values)
mapConstraintWithEmpty(name, specMap, nodeSelector, map[string]string{}, values)
return spec + topologyExpression + nodeSelectorExpression + tolerationsExpression
}

if specMap[topology] != nil {
(*values)[name].(map[string]interface{})[topology] = specMap[topology].(interface{})
delete(specMap, topology)
spec += topologyExpression
}

if specMap[tolerations] != nil {
(*values)[name].(map[string]interface{})[tolerations] = specMap[tolerations].(interface{})
delete(specMap, tolerations)
spec += tolerationsExpression
}
if specMap[nodeSelector] != nil {
(*values)[name].(map[string]interface{})[nodeSelector] = specMap[nodeSelector].(interface{})
delete(specMap, nodeSelector)
spec += nodeSelectorExpression
}

return spec
}

func mapConstraintWithEmpty(name string, specMap map[string]interface{}, constraint string, override interface{}, values *helmify.Values) {
if specMap[constraint] != nil {
(*values)[name].(map[string]interface{})[constraint] = specMap[constraint].(interface{})
} else {
(*values)[name].(map[string]interface{})[constraint] = override
arttor marked this conversation as resolved.
Show resolved Hide resolved
}
delete(specMap, constraint)
}
83 changes: 83 additions & 0 deletions pkg/processor/constraints/constraint_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package constraints

import (
"testing"

"github.com/arttor/helmify/pkg/helmify"
"github.com/stretchr/testify/require"
v1 "k8s.io/api/core/v1"
)

const templatedResult = "{{- if .Values.topologySpreadConstraints }}\n" +
" topologySpreadConstraints: {{- include \"tplvalues.render\" (dict \"value\" .Values.topologySpreadConstraints \"context\" $) | nindent 8 }}\n" +
"{{- end }}\n" +
"{{- if .Values.nodeSelector }}\n" +
" nodeSelector: {{- include \"tplvalues.render\" ( dict \"value\" .Values.nodeSelector \"context\" $) | nindent 8 }}\n" +
"{{- end }}\n" +
"{{- if .Values.tolerations }}\n" +
" tolerations: {{- include \"tplvalues.render\" (dict \"value\" .Values.tolerations \"context\" .) | nindent 8 }}\n" +
"{{- end }}\n"

func TestProcessSpecMap(t *testing.T) {

tests := []struct {
name string
specMap map[string]interface{}
values *helmify.Values
podspec v1.PodSpec
want string
wantValues *helmify.Values
}{
{name: "no predefined resource returns still a template and to fill in values",
specMap: make(map[string]interface{}, 4),
values: &helmify.Values{
"mydep": map[string]interface{}{},
},
want: templatedResult,
wantValues: &helmify.Values{
"mydep": map[string]interface{}{
"nodeSelector": map[string]string{},
"tolerations": []interface{}{},
"topologySpreadConstraints": []interface{}{},
},
},
},
{name: "predefined resource are added to values, template is the same",
values: &helmify.Values{
"mydep": map[string]interface{}{},
},
specMap: map[string]interface{}{

"topologySpreadConstraints": []v1.TopologySpreadConstraint{
{
MaxSkew: 0,
TopologyKey: "trtr",
WhenUnsatisfiable: "test",
LabelSelector: nil,
},
},
},
want: templatedResult,
wantValues: &helmify.Values{
"mydep": map[string]interface{}{
"nodeSelector": map[string]string{},
"tolerations": []interface{}{},
"topologySpreadConstraints": []v1.TopologySpreadConstraint{
{
MaxSkew: 0,
TopologyKey: "trtr",
WhenUnsatisfiable: "test",
},
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := ProcessSpecMap("mydep", tt.specMap, tt.values, true)
require.Contains(t, got, tt.want)
require.Equal(t, *tt.wantValues, *tt.values)
})
}
}
6 changes: 2 additions & 4 deletions pkg/processor/deployment/deployment.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

"github.com/arttor/helmify/pkg/cluster"
"github.com/arttor/helmify/pkg/processor"
"github.com/arttor/helmify/pkg/processor/constraints"
"github.com/arttor/helmify/pkg/processor/imagePullSecrets"

"github.com/arttor/helmify/pkg/helmify"
Expand Down Expand Up @@ -164,10 +165,7 @@ func (d deployment) Process(appMeta helmify.AppMetadata, obj *unstructured.Unstr
imagePullSecrets.ProcessSpecMap(specMap, &values)
}

spec, err := yamlformat.Marshal(specMap, 6)
if err != nil {
return true, nil, err
}
spec := constraints.ProcessSpecMap(nameCamel, specMap, &values, appMeta.Config().GenerateDefaults)
spec = strings.ReplaceAll(spec, "'", "")

return true, &result{
Expand Down
7 changes: 7 additions & 0 deletions test_data/k8s-operator-kustomize.output
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,13 @@ spec:
labels:
control-plane: controller-manager
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: DoNotSchedule
matchLabelKeys:
- app
- pod-template-hash
imagePullSecrets:
- name: my-operator-secret-registry-credentials
containers:
Expand Down