diff --git a/.gitignore b/.gitignore index d2c7bb2..5d8f05a 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,6 @@ docker-compose* .credentials release.id configs/ -cover.* +cover* .sq -katenary +./katenary diff --git a/cmd/katenary/main.go b/cmd/katenary/main.go index c1b4c5b..4f2baf6 100644 --- a/cmd/katenary/main.go +++ b/cmd/katenary/main.go @@ -178,7 +178,7 @@ func generateLabelHelpCommand() *cobra.Command { If no label is specified, the help for all labels is printed. If a label is specified, the help for this label is printed. -The name of the label must be specified without the prefix ` + generator.KATENARY_PREFIX + `. +The name of the label must be specified without the prefix ` + generator.Prefix() + `. e.g. kanetary help-labels diff --git a/doc/docs/index.md b/doc/docs/index.md index 00daa82..fc3c4c7 100644 --- a/doc/docs/index.md +++ b/doc/docs/index.md @@ -22,7 +22,7 @@ and let the magic happen. # What is it? -Katenary is a tool made to help you to transform "compose" files (`docker-compose.yml`, `podman-compose.yml`...) to +Katenary is a tool made to help you to transform "compose" files (`compose.yaml`, `docker-compose.yml`, `podman-compose.yml`...) to complete and production ready [Helm Chart](https://helm.sh). You'll be able to deploy your project in [:material-kubernetes: Kubernetes](https://kubernetes.io) in a few seconds @@ -30,7 +30,19 @@ You'll be able to deploy your project in [:material-kubernetes: Kubernetes](http It uses your current file and optionnaly labels to configure the result. -It's an opensource project, under MIT licence, partially developped at [Smile](https://www.smile.eu). The project source +It's an opensource project, under MIT licence, originally partially developped at [Smile](https://www.smile.eu). + +Today, it's partially developped in collaboration with [Klee Group](https://www.kleegroup.com). Note that Katenary is +and **will stay an opensource and free (as freedom) project**. We are convinced that the best way to make it better is to +share it with the community. + +
+![](./statics/klee.svg) +
+ +The main developer is [Patrice FERLET](https://github.com/metal3d). + +The project source code is hosted on the [:fontawesome-brands-github: Katenary GitHub Repository](https://github.com/metal3d/katenary). ## Install Katenary diff --git a/doc/docs/labels.md b/doc/docs/labels.md index 985ba09..3f13b63 100644 --- a/doc/docs/labels.md +++ b/doc/docs/labels.md @@ -7,22 +7,22 @@ Katenary will try to Unmarshal these labels. ## Label list and types -| Label name | Description | Type | -| ----------------------------- | ------------------------------------------------------ | --------------------- | +| Label name | Description | Type | +| ---------------------------- | ------------------------------------------------------ | --------------------- | | `katenary.v3/configmap-files` | Add files to the configmap. | list of strings | -| `katenary.v3/cronjob` | Create a cronjob from the service. | object | -| `katenary.v3/dependencies` | Add Helm dependencies to the service. | list of objects | -| `katenary.v3/description` | Description of the service | string | -| `katenary.v3/env-from` | Add environment variables from antoher service. | list of strings | -| `katenary.v3/health-check` | Health check to be added to the deployment. | object | -| `katenary.v3/ignore` | Ignore the service | bool | -| `katenary.v3/ingress` | Ingress rules to be added to the service. | object | -| `katenary.v3/main-app` | Mark the service as the main app. | bool | -| `katenary.v3/map-env` | Map env vars from the service to the deployment. | object | -| `katenary.v3/ports` | Ports to be added to the service. | list of uint32 | -| `katenary.v3/same-pod` | Move the same-pod deployment to the target deployment. | string | -| `katenary.v3/secrets` | Env vars to be set as secrets. | list of string | -| `katenary.v3/values` | Environment variables to be added to the values.yaml | list of string or map | +| `katenary.v3/cronjob` | Create a cronjob from the service. | object | +| `katenary.v3/dependencies` | Add Helm dependencies to the service. | list of objects | +| `katenary.v3/description` | Description of the service | string | +| `katenary.v3/env-from` | Add environment variables from antoher service. | list of strings | +| `katenary.v3/health-check` | Health check to be added to the deployment. | object | +| `katenary.v3/ignore` | Ignore the service | bool | +| `katenary.v3/ingress` | Ingress rules to be added to the service. | object | +| `katenary.v3/main-app` | Mark the service as the main app. | bool | +| `katenary.v3/map-env` | Map env vars from the service to the deployment. | object | +| `katenary.v3/ports` | Ports to be added to the service. | list of uint32 | +| `katenary.v3/same-pod` | Move the same-pod deployment to the target deployment. | string | +| `katenary.v3/secrets` | Env vars to be set as secrets. | list of string | +| `katenary.v3/values` | Environment variables to be added to the values.yaml | list of string or map | diff --git a/doc/docs/packages/generator.md b/doc/docs/packages/generator.md index 182d729..4cd0260 100644 --- a/doc/docs/packages/generator.md +++ b/doc/docs/packages/generator.md @@ -14,14 +14,6 @@ The generate.Convert\(\) create an HelmChart object and call "Generate\(\)" meth If you want to change or override the write behavior, you can use the HelmChart.Generate\(\) function and implement your own write function. This function returns the helm chart object containing all kubernetes objects and helm chart ingormation. It does not write the helm chart to the disk. -## Constants - - - -```go -const KATENARY_PREFIX = "katenary.v3/" -``` - ## Variables @@ -31,7 +23,7 @@ var ( // Standard annotationss Annotations = map[string]string{ - KATENARY_PREFIX + "version": Version, + labelName("version"): Version, } ) ``` @@ -52,7 +44,7 @@ func Convert(config ConvertOptions, dockerComposeFile ...string) Convert a compose \(docker, podman...\) project to a helm chart. It calls Generate\(\) to generate the chart and then write it to the disk. -## func [GetLabelHelp]() +## func [GetLabelHelp]() ```go func GetLabelHelp(asMarkdown bool) string @@ -61,7 +53,7 @@ func GetLabelHelp(asMarkdown bool) string Generate the help for the labels. -## func [GetLabelHelpFor]() +## func [GetLabelHelpFor]() ```go func GetLabelHelpFor(labelname string, asMarkdown bool) string @@ -70,7 +62,7 @@ func GetLabelHelpFor(labelname string, asMarkdown bool) string GetLabelHelpFor returns the help for a specific label. -## func [GetLabelNames]() +## func [GetLabelNames]() ```go func GetLabelNames() []string @@ -79,7 +71,7 @@ func GetLabelNames() []string GetLabelNames returns a sorted list of all katenary label names. -## func [GetLabels]() +## func [GetLabels]() ```go func GetLabels(serviceName, appName string) map[string]string @@ -88,7 +80,7 @@ func GetLabels(serviceName, appName string) map[string]string GetLabels returns the labels for a service. It uses the appName to replace the \_\_replace\_\_ in the labels. This is used to generate the labels in the templates. -## func [GetMatchLabels]() +## func [GetMatchLabels]() ```go func GetMatchLabels(serviceName, appName string) map[string]string @@ -114,6 +106,15 @@ func NewCronJob(service types.ServiceConfig, chart *HelmChart, appName string) ( NewCronJob creates a new CronJob from a compose service. The appName is the name of the application taken from the project name. + +## func [Prefix]() + +```go +func Prefix() string +``` + + + ## type [ChartTemplate]() @@ -274,7 +275,7 @@ Yaml returns the yaml representation of the cronjob. Implements the Yaml interface. -## type [CronJobValue]() +## type [CronJobValue]() CronJobValue is a cronjob configuration that will be saved in values.yaml. @@ -354,7 +355,7 @@ func (d *Deployment) AddContainer(service types.ServiceConfig) AddContainer adds a container to the deployment. -### func \(\*Deployment\) [AddHealthCheck]() +### func \(\*Deployment\) [AddHealthCheck]() ```go func (d *Deployment) AddHealthCheck(service types.ServiceConfig, container *corev1.Container) @@ -381,7 +382,7 @@ func (d *Deployment) AddVolumes(service types.ServiceConfig, appName string) AddVolumes adds a volume to the deployment. It does not create the PVC, it only adds the volumes to the deployment. If the volume is a bind volume it will warn the user that it is not supported yet. -### func \(\*Deployment\) [BindFrom]() +### func \(\*Deployment\) [BindFrom]() ```go func (d *Deployment) BindFrom(service types.ServiceConfig, binded *Deployment) @@ -399,7 +400,7 @@ func (d *Deployment) DependsOn(to *Deployment, servicename string) error DependsOn adds a initContainer to the deployment that will wait for the service to be up. -### func \(\*Deployment\) [Filename]() +### func \(\*Deployment\) [Filename]() ```go func (d *Deployment) Filename() string @@ -408,7 +409,7 @@ func (d *Deployment) Filename() string Filename returns the filename of the deployment. -### func \(\*Deployment\) [SetEnvFrom]() +### func \(\*Deployment\) [SetEnvFrom]() ```go func (d *Deployment) SetEnvFrom(service types.ServiceConfig, appName string) @@ -417,7 +418,7 @@ func (d *Deployment) SetEnvFrom(service types.ServiceConfig, appName string) SetEnvFrom sets the environment variables to a configmap. The configmap is created. -### func \(\*Deployment\) [Yaml]() +### func \(\*Deployment\) [Yaml]() ```go func (d *Deployment) Yaml() ([]byte, error) @@ -529,7 +530,7 @@ func NewIngress(service types.ServiceConfig, Chart *HelmChart) *Ingress NewIngress creates a new Ingress from a compose service. -### func \(\*Ingress\) [Filename]() +### func \(\*Ingress\) [Filename]() ```go func (ingress *Ingress) Filename() string @@ -538,7 +539,7 @@ func (ingress *Ingress) Filename() string -### func \(\*Ingress\) [Yaml]() +### func \(\*Ingress\) [Yaml]() ```go func (ingress *Ingress) Yaml() ([]byte, error) @@ -570,42 +571,24 @@ Label is a katenary label to find in compose files. type Label = string ``` -Known labels. +Known labels. ```go const ( - LABEL_MAIN_APP Label = KATENARY_PREFIX + "main-app" - LABEL_VALUES Label = KATENARY_PREFIX + "values" - LABEL_SECRETS Label = KATENARY_PREFIX + "secrets" - LABEL_PORTS Label = KATENARY_PREFIX + "ports" - LABEL_INGRESS Label = KATENARY_PREFIX + "ingress" - LABEL_MAP_ENV Label = KATENARY_PREFIX + "map-env" - LABEL_HEALTHCHECK Label = KATENARY_PREFIX + "health-check" - LABEL_SAME_POD Label = KATENARY_PREFIX + "same-pod" - LABEL_DESCRIPTION Label = KATENARY_PREFIX + "description" - LABEL_IGNORE Label = KATENARY_PREFIX + "ignore" - LABEL_DEPENDENCIES Label = KATENARY_PREFIX + "dependencies" - LABEL_CM_FILES Label = KATENARY_PREFIX + "configmap-files" - LABEL_CRONJOB Label = KATENARY_PREFIX + "cronjob" - LABEL_ENV_FROM Label = KATENARY_PREFIX + "env-from" -) -``` - - -## type [LabelType]() - -LabelType identifies the type of label to generate in objects. TODO: is this still needed? - -```go -type LabelType uint8 -``` - - - -```go -const ( - DeploymentLabel LabelType = iota - ServiceLabel + LabelMainApp Label = katenaryLabelPrefix + "/main-app" + LabelValues Label = katenaryLabelPrefix + "/values" + LabelSecrets Label = katenaryLabelPrefix + "/secrets" + LabelPorts Label = katenaryLabelPrefix + "/ports" + LabelIngress Label = katenaryLabelPrefix + "/ingress" + LabelMapEnv Label = katenaryLabelPrefix + "/map-env" + LabelHealthCheck Label = katenaryLabelPrefix + "/health-check" + LabelSamePod Label = katenaryLabelPrefix + "/same-pod" + LabelDescription Label = katenaryLabelPrefix + "/description" + LabelIgnore Label = katenaryLabelPrefix + "/ignore" + LabelDependencies Label = katenaryLabelPrefix + "/dependencies" + LabelConfigMapFiles Label = katenaryLabelPrefix + "/configmap-files" + LabelCronJob Label = katenaryLabelPrefix + "/cronjob" + LabelEnvFrom Label = katenaryLabelPrefix + "/env-from" ) ``` @@ -855,26 +838,9 @@ func (r *ServiceAccount) Yaml() ([]byte, error) -## type [Value]() +## type [Value]() -Value will be saved in values.yaml. It contains configuraiton for all deployment and services. The content will be lile: - -``` -name_of_component: - repository: - image: image_name - tag: image_tag - persistence: - enabled: true - storageClass: storage_class_name - ingress: - enabled: true - host: host_name - path: path_name - environment: - ENV_VAR_1: value_1 - ENV_VAR_2: value_2 -``` +Value will be saved in values.yaml. It contains configuraiton for all deployment and services. ```go type Value struct { @@ -892,7 +858,7 @@ type Value struct { ``` -### func [NewValue]() +### func [NewValue]() ```go func NewValue(service types.ServiceConfig, main ...bool) *Value @@ -903,7 +869,7 @@ NewValue creates a new Value from a compose service. The value contains the nece If \`main\` is true, the tag will be empty because it will be set in the helm chart appVersion. -### func \(\*Value\) [AddIngress]() +### func \(\*Value\) [AddIngress]() ```go func (v *Value) AddIngress(host, path string) @@ -912,7 +878,7 @@ func (v *Value) AddIngress(host, path string) -### func \(\*Value\) [AddPersistence]() +### func \(\*Value\) [AddPersistence]() ```go func (v *Value) AddPersistence(volumeName string) diff --git a/generator/configMap.go b/generator/configMap.go index 73ff639..1c08ddf 100644 --- a/generator/configMap.go +++ b/generator/configMap.go @@ -76,7 +76,7 @@ func NewConfigMap(service types.ServiceConfig, appName string) *ConfigMap { } // get the secrets from the labels - if v, ok := service.Labels[LABEL_SECRETS]; ok { + if v, ok := service.Labels[LabelSecrets]; ok { err := yaml.Unmarshal([]byte(v), &secrets) if err != nil { log.Fatal(err) @@ -87,7 +87,7 @@ func NewConfigMap(service types.ServiceConfig, appName string) *ConfigMap { } } // get the label values from the labels - varDescriptons := utils.GetValuesFromLabel(service, LABEL_VALUES) + varDescriptons := utils.GetValuesFromLabel(service, LabelValues) for value := range varDescriptons { labelValues = append(labelValues, value) } @@ -104,7 +104,7 @@ func NewConfigMap(service types.ServiceConfig, appName string) *ConfigMap { } // remove the variables that are already defined in the environment - if l, ok := service.Labels[LABEL_MAP_ENV]; ok { + if l, ok := service.Labels[LabelMapEnv]; ok { envmap := make(map[string]string) if err := goyaml.Unmarshal([]byte(l), &envmap); err != nil { log.Fatal("Error parsing map-env", err) diff --git a/generator/converter.go b/generator/converter.go index bec529f..00b887b 100644 --- a/generator/converter.go +++ b/generator/converter.go @@ -339,7 +339,7 @@ func addModeline(values []byte) []byte { // of the service definition. func addDescriptions(values []byte, project types.Project) []byte { for _, service := range project.Services { - if description, ok := service.Labels[LABEL_DESCRIPTION]; ok { + if description, ok := service.Labels[LabelDescription]; ok { // set it as comment description = "\n# " + strings.ReplaceAll(description, "\n", "\n# ") @@ -500,7 +500,7 @@ func addVariablesDoc(values []byte, project *types.Project) []byte { currentService := "" for _, service := range project.Services { - variables := utils.GetValuesFromLabel(service, LABEL_VALUES) + variables := utils.GetValuesFromLabel(service, LabelValues) for i, line := range lines { if regexp.MustCompile(`(?m)^` + service.Name + `:`).MatchString(line) { currentService = service.Name @@ -535,7 +535,7 @@ func addMainTagAppDoc(values []byte, project *types.Project) []byte { inService := false inRegistry := false // read the label LabelMainApp - if v, ok := service.Labels[LABEL_MAIN_APP]; !ok { + if v, ok := service.Labels[LabelMainApp]; !ok { continue } else if v == "false" || v == "no" || v == "0" { continue @@ -609,7 +609,7 @@ func checkOldLabels(project *types.Project) error { badServices := make([]string, 0) for _, service := range project.Services { for label := range service.Labels { - if strings.Contains(label, "katenary.") && !strings.Contains(label, KATENARY_PREFIX) { + if strings.Contains(label, "katenary.") && !strings.Contains(label, katenaryLabelPrefix) { badServices = append(badServices, fmt.Sprintf("- %s: %s", service.Name, label)) } } @@ -625,7 +625,7 @@ func checkOldLabels(project *types.Project) error { Services to upgrade: %s`, project.Name, - KATENARY_PREFIX[0:len(KATENARY_PREFIX)-1], + katenaryLabelPrefix[0:len(katenaryLabelPrefix)-1], strings.Join(badServices, "\n"), ) diff --git a/generator/cronJob.go b/generator/cronJob.go index 488ffd2..c0f6f3d 100644 --- a/generator/cronJob.go +++ b/generator/cronJob.go @@ -27,7 +27,7 @@ type CronJob struct { // NewCronJob creates a new CronJob from a compose service. The appName is the name of the application taken from the project name. func NewCronJob(service types.ServiceConfig, chart *HelmChart, appName string) (*CronJob, *RBAC) { - labels, ok := service.Labels[LABEL_CRONJOB] + labels, ok := service.Labels[LabelCronJob] if !ok { return nil, nil } diff --git a/generator/deployment.go b/generator/deployment.go index 8129e41..336a16a 100644 --- a/generator/deployment.go +++ b/generator/deployment.go @@ -44,7 +44,7 @@ type Deployment struct { // It also creates the Values map that will be used to create the values.yaml file. func NewDeployment(service types.ServiceConfig, chart *HelmChart) *Deployment { isMainApp := false - if mainLabel, ok := service.Labels[LABEL_MAIN_APP]; ok { + if mainLabel, ok := service.Labels[LabelMainApp]; ok { main := strings.ToLower(mainLabel) isMainApp = main == "true" || main == "yes" || main == "1" } @@ -83,7 +83,7 @@ func NewDeployment(service types.ServiceConfig, chart *HelmChart) *Deployment { }, Spec: corev1.PodSpec{ NodeSelector: map[string]string{ - "katenary.v3/node-selector": "replace", + labelName("node-selector"): "replace", }, }, }, @@ -112,7 +112,7 @@ func (d *Deployment) DependsOn(to *Deployment, servicename string) error { for _, container := range to.Spec.Template.Spec.Containers { commands := []string{} if len(container.Ports) == 0 { - utils.Warn("No ports found for service ", servicename, ". You should declare a port in the service or use "+LABEL_PORTS+" label.") + utils.Warn("No ports found for service ", servicename, ". You should declare a port in the service or use "+LabelPorts+" label.") os.Exit(1) } for _, port := range container.Ports { @@ -186,7 +186,7 @@ func (d *Deployment) AddIngress(service types.ServiceConfig, appName string) *In // If the volume is a bind volume it will warn the user that it is not supported yet. func (d *Deployment) AddVolumes(service types.ServiceConfig, appName string) { tobind := map[string]bool{} - if v, ok := service.Labels[LABEL_CM_FILES]; ok { + if v, ok := service.Labels[LabelConfigMapFiles]; ok { binds := []string{} if err := yaml.Unmarshal([]byte(v), &binds); err != nil { log.Fatal(err) @@ -197,7 +197,7 @@ func (d *Deployment) AddVolumes(service types.ServiceConfig, appName string) { } isSamePod := false - if v, ok := service.Labels[LABEL_SAME_POD]; !ok { + if v, ok := service.Labels[LabelSamePod]; !ok { isSamePod = false } else { isSamePod = v != "" @@ -214,7 +214,7 @@ func (d *Deployment) AddVolumes(service types.ServiceConfig, appName string) { utils.Warn( "Bind volumes are not supported yet, " + "excepting for those declared as " + - LABEL_CM_FILES + + LabelConfigMapFiles + ", skipping volume " + volume.Source + " from service " + service.Name, ) @@ -242,7 +242,7 @@ func (d *Deployment) AddVolumes(service types.ServiceConfig, appName string) { }) // Add volume to values.yaml only if it the service is not in the same pod that another service. // If it is in the same pod, the volume will be added to the other service later - if _, ok := service.Labels[LABEL_SAME_POD]; !ok { + if _, ok := service.Labels[LabelSamePod]; !ok { d.chart.Values[service.Name].(*Value).AddPersistence(volume.Source) } // Add volume to deployment @@ -354,7 +354,7 @@ func (d *Deployment) SetEnvFrom(service types.ServiceConfig, appName string) { // secrets from label labelSecrets := []string{} - if v, ok := service.Labels[LABEL_SECRETS]; ok { + if v, ok := service.Labels[LabelSecrets]; ok { err := yaml.Unmarshal([]byte(v), &labelSecrets) if err != nil { log.Fatal(err) @@ -362,7 +362,7 @@ func (d *Deployment) SetEnvFrom(service types.ServiceConfig, appName string) { } // values from label - varDescriptons := utils.GetValuesFromLabel(service, LABEL_VALUES) + varDescriptons := utils.GetValuesFromLabel(service, LabelValues) labelValues := []string{} for v := range varDescriptons { labelValues = append(labelValues, v) @@ -441,7 +441,7 @@ func (d *Deployment) SetEnvFrom(service types.ServiceConfig, appName string) { func (d *Deployment) AddHealthCheck(service types.ServiceConfig, container *corev1.Container) { // get the label for healthcheck - if v, ok := service.Labels[LABEL_HEALTHCHECK]; ok { + if v, ok := service.Labels[LabelHealthCheck]; ok { probes := struct { LivenessProbe *corev1.Probe `yaml:"livenessProbe"` ReadinessProbe *corev1.Probe `yaml:"readinessProbe"` @@ -576,7 +576,6 @@ func (d *Deployment) Yaml() ([]byte, error) { post := spaces + "{{- end }}" ns := spaces + "nodeSelector:\n" ns += spaces + ` {{- .Values.` + serviceName + `.nodeSelector | toYaml | nindent __indent__ }}` - //line = strings.Replace(line, "katenary.v3/node-selector: replace", ns, 1) line = pre + "\n" + ns + "\n" + post } // manage replicas @@ -608,7 +607,7 @@ func (d *Deployment) Yaml() ([]byte, error) { // find the katenary.v3/node-selector line, and remove it for i, line := range content { - if strings.Contains(line, "katenary.v3/node-selector") { + if strings.Contains(line, labelName("node-selector")) { content = append(content[:i], content[i+1:]...) continue } diff --git a/generator/generator.go b/generator/generator.go index f08e237..892565a 100644 --- a/generator/generator.go +++ b/generator/generator.go @@ -45,7 +45,7 @@ func Generate(project *types.Project) (*HelmChart, error) { if err != nil { return nil, err } - Annotations[KATENARY_PREFIX+"compose-hash"] = hash + Annotations[labelName("compose-hash")] = hash chart.composeHash = &hash // find the "main-app" label, and set chart.AppVersion to the tag if exists @@ -92,7 +92,7 @@ func Generate(project *types.Project) (*HelmChart, error) { // get the same-pod label if exists, add it to the list. // We later will copy some parts to the target deployment and remove this one. - if samePod, ok := service.Labels[LABEL_SAME_POD]; ok && samePod != "" { + if samePod, ok := service.Labels[LabelSamePod]; ok && samePod != "" { podToMerge[samePod] = &service } @@ -127,14 +127,14 @@ func Generate(project *types.Project) (*HelmChart, error) { // drop all "same-pod" deployments because the containers and volumes are already // in the target deployment for _, service := range podToMerge { - if samepod, ok := service.Labels[LABEL_SAME_POD]; ok && samepod != "" { + if samepod, ok := service.Labels[LabelSamePod]; ok && samepod != "" { // move this deployment volumes to the target deployment if target, ok := deployments[samepod]; ok { target.AddContainer(*service) target.BindFrom(*service, deployments[service.Name]) delete(deployments, service.Name) } else { - log.Printf("service %[1]s is declared as %[2]s, but %[2]s is not defined", service.Name, LABEL_SAME_POD) + log.Printf("service %[1]s is declared as %[2]s, but %[2]s is not defined", service.Name, LabelSamePod) } } } @@ -252,7 +252,7 @@ func removeReplaceString(b []byte) []byte { // serviceIsMain returns true if the service is the main app. func serviceIsMain(service types.ServiceConfig) bool { - if main, ok := service.Labels[LABEL_MAIN_APP]; ok { + if main, ok := service.Labels[LabelMainApp]; ok { return main == "true" || main == "yes" || main == "1" } return false @@ -274,7 +274,7 @@ func setChartVersion(chart *HelmChart, service types.ServiceConfig) { // fixPorts checks the "ports" label from container and add it to the service. func fixPorts(service *types.ServiceConfig) error { // check the "ports" label from container and add it to the service - if portsLabel, ok := service.Labels[LABEL_PORTS]; ok { + if portsLabel, ok := service.Labels[LabelPorts]; ok { ports := []uint32{} if err := goyaml.Unmarshal([]byte(portsLabel), &ports); err != nil { // maybe it's a string, comma separated @@ -302,7 +302,7 @@ func fixPorts(service *types.ServiceConfig) error { // setCronJob creates a cronjob from the service labels. func setCronJob(service types.ServiceConfig, chart *HelmChart, appName string) *CronJob { - if _, ok := service.Labels[LABEL_CRONJOB]; !ok { + if _, ok := service.Labels[LabelCronJob]; !ok { return nil } cronjob, rbac := NewCronJob(service, chart, appName) @@ -336,7 +336,7 @@ func setCronJob(service types.ServiceConfig, chart *HelmChart, appName string) * // setDependencies sets the dependencies from the service labels. func setDependencies(chart *HelmChart, service types.ServiceConfig) (bool, error) { // helm dependency - if v, ok := service.Labels[LABEL_DEPENDENCIES]; ok { + if v, ok := service.Labels[LabelDependencies]; ok { d := []Dependency{} if err := yaml.Unmarshal([]byte(v), &d); err != nil { return false, err @@ -360,7 +360,7 @@ func setDependencies(chart *HelmChart, service types.ServiceConfig) (bool, error // isIgnored returns true if the service is ignored. func isIgnored(service types.ServiceConfig) bool { - if v, ok := service.Labels[LABEL_IGNORE]; ok { + if v, ok := service.Labels[LabelIgnore]; ok { return v == "true" || v == "yes" || v == "1" } return false @@ -381,7 +381,7 @@ func buildVolumes(service types.ServiceConfig, chart *HelmChart, deployments map // if the service is integrated in another deployment, we need to add the volume // to the target deployment - if override, ok := service.Labels[LABEL_SAME_POD]; ok { + if override, ok := service.Labels[LabelSamePod]; ok { pvc.nameOverride = override pvc.Spec.StorageClassName = utils.StrPtr(`{{ .Values.` + override + `.persistence.` + v.Source + `.storageClass }}`) chart.Values[override].(*Value).AddPersistence(v.Source) @@ -461,7 +461,7 @@ func generateConfigMapsAndSecrets(project *types.Project, chart *HelmChart) erro originalEnv[k] = v } - if v, ok := s.Labels[LABEL_SECRETS]; ok { + if v, ok := s.Labels[LabelSecrets]; ok { list := []string{} if err := yaml.Unmarshal([]byte(v), &list); err != nil { log.Fatal("error unmarshaling secrets label:", err) @@ -523,7 +523,7 @@ func samePodVolume(service types.ServiceConfig, v types.ServiceVolumeConfig, dep } targetDeployment := "" - if targetName, ok := service.Labels[LABEL_SAME_POD]; !ok { + if targetName, ok := service.Labels[LabelSamePod]; !ok { return false } else { targetDeployment = targetName @@ -555,11 +555,11 @@ func samePodVolume(service types.ServiceConfig, v types.ServiceVolumeConfig, dep func setSharedConf(service types.ServiceConfig, chart *HelmChart, deployments map[string]*Deployment) { // if the service has the "shared-conf" label, we need to add the configmap // to the chart and add the env vars to the service - if _, ok := service.Labels[LABEL_ENV_FROM]; !ok { + if _, ok := service.Labels[LabelEnvFrom]; !ok { return } fromservices := []string{} - if err := yaml.Unmarshal([]byte(service.Labels[LABEL_ENV_FROM]), &fromservices); err != nil { + if err := yaml.Unmarshal([]byte(service.Labels[LabelEnvFrom]), &fromservices); err != nil { log.Fatal("error unmarshaling env-from label:", err) } // find the configmap in the chart templates diff --git a/generator/globals.go b/generator/globals.go index e4e74ba..057dcc7 100644 --- a/generator/globals.go +++ b/generator/globals.go @@ -11,6 +11,6 @@ var ( // Standard annotationss Annotations = map[string]string{ - KATENARY_PREFIX + "version": Version, + labelName("version"): Version, } ) diff --git a/generator/helmHelper.tpl b/generator/helmHelper.tpl index f1b2515..769c55d 100644 --- a/generator/helmHelper.tpl +++ b/generator/helmHelper.tpl @@ -22,15 +22,15 @@ {{- define "__APP__.labels" -}} {{ include "__APP__.selectorLabels" .}} {{ if .Chart.Version -}} -{{ printf "__PREFIX__chart-version: '%s'" .Chart.Version }} +{{ printf "__PREFIX__/chart-version: '%s'" .Chart.Version }} {{- end }} {{ if .Chart.AppVersion -}} -{{ printf "__PREFIX__app-version: '%s'" .Chart.AppVersion }} +{{ printf "__PREFIX__/app-version: '%s'" .Chart.AppVersion }} {{- end }} {{- end -}} {{- define "__APP__.selectorLabels" -}} {{- $name := default .Chart.Name .Values.nameOverride -}} -{{ printf "__PREFIX__name: %s" $name }} -{{ printf "__PREFIX__instance: %s" .Release.Name }} +{{ printf "__PREFIX__/name: %s" $name }} +{{ printf "__PREFIX__/instance: %s" .Release.Name }} {{- end -}} diff --git a/generator/helper.go b/generator/helper.go index 51487af..a6a03c2 100644 --- a/generator/helper.go +++ b/generator/helper.go @@ -13,7 +13,7 @@ var helmHelper string // Helper returns the _helpers.tpl file for a chart. func Helper(name string) string { helmHelper := strings.ReplaceAll(helmHelper, "__APP__", name) - helmHelper = strings.ReplaceAll(helmHelper, "__PREFIX__", KATENARY_PREFIX) + helmHelper = strings.ReplaceAll(helmHelper, "__PREFIX__", katenaryLabelPrefix) helmHelper = strings.ReplaceAll(helmHelper, "__VERSION__", "0.1.0") return helmHelper } diff --git a/generator/ingress.go b/generator/ingress.go index 316743a..72bb041 100644 --- a/generator/ingress.go +++ b/generator/ingress.go @@ -24,13 +24,12 @@ type Ingress struct { func NewIngress(service types.ServiceConfig, Chart *HelmChart) *Ingress { appName := Chart.Name - // parse the KATENARY_PREFIX/ingress label from the service if service.Labels == nil { service.Labels = make(map[string]string) } var label string var ok bool - if label, ok = service.Labels[LABEL_INGRESS]; !ok { + if label, ok = service.Labels[LabelIngress]; !ok { return nil } diff --git a/generator/ingress_test.go b/generator/ingress_test.go index ccdc080..c81b2d4 100644 --- a/generator/ingress_test.go +++ b/generator/ingress_test.go @@ -18,11 +18,11 @@ services: - 80:80 - 443:443 labels: - %singress: |- + %s/ingress: |- host: my.test.tld port: 80 ` - composeFile = fmt.Sprintf(composeFile, KATENARY_PREFIX) + composeFile = fmt.Sprintf(composeFile, katenaryLabelPrefix) tmpDir := setup(composeFile) defer teardown(tmpDir) diff --git a/generator/katenaryLabels.go b/generator/katenaryLabels.go index 6c7c37a..d26d08d 100644 --- a/generator/katenaryLabels.go +++ b/generator/katenaryLabels.go @@ -36,24 +36,28 @@ type Help struct { Type string `yaml:"type"` } -const KATENARY_PREFIX = "katenary.v3/" +const katenaryLabelPrefix = "katenary.v3" + +func Prefix() string { + return katenaryLabelPrefix +} // Known labels. const ( - LABEL_MAIN_APP Label = KATENARY_PREFIX + "main-app" - LABEL_VALUES Label = KATENARY_PREFIX + "values" - LABEL_SECRETS Label = KATENARY_PREFIX + "secrets" - LABEL_PORTS Label = KATENARY_PREFIX + "ports" - LABEL_INGRESS Label = KATENARY_PREFIX + "ingress" - LABEL_MAP_ENV Label = KATENARY_PREFIX + "map-env" - LABEL_HEALTHCHECK Label = KATENARY_PREFIX + "health-check" - LABEL_SAME_POD Label = KATENARY_PREFIX + "same-pod" - LABEL_DESCRIPTION Label = KATENARY_PREFIX + "description" - LABEL_IGNORE Label = KATENARY_PREFIX + "ignore" - LABEL_DEPENDENCIES Label = KATENARY_PREFIX + "dependencies" - LABEL_CM_FILES Label = KATENARY_PREFIX + "configmap-files" - LABEL_CRONJOB Label = KATENARY_PREFIX + "cronjob" - LABEL_ENV_FROM Label = KATENARY_PREFIX + "env-from" + LabelMainApp Label = katenaryLabelPrefix + "/main-app" + LabelValues Label = katenaryLabelPrefix + "/values" + LabelSecrets Label = katenaryLabelPrefix + "/secrets" + LabelPorts Label = katenaryLabelPrefix + "/ports" + LabelIngress Label = katenaryLabelPrefix + "/ingress" + LabelMapEnv Label = katenaryLabelPrefix + "/map-env" + LabelHealthCheck Label = katenaryLabelPrefix + "/health-check" + LabelSamePod Label = katenaryLabelPrefix + "/same-pod" + LabelDescription Label = katenaryLabelPrefix + "/description" + LabelIgnore Label = katenaryLabelPrefix + "/ignore" + LabelDependencies Label = katenaryLabelPrefix + "/dependencies" + LabelConfigMapFiles Label = katenaryLabelPrefix + "/configmap-files" + LabelCronJob Label = katenaryLabelPrefix + "/cronjob" + LabelEnvFrom Label = katenaryLabelPrefix + "/env-from" ) func init() { @@ -62,6 +66,10 @@ func init() { } } +func labelName(name string) Label { + return Label(katenaryLabelPrefix + "/" + name) +} + // Generate the help for the labels. func GetLabelHelp(asMarkdown bool) string { names := GetLabelNames() // sorted @@ -75,7 +83,7 @@ func generatePlainHelp(names []string) string { var builder strings.Builder for _, name := range names { help := labelFullHelp[name] - fmt.Fprintf(&builder, "%s%s:\t%s\t%s\n", KATENARY_PREFIX, name, help.Type, help.Short) + fmt.Fprintf(&builder, "%s:\t%s\t%s\n", labelName(name), help.Type, help.Short) } // use tabwriter to align the help text @@ -100,7 +108,7 @@ func generateMarkdownHelp(names []string) string { } for _, name := range names { help := labelFullHelp[name] - maxNameLength = max(maxNameLength, len(name)+2+len(KATENARY_PREFIX)) + maxNameLength = max(maxNameLength, len(name)+2+len(katenaryLabelPrefix)) maxDescriptionLength = max(maxDescriptionLength, len(help.Short)) maxTypeLength = max(maxTypeLength, len(help.Type)) } @@ -111,7 +119,7 @@ func generateMarkdownHelp(names []string) string { for _, name := range names { help := labelFullHelp[name] fmt.Fprintf(&builder, "| %-*s | %-*s | %-*s |\n", - maxNameLength, "`"+KATENARY_PREFIX+name+"`", // enclose in backticks + maxNameLength, "`"+labelName(name)+"`", // enclose in backticks maxDescriptionLength, help.Short, maxTypeLength, help.Type, ) @@ -166,29 +174,29 @@ func GetLabelHelpFor(labelname string, asMarkdown bool) string { var buf bytes.Buffer template.Must(template.New("shorthelp").Parse(help.Long)).Execute(&buf, struct { - KATENARY_PREFIX string + KatenaryPrefix string }{ - KATENARY_PREFIX: KATENARY_PREFIX, + KatenaryPrefix: katenaryLabelPrefix, }) help.Long = buf.String() buf.Reset() template.Must(template.New("example").Parse(help.Example)).Execute(&buf, struct { - KATENARY_PREFIX string + KatenaryPrefix string }{ - KATENARY_PREFIX: KATENARY_PREFIX, + KatenaryPrefix: katenaryLabelPrefix, }) help.Example = buf.String() buf.Reset() template.Must(template.New("complete").Parse(helpTemplate)).Execute(&buf, struct { - Name string - Help Help - KATENARY_PREFIX string + Name string + Help Help + KatenaryPrefix string }{ - Name: labelname, - Help: help, - KATENARY_PREFIX: KATENARY_PREFIX, + Name: labelname, + Help: help, + KatenaryPrefix: katenaryLabelPrefix, }) return buf.String() @@ -206,7 +214,7 @@ func GetLabelNames() []string { func getHelpTemplate(asMarkdown bool) string { if asMarkdown { - return `## {{ .KATENARY_PREFIX }}{{ .Name }} + return `## {{ .KatenaryPrefix }}/{{ .Name }} {{ .Help.Short }} @@ -217,7 +225,7 @@ func getHelpTemplate(asMarkdown bool) string { **Example:**` + "\n\n```yaml\n" + `{{ .Help.Example }}` + "\n```\n" } - return `{{ .KATENARY_PREFIX }}{{ .Name }}: {{ .Help.Short }} + return `{{ .KatenaryPrefix }}/{{ .Name }}: {{ .Help.Short }} Type: {{ .Help.Type }} {{ .Help.Long }} diff --git a/generator/katenaryLabelsDoc.yaml b/generator/katenaryLabelsDoc.yaml index 36cd49b..9553343 100644 --- a/generator/katenaryLabelsDoc.yaml +++ b/generator/katenaryLabelsDoc.yaml @@ -19,7 +19,7 @@ # This is an {{ "{{ example }}" }}. # # This will display "This is an {{ exemple }}" in the output. -# - Use {{ .KATENARY_PREFIX }} to let Katenary replace it with the label prefix (e.g. "katenary.v3/") +# - Use {{ .KatenaryPrefix }} to let Katenary replace it with the label prefix (e.g. "katenary.v3") "main-app": short: "Mark the service as the main app." @@ -40,7 +40,7 @@ # The chart is now named ghost, and the appVersion is 1.25.5. # In Deployment, the image attribute is set to ghost:1.25.5 if # you don't change the "tag" attribute in values.yaml - {{ .KATENARY_PREFIX }}main-app: true + {{ .KatenaryPrefix }}/main-app: true type: "bool" "values": @@ -63,7 +63,7 @@ TO_CONFIGURE: something that can be changed in values.yaml A_COMPLEX_VALUE: example labels: - {{ .KATENARY_PREFIX }}values: |- + {{ .KatenaryPrefix }}/values: |- # simple values, set as is in values.yaml - TO_CONFIGURE # complex values, set as a template in values.yaml with a documentation @@ -79,14 +79,14 @@ This label allows setting the environment variables as secrets. The variable is removed from the environment and added to a secret object. - The variable can be set to the {{ printf "%s%s" .KATENARY_PREFIX "values"}} too, + The variable can be set to the {{ printf "%s/%s" .KatenaryPrefix "values"}} too, so the secret value can be configured in values.yaml example: |- env: PASSWORD: a very secret password NOT_A_SECRET: a public value labels: - {{ .KATENARY_PREFIX }}secrets: |- + {{ .KatenaryPrefix }}/secrets: |- - PASSWORD type: "list of string" @@ -97,7 +97,7 @@ service is a dependency of another service. example: |- labels: - {{ .KATENARY_PREFIX }}ports: |- + {{ .KatenaryPrefix }}/ports: |- - 8080 - 8081 type: "list of uint32" @@ -106,10 +106,10 @@ short: "Ingress rules to be added to the service." long: |- Declare an ingress rule for the service. The port should be exposed or - declared with {{ printf "%s%s" .KATENARY_PREFIX "ports" }}. + declared with {{ printf "%s/%s" .KatenaryPrefix "ports" }}. example: |- labels: - {{ .KATENARY_PREFIX }}ingress: |- + {{ .KatenaryPrefix }}/ingress: |- port: 80 hostname: mywebsite.com (optional) type: "object" @@ -130,7 +130,7 @@ RUNNING: docker OTHER: value labels: - {{ .KATENARY_PREFIX }}map-env: |- + {{ .KatenaryPrefix }}/map-env: |- RUNNING: kubernetes DB_HOST: '{{ "{{ include \"__APP__.fullname\" . }}" }}-database' type: "object" @@ -140,7 +140,7 @@ long: "Health check to be added to the deployment." example: |- labels: - {{ .KATENARY_PREFIX }}health-check: |- + {{ .KatenaryPrefix }}/health-check: |- httpGet: path: /health port: 8080 @@ -161,7 +161,7 @@ php: image: php:7.4-fpm labels: - {{ .KATENARY_PREFIX }}same-pod: web + {{ .KatenaryPrefix }}/same-pod: web type: "string" "description": @@ -173,7 +173,7 @@ The value can be set with a documentation in multiline format. example: |- labels: - {{ .KATENARY_PREFIX }}description: |- + {{ .KatenaryPrefix }}/description: |- This is a description of the service. It can be multiline. type: "string" @@ -181,7 +181,7 @@ "ignore": short: "Ignore the service" long: "Ingoring a service to not be exported in helm chart." - example: "labels:\n {{ .KATENARY_PREFIX }}ignore: \"true\"" + example: "labels:\n {{ .KatenaryPrefix }}/ignore: \"true\"" type: "bool" "dependencies": @@ -209,7 +209,7 @@ in values.yaml. example: |- labels: - {{ .KATENARY_PREFIX }}dependencies: |- + {{ .KatenaryPrefix }}/dependencies: |- - name: mariadb repository: oci://registry-1.docker.io/bitnamicharts @@ -244,7 +244,7 @@ volumes - ./conf.d:/etc/nginx/conf.d labels: - {{ .KATENARY_PREFIX }}configmap-files: |- + {{ .KatenaryPrefix }}/configmap-files: |- - ./conf.d type: "list of strings" @@ -261,7 +261,7 @@ a serviceaccount to make your cronjob able to connect the Kubernetes API example: |- labels: - {{ .KATENARY_PREFIX }}cronjob: |- + {{ .KatenaryPrefix }}/cronjob: |- command: echo "hello world" schedule: "* */1 * * *" # or @hourly for example type: "object" @@ -282,6 +282,6 @@ labels: # get the congigMap from service1 where FOO is # defined inside this service too - {{ .KATENARY_PREFIX }}env-from: |- + {{ .KatenaryPrefix }}/env-from: |- - myservice1 # vim: ft=gotmpl.yaml diff --git a/generator/labels.go b/generator/labels.go index acb2982..7a828a0 100644 --- a/generator/labels.go +++ b/generator/labels.go @@ -4,20 +4,13 @@ import ( "fmt" ) -// LabelType identifies the type of label to generate in objects. -// TODO: is this still needed? -type LabelType uint8 - -const ( - DeploymentLabel LabelType = iota - ServiceLabel -) +var componentLabel = labelName("component") // GetLabels returns the labels for a service. It uses the appName to replace the __replace__ in the labels. // This is used to generate the labels in the templates. func GetLabels(serviceName, appName string) map[string]string { labels := map[string]string{ - KATENARY_PREFIX + "component": serviceName, + componentLabel: serviceName, } key := `{{- include "%s.labels" . | nindent __indent__ }}` @@ -30,7 +23,7 @@ func GetLabels(serviceName, appName string) map[string]string { // This is used to generate the matchLabels in the templates. func GetMatchLabels(serviceName, appName string) map[string]string { labels := map[string]string{ - KATENARY_PREFIX + "component": serviceName, + componentLabel: serviceName, } key := `{{- include "%s.selectorLabels" . | nindent __indent__ }}` diff --git a/generator/secret.go b/generator/secret.go index 16b7eb1..9a6122f 100644 --- a/generator/secret.go +++ b/generator/secret.go @@ -46,7 +46,7 @@ func NewSecret(service types.ServiceConfig, appName string) *Secret { // check if the value should be in values.yaml valueList := []string{} - varDescriptons := utils.GetValuesFromLabel(service, LABEL_VALUES) + varDescriptons := utils.GetValuesFromLabel(service, LabelValues) for value := range varDescriptons { valueList = append(valueList, value) } diff --git a/generator/secret_test.go b/generator/secret_test.go index fb30ebb..93949b6 100644 --- a/generator/secret_test.go +++ b/generator/secret_test.go @@ -18,10 +18,10 @@ services: - FOO=bar - BAR=baz labels: - %ssecrets: |- + %s/secrets: |- - BAR ` - composeFile = fmt.Sprintf(composeFile, KATENARY_PREFIX) + composeFile = fmt.Sprintf(composeFile, katenaryLabelPrefix) tmpDir := setup(composeFile) defer teardown(tmpDir) diff --git a/generator/values.go b/generator/values.go index 7db405f..8b26b39 100644 --- a/generator/values.go +++ b/generator/values.go @@ -33,22 +33,6 @@ type IngressValue struct { } // Value will be saved in values.yaml. It contains configuraiton for all deployment and services. -// The content will be lile: -// -// name_of_component: -// repository: -// image: image_name -// tag: image_tag -// persistence: -// enabled: true -// storageClass: storage_class_name -// ingress: -// enabled: true -// host: host_name -// path: path_name -// environment: -// ENV_VAR_1: value_1 -// ENV_VAR_2: value_2 type Value struct { Repository *RepositoryValue `yaml:"repository,omitempty"` Persistence map[string]*PersistenceValue `yaml:"persistence,omitempty"` diff --git a/generator/volume_test.go b/generator/volume_test.go index 86659a8..9d327d3 100644 --- a/generator/volume_test.go +++ b/generator/volume_test.go @@ -47,10 +47,10 @@ services: volumes: - ./static:/var/www labels: - %sconfigmap-files: |- + %s/configmap-files: |- - ./static ` - _compose_file = fmt.Sprintf(_compose_file, KATENARY_PREFIX) + _compose_file = fmt.Sprintf(_compose_file, katenaryLabelPrefix) tmpDir := setup(_compose_file) defer teardown(tmpDir)