Skip to content
parameters_helpers.go 5.81 KiB
Newer Older
Timothee Gosselin's avatar
Timothee Gosselin committed
/*

Licensed under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.gnu.org/licenses/agpl-3.0.html

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package parameters

import (
	"bytes"
Timothee Gosselin's avatar
Timothee Gosselin committed
	"sort"
	"text/template"

	"github.com/presslabs/controller-util/rand"
	corev1 "k8s.io/api/core/v1"
	"k8s.libre.sh/interfaces"
	"sigs.k8s.io/controller-runtime/pkg/client"
Timothee Gosselin's avatar
Timothee Gosselin committed
)

// InitRandValues initialies the parameters random values
func (p *Parameters) InitRandValues() {
	for _, param := range *p {
Timothee Gosselin's avatar
Timothee Gosselin committed
		if len(param.Key) > 0 && param.IsRand() && len(param.Value) == 0 {
Timothee Gosselin's avatar
Timothee Gosselin committed
			var size int
			switch param.Generate {
			case GenerateRand24:
				size = 24
				random, err := rand.AlphaNumericString(size)
				if err != nil {
				}
				param.Value = random

			case GenerateRand12:
				size = 12
				random, err := rand.AlphaNumericString(size)
				if err != nil {
				}
				param.Value = random
			}
		}
Timothee Gosselin's avatar
Timothee Gosselin committed
	}
}

// InitTemplateValues initialies the parameters values from a template and a key pair value set
// The template shoud be in the parameter value when GenerateTemplate is specified and the values
// will be replaced from the result of the template processing.
Timothee Gosselin's avatar
Timothee Gosselin committed
//func (p *Parameters) InitTemplateValues(values map[string]string) error {
func (p *Parameters) InitTemplateValues(values map[string]interface{}) error {
Timothee Gosselin's avatar
Timothee Gosselin committed

	for _, param := range *p {
		if param.Generate == GenerateTemplate {
			tmpl, err := template.New(param.Key).Parse(param.Value)

			if err != nil {
				return err
			}

			var tpl bytes.Buffer
			err = tmpl.Execute(&tpl, values)

			if err != nil {
				return err
			}

			param.Value = tpl.String()
		}
	}
	return nil
}

// GetData get the data for the secret or configmap as a key:values
// This function only returns data which should be either in a secret or a configmap
// It implements the configmap and secret interfaces
func (p *Parameters) GetData() map[string]string {
	data := make(map[string]string)

	for _, param := range *p {
Timothee Gosselin's avatar
Timothee Gosselin committed
		if param.IsMount() &&
Timothee Gosselin's avatar
Timothee Gosselin committed
			param.Type != ObjectFieldParameter &&
			len(param.Value) > 0 {
			data[param.Key] = param.Value
		}
	}

	return data
}

Timothee Gosselin's avatar
Timothee Gosselin committed
func (p *Parameters) GetConfigData() map[string]string {
	data := make(map[string]string)

	for _, param := range *p {
		if param.IsMount() &&
			param.Type == ConfigParameter &&
			len(param.Value) > 0 {
			data[param.Key] = param.Value
		}
	}

	return data
}

func (p *Parameters) GetSecretData() map[string][]byte {
	data := make(map[string][]byte)

	for _, param := range *p {
		if param.IsMount() &&
			// TODO TO FIX ?
			(param.Type == SecretParameter || param.Type == "") &&
			len(param.Value) > 0 {
			data[param.Key] = []byte(param.Value)
		}
	}

	return data
}

Timothee Gosselin's avatar
Timothee Gosselin committed
// GetEnvVar gets a list of environment variables to set in the container.
func (p *Parameters) GetEnvVar() []corev1.EnvVar {
	envVars := []corev1.EnvVar{}
	envVar := corev1.EnvVar{}

	var err error

	if p != nil {
		for _, param := range *p {
			envVar, err = param.GetEnvVar()
			// TODO TOFIX
			if err != nil {
			}
Timothee Gosselin's avatar
Timothee Gosselin committed

			if len(envVar.Name) > 0 {
				envVars = append(envVars, envVar)
			}
Timothee Gosselin's avatar
Timothee Gosselin committed
		}
	}

	if len(envVars) > 0 {
		// Sort var to avoid update of the object if var are not in the same order?
		sort.SliceStable(envVars, func(i, j int) bool {
			return envVars[i].Name < envVars[j].Name
		})

		return envVars
	}
	return nil
}

func (p *Parameters) GetVolumeMounts() []corev1.VolumeMount {
	volumeMounts := []corev1.VolumeMount{}

	if p != nil {
		for _, param := range *p {
			if param.MountType == MountFile {

				volumeMount := param.GetVolumeMount()

				if len(volumeMount.Name) > 0 {
					volumeMounts = append(volumeMounts, volumeMount)
				}
			}
		}
	}

	if len(volumeMounts) == 0 {
		return nil
	}

	return volumeMounts
}

func (p *Parameters) GetPodVolumes() []corev1.Volume {
	volumes := []corev1.Volume{}

	if p != nil {
		for _, param := range *p {
			if param.MountType == MountFile {
				volume := param.GetPodVolume()

				if len(volume.Name) > 0 {
					volumes = append(volumes, volume)
				}
			}
		}

	}

	if len(volumes) == 0 {
		return nil
	}


func (ps *Parameters) MergeData(data map[string]string) error {

	paramsByKey := ByKey(ps)

	if len(data) > 0 {
		if len(*ps) > 0 {
			for _, p := range *ps {
				if len(string(data[p.FromKey])) == 0 {
					return errors.New("parameter is not in resource data")
				}

				paramsByKey[p.Key].Value = string(data[p.FromKey])
				// TODO to fix, is it needed if data is generated only if value is empty ?
				// Reset default Generate
				paramsByKey[p.Key].Generate = ""
			}
		} else {
			for k, v := range data {
				*ps = append(*ps, &Parameter{
					Value: v,
					Key:   k,
				})
			}
		}
	}

	return nil

}

func (ps *Parameters) Merge(in *Parameters) error {

	inByKey := ByKey(in)
	destByKey := ByKey(ps)

	for k, p := range inByKey {
		if destByKey[k] != nil {
			p.DeepCopyInto(destByKey[k])
		} else {
			*ps = append(*ps, p)
		}
	}

	return nil
}

func (ps *Parameters) InitValueFrom(c client.Client, owner interfaces.Object) error {

	var obj interfaces.Object

	sorted := OrderByResourceRef(ps)

	for ptype, byRef := range sorted {
		switch ptype {
		case ConfigParameter:
			obj = &corev1.ConfigMap{}
		case SecretParameter:
			obj = &corev1.Secret{}
		default:
			return nil
		}

		for ref, params := range byRef {
			obj.SetName(ref)
			obj.SetNamespace(owner.GetNamespace())

			data, err := GetDataFromResource(c, obj, owner)
			if err != nil {
				return err
			}

			err = params.MergeData(data)
			if err != nil {
				return err
			}
		}
	}

	return nil
}