From 6512b1f3fcba7342c11cf96968e753c78e66561b Mon Sep 17 00:00:00 2001 From: Shinnosuke Sawada-Dazai Date: Mon, 28 Oct 2024 13:01:51 +0900 Subject: [PATCH] Implement TemplateLocalChart with helm (#5294) * Implement TemplateLocalChart with helm Signed-off-by: Shinnosuke Sawada-Dazai * Copy testdata for helm test Signed-off-by: Shinnosuke Sawada-Dazai * Add helm test Signed-off-by: Shinnosuke Sawada-Dazai --------- Signed-off-by: Shinnosuke Sawada-Dazai --- .../pipedv1/plugin/kubernetes/config/helm.go | 31 +++ .../plugin/kubernetes/provider/helm.go | 161 ++++++++++++++++ .../plugin/kubernetes/provider/helm_test.go | 178 ++++++++++++++++++ .../provider/testdata/testchart/.helmignore | 23 +++ .../provider/testdata/testchart/Chart.yaml | 23 +++ .../testdata/testchart/templates/NOTES.txt | 21 +++ .../testdata/testchart/templates/_helpers.tpl | 63 +++++++ .../testchart/templates/deployment.yaml | 62 ++++++ .../testdata/testchart/templates/hpa.yaml | 28 +++ .../testdata/testchart/templates/ingress.yaml | 42 +++++ .../testdata/testchart/templates/service.yaml | 16 ++ .../testchart/templates/serviceaccount.yaml | 13 ++ .../templates/tests/test-connection.yaml | 15 ++ .../provider/testdata/testchart/values.yaml | 79 ++++++++ .../testhelm/appconfdir/app.pipecd.yaml | 0 .../testhelm/appconfdir/dir/values.yaml | 0 .../testhelm/appconfdir/invalid-symlink | 1 + .../testhelm/appconfdir/valid-symlink | 1 + .../testdata/testhelm/appconfdir/values.yaml | 0 .../provider/testdata/testhelm/values.yaml | 0 20 files changed, 757 insertions(+) create mode 100644 pkg/app/pipedv1/plugin/kubernetes/config/helm.go create mode 100644 pkg/app/pipedv1/plugin/kubernetes/provider/helm.go create mode 100644 pkg/app/pipedv1/plugin/kubernetes/provider/helm_test.go create mode 100644 pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/.helmignore create mode 100644 pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/Chart.yaml create mode 100644 pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/NOTES.txt create mode 100644 pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/_helpers.tpl create mode 100644 pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/deployment.yaml create mode 100644 pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/hpa.yaml create mode 100644 pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/ingress.yaml create mode 100644 pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/service.yaml create mode 100644 pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/serviceaccount.yaml create mode 100644 pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/tests/test-connection.yaml create mode 100644 pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/values.yaml create mode 100644 pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/appconfdir/app.pipecd.yaml create mode 100644 pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/appconfdir/dir/values.yaml create mode 120000 pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/appconfdir/invalid-symlink create mode 120000 pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/appconfdir/valid-symlink create mode 100644 pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/appconfdir/values.yaml create mode 100644 pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/values.yaml diff --git a/pkg/app/pipedv1/plugin/kubernetes/config/helm.go b/pkg/app/pipedv1/plugin/kubernetes/config/helm.go new file mode 100644 index 0000000000..b0a3f3879c --- /dev/null +++ b/pkg/app/pipedv1/plugin/kubernetes/config/helm.go @@ -0,0 +1,31 @@ +// Copyright 2024 The PipeCD Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 config + +type InputHelmOptions struct { + // The release name of helm deployment. + // By default the release name is equal to the application name. + ReleaseName string `json:"releaseName,omitempty"` + // List of values. + SetValues map[string]string `json:"setValues,omitempty"` + // List of value files should be loaded. + ValueFiles []string `json:"valueFiles,omitempty"` + // List of file path for values. + SetFiles map[string]string `json:"setFiles,omitempty"` + // Set of supported Kubernetes API versions. + APIVersions []string `json:"apiVersions,omitempty"` + // Kubernetes version used for Capabilities.KubeVersion + KubeVersion string `json:"kubeVersion,omitempty"` +} diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/helm.go b/pkg/app/pipedv1/plugin/kubernetes/provider/helm.go new file mode 100644 index 0000000000..a6796ec867 --- /dev/null +++ b/pkg/app/pipedv1/plugin/kubernetes/provider/helm.go @@ -0,0 +1,161 @@ +// Copyright 2024 The PipeCD Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 provider + +import ( + "bytes" + "context" + "fmt" + "net/url" + "os" + "os/exec" + "path/filepath" + "strings" + + "go.uber.org/zap" + + "github.com/pipe-cd/pipecd/pkg/app/pipedv1/plugin/kubernetes/config" +) + +var ( + allowedURLSchemes = []string{"http", "https"} +) + +type Helm struct { + execPath string + logger *zap.Logger +} + +func NewHelm(path string, logger *zap.Logger) *Helm { + return &Helm{ + execPath: path, + logger: logger, + } +} + +func (h *Helm) TemplateLocalChart(ctx context.Context, appName, appDir, namespace, chartPath string, opts *config.InputHelmOptions) (string, error) { + releaseName := appName + if opts != nil && opts.ReleaseName != "" { + releaseName = opts.ReleaseName + } + + args := []string{ + "template", + "--no-hooks", + "--include-crds", + releaseName, + chartPath, + } + + if namespace != "" { + args = append(args, fmt.Sprintf("--namespace=%s", namespace)) + } + + if opts != nil { + for k, v := range opts.SetValues { + args = append(args, "--set", fmt.Sprintf("%s=%s", k, v)) + } + for _, v := range opts.ValueFiles { + if err := verifyHelmValueFilePath(appDir, v); err != nil { + h.logger.Error("failed to verify values file path", zap.Error(err)) + return "", err + } + args = append(args, "-f", v) + } + for k, v := range opts.SetFiles { + args = append(args, "--set-file", fmt.Sprintf("%s=%s", k, v)) + } + for _, v := range opts.APIVersions { + args = append(args, "--api-versions", v) + } + if opts.KubeVersion != "" { + args = append(args, "--kube-version", opts.KubeVersion) + } + } + + var stdout, stderr bytes.Buffer + cmd := exec.CommandContext(ctx, h.execPath, args...) + cmd.Dir = appDir + cmd.Stdout = &stdout + cmd.Stderr = &stderr + + h.logger.Info(fmt.Sprintf("start templating a local chart (or cloned remote git chart) for application %s", appName), + zap.Any("args", args), + ) + + if err := cmd.Run(); err != nil { + return stdout.String(), fmt.Errorf("%w: %s", err, stderr.String()) + } + return stdout.String(), nil +} + +// verifyHelmValueFilePath verifies if the path of the values file references +// a remote URL or inside the path where the application configuration file (i.e. *.pipecd.yaml) is located. +func verifyHelmValueFilePath(appDir, valueFilePath string) error { + url, err := url.Parse(valueFilePath) + if err == nil && url.Scheme != "" { + for _, s := range allowedURLSchemes { + if strings.EqualFold(url.Scheme, s) { + return nil + } + } + + return fmt.Errorf("scheme %s is not allowed to load values file", url.Scheme) + } + + // valueFilePath is a path where non-default Helm values file is located. + if !filepath.IsAbs(valueFilePath) { + valueFilePath = filepath.Join(appDir, valueFilePath) + } + + if isSymlink(valueFilePath) { + if valueFilePath, err = resolveSymlinkToAbsPath(valueFilePath, appDir); err != nil { + return err + } + } + + // If a path outside of appDir is specified as the path for the values file, + // it may indicate that someone trying to illegally read a file as values file that + // exists in the environment where Piped is running. + if !strings.HasPrefix(valueFilePath, appDir) { + return fmt.Errorf("values file %s references outside the application configuration directory", valueFilePath) + } + + return nil +} + +// isSymlink returns the path is whether symbolic link or not. +func isSymlink(path string) bool { + lstat, err := os.Lstat(path) + if err != nil { + return false + } + + return lstat.Mode()&os.ModeSymlink == os.ModeSymlink +} + +// resolveSymlinkToAbsPath resolves symbolic link to an absolute path. +func resolveSymlinkToAbsPath(path, absParentDir string) (string, error) { + resolved, err := os.Readlink(path) + if err != nil { + return "", err + } + + if !filepath.IsAbs(resolved) { + resolved = filepath.Join(absParentDir, resolved) + } + + return resolved, nil +} diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/helm_test.go b/pkg/app/pipedv1/plugin/kubernetes/provider/helm_test.go new file mode 100644 index 0000000000..b32a2152b3 --- /dev/null +++ b/pkg/app/pipedv1/plugin/kubernetes/provider/helm_test.go @@ -0,0 +1,178 @@ +// Copyright 2024 The PipeCD Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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 provider + +import ( + "context" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + + "github.com/pipe-cd/pipecd/pkg/app/pipedv1/plugin/kubernetes/toolregistry" + "github.com/pipe-cd/pipecd/pkg/app/pipedv1/plugin/toolregistry/toolregistrytest" +) + +func TestTemplateLocalChart(t *testing.T) { + t.Parallel() + + var ( + ctx = context.Background() + appName = "testapp" + appDir = "testdata" + chartPath = "testchart" + ) + + c, err := toolregistrytest.NewToolRegistry(t) + require.NoError(t, err) + t.Cleanup(func() { c.Close() }) + + r := toolregistry.NewRegistry(c) + helmPath, err := r.Helm(ctx, "3.16.1") + require.NoError(t, err) + + helm := NewHelm(helmPath, zap.NewNop()) + out, err := helm.TemplateLocalChart(ctx, appName, appDir, "", chartPath, nil) + require.NoError(t, err) + + out = strings.TrimPrefix(out, "---") + manifests := strings.Split(out, "---") + assert.Equal(t, 3, len(manifests)) +} + +func TestTemplateLocalChart_WithNamespace(t *testing.T) { + t.Parallel() + + var ( + ctx = context.Background() + appName = "testapp" + appDir = "testdata" + chartPath = "testchart" + namespace = "testnamespace" + ) + + c, err := toolregistrytest.NewToolRegistry(t) + require.NoError(t, err) + t.Cleanup(func() { c.Close() }) + + r := toolregistry.NewRegistry(c) + helmPath, err := r.Helm(ctx, "3.16.1") + require.NoError(t, err) + + helm := NewHelm(helmPath, zap.NewNop()) + out, err := helm.TemplateLocalChart(ctx, appName, appDir, namespace, chartPath, nil) + require.NoError(t, err) + + out = strings.TrimPrefix(out, "---") + + manifests, _ := ParseManifests(out) + for _, manifest := range manifests { + metadata, _, err := unstructured.NestedMap(manifest.Body.Object, "metadata") + require.NoError(t, err) + require.Equal(t, namespace, metadata["namespace"]) + } +} + +func TestVerifyHelmValueFilePath(t *testing.T) { + t.Parallel() + + testcases := []struct { + name string + appDir string + valueFilePath string + wantErr bool + }{ + { + name: "Values file locates inside the app dir", + appDir: "testdata/testhelm/appconfdir", + valueFilePath: "values.yaml", + wantErr: false, + }, + { + name: "Values file locates inside the app dir (with ..)", + appDir: "testdata/testhelm/appconfdir", + valueFilePath: "../../../testdata/testhelm/appconfdir/values.yaml", + wantErr: false, + }, + { + name: "Values file locates under the app dir", + appDir: "testdata/testhelm/appconfdir", + valueFilePath: "dir/values.yaml", + wantErr: false, + }, + { + name: "Values file locates under the app dir (with ..)", + appDir: "testdata/testhelm/appconfdir", + valueFilePath: "../../../testdata/testhelm/appconfdir/dir/values.yaml", + wantErr: false, + }, + { + name: "arbitrary file locates outside the app dir", + appDir: "testdata/testhelm/appconfdir", + valueFilePath: "/etc/hosts", + wantErr: true, + }, + { + name: "arbitrary file locates outside the app dir (with ..)", + appDir: "testdata/testhelm/appconfdir", + valueFilePath: "../../../../../../../../../../../../etc/hosts", + wantErr: true, + }, + { + name: "Values file locates allowed remote URL (http)", + appDir: "testdata/testhelm/appconfdir", + valueFilePath: "http://exmaple.com/values.yaml", + wantErr: false, + }, + { + name: "Values file locates allowed remote URL (https)", + appDir: "testdata/testhelm/appconfdir", + valueFilePath: "https://exmaple.com/values.yaml", + wantErr: false, + }, + { + name: "Values file locates disallowed remote URL (ftp)", + appDir: "testdata/testhelm/appconfdir", + valueFilePath: "ftp://exmaple.com/values.yaml", + wantErr: true, + }, + { + name: "Values file is symlink targeting valid values file", + appDir: "testdata/testhelm/appconfdir", + valueFilePath: "valid-symlink", + wantErr: false, + }, + { + name: "Values file is symlink targeting invalid values file", + appDir: "testdata/testhelm/appconfdir", + valueFilePath: "invalid-symlink", + wantErr: true, + }, + } + + for _, tc := range testcases { + t.Run(tc.name, func(t *testing.T) { + err := verifyHelmValueFilePath(tc.appDir, tc.valueFilePath) + if tc.wantErr { + require.Error(t, err) + } else { + require.NoError(t, err) + } + }) + } +} diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/.helmignore b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/.helmignore new file mode 100644 index 0000000000..0e8a0eb36f --- /dev/null +++ b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/.helmignore @@ -0,0 +1,23 @@ +# Patterns to ignore when building packages. +# This supports shell glob matching, relative path matching, and +# negation (prefixed with !). Only one pattern per line. +.DS_Store +# Common VCS dirs +.git/ +.gitignore +.bzr/ +.bzrignore +.hg/ +.hgignore +.svn/ +# Common backup files +*.swp +*.bak +*.tmp +*.orig +*~ +# Various IDEs +.project +.idea/ +*.tmproj +.vscode/ diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/Chart.yaml b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/Chart.yaml new file mode 100644 index 0000000000..5bbebd26c2 --- /dev/null +++ b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/Chart.yaml @@ -0,0 +1,23 @@ +apiVersion: v2 +name: testchart +description: A Helm chart for Kubernetes + +# A chart can be either an 'application' or a 'library' chart. +# +# Application charts are a collection of templates that can be packaged into versioned archives +# to be deployed. +# +# Library charts provide useful utilities or functions for the chart developer. They're included as +# a dependency of application charts to inject those utilities and functions into the rendering +# pipeline. Library charts do not define any templates and therefore cannot be deployed. +type: application + +# This is the chart version. This version number should be incremented each time you make changes +# to the chart and its templates, including the app version. +# Versions are expected to follow Semantic Versioning (https://semver.org/) +version: 0.1.0 + +# This is the version number of the application being deployed. This version number should be +# incremented each time you make changes to the application. Versions are not expected to +# follow Semantic Versioning. They should reflect the version the application is using. +appVersion: 1.16.0 diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/NOTES.txt b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/NOTES.txt new file mode 100644 index 0000000000..9b8fb51f68 --- /dev/null +++ b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/NOTES.txt @@ -0,0 +1,21 @@ +1. Get the application URL by running these commands: +{{- if .Values.ingress.enabled }} +{{- range $host := .Values.ingress.hosts }} + {{- range .paths }} + http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $host.host }}{{ . }} + {{- end }} +{{- end }} +{{- else if contains "NodePort" .Values.service.type }} + export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "testchart.fullname" . }}) + export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}") + echo http://$NODE_IP:$NODE_PORT +{{- else if contains "LoadBalancer" .Values.service.type }} + NOTE: It may take a few minutes for the LoadBalancer IP to be available. + You can watch the status of by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "testchart.fullname" . }}' + export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "testchart.fullname" . }} --template "{{"{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}"}}") + echo http://$SERVICE_IP:{{ .Values.service.port }} +{{- else if contains "ClusterIP" .Values.service.type }} + export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "testchart.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}") + echo "Visit http://127.0.0.1:8080 to use your application" + kubectl --namespace {{ .Release.Namespace }} port-forward $POD_NAME 8080:80 +{{- end }} diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/_helpers.tpl b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/_helpers.tpl new file mode 100644 index 0000000000..698af2572c --- /dev/null +++ b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/_helpers.tpl @@ -0,0 +1,63 @@ +{{/* vim: set filetype=mustache: */}} +{{/* +Expand the name of the chart. +*/}} +{{- define "testchart.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Create a default fully qualified app name. +We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). +If release name contains chart name it will be used as a full name. +*/}} +{{- define "testchart.fullname" -}} +{{- if .Values.fullnameOverride }} +{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- $name := default .Chart.Name .Values.nameOverride }} +{{- if contains $name .Release.Name }} +{{- .Release.Name | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }} +{{- end }} +{{- end }} +{{- end }} + +{{/* +Create chart name and version as used by the chart label. +*/}} +{{- define "testchart.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Common labels +*/}} +{{- define "testchart.labels" -}} +helm.sh/chart: {{ include "testchart.chart" . }} +{{ include "testchart.selectorLabels" . }} +{{- if .Chart.AppVersion }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +{{- end }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end }} + +{{/* +Selector labels +*/}} +{{- define "testchart.selectorLabels" -}} +app.kubernetes.io/name: {{ include "testchart.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- end }} + +{{/* +Create the name of the service account to use +*/}} +{{- define "testchart.serviceAccountName" -}} +{{- if .Values.serviceAccount.create }} +{{- default (include "testchart.fullname" .) .Values.serviceAccount.name }} +{{- else }} +{{- default "default" .Values.serviceAccount.name }} +{{- end }} +{{- end }} diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/deployment.yaml b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/deployment.yaml new file mode 100644 index 0000000000..b9c4cf95df --- /dev/null +++ b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/deployment.yaml @@ -0,0 +1,62 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "testchart.fullname" . }} + labels: + {{- include "testchart.labels" . | nindent 4 }} + namespace: {{.Release.Namespace}} +spec: +{{- if not .Values.autoscaling.enabled }} + replicas: {{ .Values.replicaCount }} +{{- end }} + selector: + matchLabels: + {{- include "testchart.selectorLabels" . | nindent 6 }} + template: + metadata: + {{- with .Values.podAnnotations }} + annotations: + {{- toYaml . | nindent 8 }} + {{- end }} + labels: + {{- include "testchart.selectorLabels" . | nindent 8 }} + spec: + {{- with .Values.imagePullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + serviceAccountName: {{ include "testchart.serviceAccountName" . }} + securityContext: + {{- toYaml .Values.podSecurityContext | nindent 8 }} + containers: + - name: {{ .Chart.Name }} + securityContext: + {{- toYaml .Values.securityContext | nindent 12 }} + image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + ports: + - name: http + containerPort: 80 + protocol: TCP + livenessProbe: + httpGet: + path: / + port: http + readinessProbe: + httpGet: + path: / + port: http + resources: + {{- toYaml .Values.resources | nindent 12 }} + {{- with .Values.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.affinity }} + affinity: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/hpa.yaml b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/hpa.yaml new file mode 100644 index 0000000000..58c5a47d7e --- /dev/null +++ b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/hpa.yaml @@ -0,0 +1,28 @@ +{{- if .Values.autoscaling.enabled }} +apiVersion: autoscaling/v2beta1 +kind: HorizontalPodAutoscaler +metadata: + name: {{ include "testchart.fullname" . }} + labels: + {{- include "testchart.labels" . | nindent 4 }} +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: {{ include "testchart.fullname" . }} + minReplicas: {{ .Values.autoscaling.minReplicas }} + maxReplicas: {{ .Values.autoscaling.maxReplicas }} + metrics: + {{- if .Values.autoscaling.targetCPUUtilizationPercentage }} + - type: Resource + resource: + name: cpu + targetAverageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }} + {{- end }} + {{- if .Values.autoscaling.targetMemoryUtilizationPercentage }} + - type: Resource + resource: + name: memory + targetAverageUtilization: {{ .Values.autoscaling.targetMemoryUtilizationPercentage }} + {{- end }} +{{- end }} diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/ingress.yaml b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/ingress.yaml new file mode 100644 index 0000000000..7c17e022f3 --- /dev/null +++ b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/ingress.yaml @@ -0,0 +1,42 @@ +{{- if .Values.ingress.enabled -}} +{{- $fullName := include "testchart.fullname" . -}} +{{- $svcPort := .Values.service.port -}} +{{- if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}} +apiVersion: networking.k8s.io/v1beta1 +{{- else -}} +apiVersion: extensions/v1beta1 +{{- end }} +kind: Ingress +metadata: + name: {{ $fullName }} + labels: + {{- include "testchart.labels" . | nindent 4 }} + {{- with .Values.ingress.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} + namespace: {{.Release.Namespace}} +spec: + {{- if .Values.ingress.tls }} + tls: + {{- range .Values.ingress.tls }} + - hosts: + {{- range .hosts }} + - {{ . | quote }} + {{- end }} + secretName: {{ .secretName }} + {{- end }} + {{- end }} + rules: + {{- range .Values.ingress.hosts }} + - host: {{ .host | quote }} + http: + paths: + {{- range .paths }} + - path: {{ . }} + backend: + serviceName: {{ $fullName }} + servicePort: {{ $svcPort }} + {{- end }} + {{- end }} + {{- end }} diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/service.yaml b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/service.yaml new file mode 100644 index 0000000000..d8c6e26de7 --- /dev/null +++ b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/service.yaml @@ -0,0 +1,16 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ include "testchart.fullname" . }} + labels: + {{- include "testchart.labels" . | nindent 4 }} + namespace: {{.Release.Namespace}} +spec: + type: {{ .Values.service.type }} + ports: + - port: {{ .Values.service.port }} + targetPort: http + protocol: TCP + name: http + selector: + {{- include "testchart.selectorLabels" . | nindent 4 }} diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/serviceaccount.yaml b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/serviceaccount.yaml new file mode 100644 index 0000000000..4537db7747 --- /dev/null +++ b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/serviceaccount.yaml @@ -0,0 +1,13 @@ +{{- if .Values.serviceAccount.create -}} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "testchart.serviceAccountName" . }} + namespace: {{.Release.Namespace}} + labels: + {{- include "testchart.labels" . | nindent 4 }} + {{- with .Values.serviceAccount.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +{{- end }} diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/tests/test-connection.yaml b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/tests/test-connection.yaml new file mode 100644 index 0000000000..94ec750986 --- /dev/null +++ b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/templates/tests/test-connection.yaml @@ -0,0 +1,15 @@ +apiVersion: v1 +kind: Pod +metadata: + name: "{{ include "testchart.fullname" . }}-test-connection" + labels: + {{- include "testchart.labels" . | nindent 4 }} + annotations: + "helm.sh/hook": test-success +spec: + containers: + - name: wget + image: busybox + command: ['wget'] + args: ['{{ include "testchart.fullname" . }}:{{ .Values.service.port }}'] + restartPolicy: Never diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/values.yaml b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/values.yaml new file mode 100644 index 0000000000..6c45a41504 --- /dev/null +++ b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testchart/values.yaml @@ -0,0 +1,79 @@ +# Default values for testchart. +# This is a YAML-formatted file. +# Declare variables to be passed into your templates. + +replicaCount: 1 + +image: + repository: nginx + pullPolicy: IfNotPresent + # Overrides the image tag whose default is the chart appVersion. + tag: "" + +imagePullSecrets: [] +nameOverride: "" +fullnameOverride: "" + +serviceAccount: + # Specifies whether a service account should be created + create: true + # Annotations to add to the service account + annotations: {} + # The name of the service account to use. + # If not set and create is true, a name is generated using the fullname template + name: "" + +podAnnotations: {} + +podSecurityContext: {} + # fsGroup: 2000 + +securityContext: {} + # capabilities: + # drop: + # - ALL + # readOnlyRootFilesystem: true + # runAsNonRoot: true + # runAsUser: 1000 + +service: + type: ClusterIP + port: 80 + +ingress: + enabled: false + annotations: {} + # kubernetes.io/ingress.class: nginx + # kubernetes.io/tls-acme: "true" + hosts: + - host: chart-example.local + paths: [] + tls: [] + # - secretName: chart-example-tls + # hosts: + # - chart-example.local + +resources: {} + # We usually recommend not to specify default resources and to leave this as a conscious + # choice for the user. This also increases chances charts run on environments with little + # resources, such as Minikube. If you do want to specify resources, uncomment the following + # lines, adjust them as necessary, and remove the curly braces after 'resources:'. + # limits: + # cpu: 100m + # memory: 128Mi + # requests: + # cpu: 100m + # memory: 128Mi + +autoscaling: + enabled: false + minReplicas: 1 + maxReplicas: 100 + targetCPUUtilizationPercentage: 80 + # targetMemoryUtilizationPercentage: 80 + +nodeSelector: {} + +tolerations: [] + +affinity: {} diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/appconfdir/app.pipecd.yaml b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/appconfdir/app.pipecd.yaml new file mode 100644 index 0000000000..e69de29bb2 diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/appconfdir/dir/values.yaml b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/appconfdir/dir/values.yaml new file mode 100644 index 0000000000..e69de29bb2 diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/appconfdir/invalid-symlink b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/appconfdir/invalid-symlink new file mode 120000 index 0000000000..555dec973e --- /dev/null +++ b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/appconfdir/invalid-symlink @@ -0,0 +1 @@ +/etc/hosts \ No newline at end of file diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/appconfdir/valid-symlink b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/appconfdir/valid-symlink new file mode 120000 index 0000000000..a53324e8c5 --- /dev/null +++ b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/appconfdir/valid-symlink @@ -0,0 +1 @@ +dir/values.yaml \ No newline at end of file diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/appconfdir/values.yaml b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/appconfdir/values.yaml new file mode 100644 index 0000000000..e69de29bb2 diff --git a/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/values.yaml b/pkg/app/pipedv1/plugin/kubernetes/provider/testdata/testhelm/values.yaml new file mode 100644 index 0000000000..e69de29bb2