sigs.k8s.io/kubebuilder/v3@v3.14.0/pkg/plugins/golang/v4/scaffolds/internal/templates/test/utils/utils.go (about)

     1  /*
     2  Copyright 2022 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package utils
    18  
    19  import (
    20  	"sigs.k8s.io/kubebuilder/v3/pkg/machinery"
    21  )
    22  
    23  var _ machinery.Template = &Utils{}
    24  
    25  type Utils struct {
    26  	machinery.TemplateMixin
    27  	machinery.BoilerplateMixin
    28  }
    29  
    30  func (f *Utils) SetTemplateDefaults() error {
    31  	if f.Path == "" {
    32  		f.Path = "test/utils/utils.go"
    33  	}
    34  
    35  	f.TemplateBody = utilsTemplate
    36  
    37  	return nil
    38  }
    39  
    40  var utilsTemplate = `{{ .Boilerplate }}
    41  
    42  package utils
    43  
    44  import (
    45  	"fmt"
    46  	"os"
    47  	"os/exec"
    48  	"strings"
    49  
    50  	. "github.com/onsi/ginkgo/v2" //nolint:golint,revive
    51  )
    52  
    53  const (
    54  	prometheusOperatorVersion = "v0.68.0"
    55  	prometheusOperatorURL     = "https://github.com/prometheus-operator/prometheus-operator/" +
    56  		"releases/download/%s/bundle.yaml"
    57  
    58  	certmanagerVersion = "v1.5.3"
    59  	certmanagerURLTmpl = "https://github.com/jetstack/cert-manager/releases/download/%s/cert-manager.yaml"
    60  )
    61  
    62  func warnError(err error) {
    63  	fmt.Fprintf(GinkgoWriter, "warning: %v\n", err)
    64  }
    65  
    66  // InstallPrometheusOperator installs the prometheus Operator to be used to export the enabled metrics.
    67  func InstallPrometheusOperator() error {
    68  	url := fmt.Sprintf(prometheusOperatorURL, prometheusOperatorVersion)
    69  	cmd := exec.Command("kubectl", "create", "-f", url)
    70  	_, err := Run(cmd)
    71  	return err
    72  }
    73  
    74  // Run executes the provided command within this context
    75  func Run(cmd *exec.Cmd) ([]byte, error) {
    76  	dir, _ := GetProjectDir()
    77  	cmd.Dir = dir
    78  
    79  	if err := os.Chdir(cmd.Dir); err != nil {
    80  		fmt.Fprintf(GinkgoWriter, "chdir dir: %s\n", err)
    81  	}
    82  
    83  	cmd.Env = append(os.Environ(), "GO111MODULE=on")
    84  	command := strings.Join(cmd.Args, " ")
    85  	fmt.Fprintf(GinkgoWriter, "running: %s\n", command)
    86  	output, err := cmd.CombinedOutput()
    87  	if err != nil {
    88  		return output, fmt.Errorf("%s failed with error: (%v) %s", command, err, string(output))
    89  	}
    90  
    91  	return output, nil
    92  }
    93  
    94  // UninstallPrometheusOperator uninstalls the prometheus
    95  func UninstallPrometheusOperator() {
    96  	url := fmt.Sprintf(prometheusOperatorURL, prometheusOperatorVersion)
    97  	cmd := exec.Command("kubectl", "delete", "-f", url)
    98  	if _, err := Run(cmd); err != nil {
    99  		warnError(err)
   100  	}
   101  }
   102  
   103  // UninstallCertManager uninstalls the cert manager
   104  func UninstallCertManager() {
   105  	url := fmt.Sprintf(certmanagerURLTmpl, certmanagerVersion)
   106  	cmd := exec.Command("kubectl", "delete", "-f", url)
   107  	if _, err := Run(cmd); err != nil {
   108  		warnError(err)
   109  	}
   110  }
   111  
   112  // InstallCertManager installs the cert manager bundle.
   113  func InstallCertManager() error {
   114  	url := fmt.Sprintf(certmanagerURLTmpl, certmanagerVersion)
   115  	cmd := exec.Command("kubectl", "apply", "-f", url)
   116  	if _, err := Run(cmd); err != nil {
   117  		return err
   118  	}
   119  	// Wait for cert-manager-webhook to be ready, which can take time if cert-manager
   120  	// was re-installed after uninstalling on a cluster.
   121  	cmd = exec.Command("kubectl", "wait", "deployment.apps/cert-manager-webhook",
   122  		"--for", "condition=Available",
   123  		"--namespace", "cert-manager",
   124  		"--timeout", "5m",
   125  	)
   126  
   127  	_, err := Run(cmd)
   128  	return err
   129  }
   130  
   131  // LoadImageToKindCluster loads a local docker image to the kind cluster
   132  func LoadImageToKindClusterWithName(name string) error {
   133  	cluster := "kind"
   134  	if v, ok := os.LookupEnv("KIND_CLUSTER"); ok {
   135  		cluster = v
   136  	}
   137  	kindOptions := []string{"load", "docker-image", name, "--name", cluster}
   138  	cmd := exec.Command("kind", kindOptions...)
   139  	_, err := Run(cmd)
   140  	return err
   141  }
   142  
   143  // GetNonEmptyLines converts given command output string into individual objects
   144  // according to line breakers, and ignores the empty elements in it.
   145  func GetNonEmptyLines(output string) []string {
   146  	var res []string
   147  	elements := strings.Split(output, "\n")
   148  	for _, element := range elements {
   149  		if element != "" {
   150  			res = append(res, element)
   151  		}
   152  	}
   153  
   154  	return res
   155  }
   156  
   157  // GetProjectDir will return the directory where the project is
   158  func GetProjectDir() (string, error) {
   159  	wd, err := os.Getwd()
   160  	if err != nil {
   161  		return wd, err
   162  	}
   163  	wd = strings.Replace(wd, "/test/e2e", "", -1)
   164  	return wd, nil
   165  }
   166  `