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: support statefulSets #29

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ Usage:

## Status
Supported k8s resources:
- deployment
- deployment, statefulset
- service, Ingress
- PersistentVolumeClaim
- RBAC (serviceaccount, (cluster-)role, (cluster-)rolebinding)
Expand Down
2 changes: 2 additions & 0 deletions pkg/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/arttor/helmify/pkg/processor/configmap"
"github.com/arttor/helmify/pkg/processor/crd"
"github.com/arttor/helmify/pkg/processor/deployment"
"github.com/arttor/helmify/pkg/processor/statefulset"
"github.com/arttor/helmify/pkg/processor/rbac"
"github.com/arttor/helmify/pkg/processor/secret"
"github.com/arttor/helmify/pkg/processor/service"
Expand Down Expand Up @@ -45,6 +46,7 @@ func Start(input io.Reader, config config.Config) error {
configmap.New(),
crd.New(),
deployment.New(),
statefulset.New(),
storage.New(),
service.New(),
service.NewIngress(),
Expand Down
186 changes: 15 additions & 171 deletions pkg/processor/deployment/deployment.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,15 @@ package deployment
import (
"fmt"
"io"
"strings"
"text/template"

"github.com/arttor/helmify/pkg/helmify"
"github.com/arttor/helmify/pkg/processor"

"github.com/arttor/helmify/pkg/helmify"
yamlformat "github.com/arttor/helmify/pkg/yaml"
"github.com/iancoleman/strcase"
"github.com/pkg/errors"

appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
Expand Down Expand Up @@ -41,10 +39,6 @@ spec:
spec:
{{ .Spec }}`)

const selectorTempl = `%[1]s
{{- include "%[2]s.selectorLabels" . | nindent 6 }}
%[3]s`

// New creates processor for k8s Deployment resource.
func New() helmify.Processor {
return &deployment{}
Expand All @@ -57,107 +51,47 @@ func (d deployment) Process(appMeta helmify.AppMetadata, obj *unstructured.Unstr
if obj.GroupVersionKind() != deploymentGVC {
return false, nil, nil
}
depl := appsv1.Deployment{}
err := runtime.DefaultUnstructuredConverter.FromUnstructured(obj.Object, &depl)
typedObj := appsv1.Deployment{}
err := runtime.DefaultUnstructuredConverter.FromUnstructured(obj.Object, &typedObj)
if err != nil {
return true, nil, errors.Wrap(err, "unable to cast to deployment")
}
meta, err := processor.ProcessObjMeta(appMeta, obj)
if err != nil {
return true, nil, err
}

values := helmify.Values{}

name := appMeta.TrimName(obj.GetName())
replicas, err := processReplicas(name, &depl, &values)
if err != nil {
return true, nil, err
}

matchLabels, err := yamlformat.Marshal(map[string]interface{}{"matchLabels": depl.Spec.Selector.MatchLabels}, 0)
meta, err := processor.ProcessObjMeta(appMeta, obj)
if err != nil {
return true, nil, err
}
matchExpr := ""
if depl.Spec.Selector.MatchExpressions != nil {
matchExpr, err = yamlformat.Marshal(map[string]interface{}{"matchExpressions": depl.Spec.Selector.MatchExpressions}, 0)
if err != nil {
return true, nil, err
}
}
selector := fmt.Sprintf(selectorTempl, matchLabels, appMeta.ChartName(), matchExpr)
selector = strings.Trim(selector, " \n")
selector = string(yamlformat.Indent([]byte(selector), 4))

podLabels, err := yamlformat.Marshal(depl.Spec.Template.ObjectMeta.Labels, 8)
replicas, err := processor.ProcessReplicas(name, typedObj.Spec.Replicas, &values)
if err != nil {
return true, nil, err
}
podLabels += fmt.Sprintf("\n {{- include \"%s.selectorLabels\" . | nindent 8 }}", appMeta.ChartName())

podAnnotations := ""
if len(depl.Spec.Template.ObjectMeta.Annotations) != 0 {
podAnnotations, err = yamlformat.Marshal(map[string]interface{}{"annotations": depl.Spec.Template.ObjectMeta.Annotations}, 6)
if err != nil {
return true, nil, err
}

podAnnotations = "\n" + podAnnotations
}

nameCamel := strcase.ToLowerCamel(name)
podValues, err := processPodSpec(nameCamel, appMeta, &depl.Spec.Template.Spec)
if err != nil {
return true, nil, err
}
err = values.Merge(podValues)
selector, err := processor.ProcessSelector(appMeta, typedObj.Spec.Selector)
if err != nil {
return true, nil, err
}

// replace PVC to templated name
for i := 0; i < len(depl.Spec.Template.Spec.Volumes); i++ {
vol := depl.Spec.Template.Spec.Volumes[i]
if vol.PersistentVolumeClaim == nil {
continue
}
tempPVCName := appMeta.TemplatedName(vol.PersistentVolumeClaim.ClaimName)
depl.Spec.Template.Spec.Volumes[i].PersistentVolumeClaim.ClaimName = tempPVCName
pod := processor.Pod{
Name: strcase.ToLowerCamel(name),
AppMeta: appMeta,
Pod: &typedObj.Spec.Template,
}

// replace container resources with template to values.
specMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&depl.Spec.Template.Spec)
if err != nil {
return true, nil, err
}
containers, _, err := unstructured.NestedSlice(specMap, "containers")
podLabels, podAnnotations, err := pod.ProcessObjectMeta()
if err != nil {
return true, nil, err
}
for i := range containers {
containerName := strcase.ToLowerCamel((containers[i].(map[string]interface{})["name"]).(string))
res, exists, err := unstructured.NestedMap(values, nameCamel, containerName, "resources")
if err != nil {
return true, nil, err
}
if !exists || len(res) == 0 {
continue
}
err = unstructured.SetNestedField(containers[i].(map[string]interface{}), fmt.Sprintf(`{{- toYaml .Values.%s.%s.resources | nindent 10 }}`, nameCamel, containerName), "resources")
if err != nil {
return true, nil, err
}
}
err = unstructured.SetNestedSlice(specMap, containers, "containers")
if err != nil {
return true, nil, err
}
spec, err := yamlformat.Marshal(specMap, 6)
podLabels += fmt.Sprintf("\n {{- include \"%s.selectorLabels\" . | nindent 8 }}", appMeta.ChartName())

spec, err := pod.ProcessSpec(&values)
if err != nil {
return true, nil, err
}
spec = strings.ReplaceAll(spec, "'", "")

return true, &result{
values: values,
Expand All @@ -179,96 +113,6 @@ func (d deployment) Process(appMeta helmify.AppMetadata, obj *unstructured.Unstr
}, nil
}

func processReplicas(name string, deployment *appsv1.Deployment, values *helmify.Values) (string, error) {
if deployment.Spec.Replicas == nil {
return "", nil
}
replicasTpl, err := values.Add(int64(*deployment.Spec.Replicas), name, "replicas")
if err != nil {
return "", err
}
replicas, err := yamlformat.Marshal(map[string]interface{}{"replicas": replicasTpl}, 2)
if err != nil {
return "", err
}
replicas = strings.ReplaceAll(replicas, "'", "")
return replicas, nil
}

func processPodSpec(name string, appMeta helmify.AppMetadata, pod *corev1.PodSpec) (helmify.Values, error) {
values := helmify.Values{}
for i, c := range pod.Containers {
processed, err := processPodContainer(name, appMeta, c, &values)
if err != nil {
return nil, err
}
pod.Containers[i] = processed
}
for _, v := range pod.Volumes {
if v.ConfigMap != nil {
v.ConfigMap.Name = appMeta.TemplatedName(v.ConfigMap.Name)
}
if v.Secret != nil {
v.Secret.SecretName = appMeta.TemplatedName(v.Secret.SecretName)
}
}
pod.ServiceAccountName = appMeta.TemplatedName(pod.ServiceAccountName)

for i, s := range pod.ImagePullSecrets {
pod.ImagePullSecrets[i].Name = appMeta.TemplatedName(s.Name)
}

return values, nil
}

func processPodContainer(name string, appMeta helmify.AppMetadata, c corev1.Container, values *helmify.Values) (corev1.Container, error) {
index := strings.LastIndex(c.Image, ":")
if index < 0 {
return c, errors.New("wrong image format: " + c.Image)
}
repo, tag := c.Image[:index], c.Image[index+1:]
containerName := strcase.ToLowerCamel(c.Name)
c.Image = fmt.Sprintf("{{ .Values.%[1]s.%[2]s.image.repository }}:{{ .Values.%[1]s.%[2]s.image.tag | default .Chart.AppVersion }}", name, containerName)

err := unstructured.SetNestedField(*values, repo, name, containerName, "image", "repository")
if err != nil {
return c, errors.Wrap(err, "unable to set deployment value field")
}
err = unstructured.SetNestedField(*values, tag, name, containerName, "image", "tag")
if err != nil {
return c, errors.Wrap(err, "unable to set deployment value field")
}
for _, e := range c.Env {
if e.ValueFrom != nil && e.ValueFrom.SecretKeyRef != nil {
e.ValueFrom.SecretKeyRef.Name = appMeta.TemplatedName(e.ValueFrom.SecretKeyRef.Name)
}
if e.ValueFrom != nil && e.ValueFrom.ConfigMapKeyRef != nil {
e.ValueFrom.ConfigMapKeyRef.Name = appMeta.TemplatedName(e.ValueFrom.ConfigMapKeyRef.Name)
}
}
for _, e := range c.EnvFrom {
if e.SecretRef != nil {
e.SecretRef.Name = appMeta.TemplatedName(e.SecretRef.Name)
}
if e.ConfigMapRef != nil {
e.ConfigMapRef.Name = appMeta.TemplatedName(e.ConfigMapRef.Name)
}
}
for k, v := range c.Resources.Requests {
err = unstructured.SetNestedField(*values, v.ToUnstructured(), name, containerName, "resources", "requests", k.String())
if err != nil {
return c, errors.Wrap(err, "unable to set container resources value")
}
}
for k, v := range c.Resources.Limits {
err = unstructured.SetNestedField(*values, v.ToUnstructured(), name, containerName, "resources", "limits", k.String())
if err != nil {
return c, errors.Wrap(err, "unable to set container resources value")
}
}
return c, nil
}

type result struct {
data struct {
Meta string
Expand Down
Loading