util.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /*
  2. Copyright © 2025 ESO Maintainer Team
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package util
  14. import (
  15. "bytes"
  16. "context"
  17. "fmt"
  18. "net/http"
  19. "os"
  20. "path/filepath"
  21. "time"
  22. fluxhelm "github.com/fluxcd/helm-controller/api/v2beta1"
  23. fluxsrc "github.com/fluxcd/source-controller/api/v1beta2"
  24. v1 "k8s.io/api/core/v1"
  25. apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  26. apierrors "k8s.io/apimachinery/pkg/api/errors"
  27. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  28. "k8s.io/apimachinery/pkg/runtime"
  29. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  30. "k8s.io/apimachinery/pkg/util/wait"
  31. "k8s.io/client-go/kubernetes"
  32. clientgoscheme "k8s.io/client-go/kubernetes/scheme"
  33. "k8s.io/client-go/rest"
  34. restclient "k8s.io/client-go/rest"
  35. "k8s.io/client-go/tools/clientcmd"
  36. "k8s.io/client-go/tools/remotecommand"
  37. "k8s.io/client-go/util/homedir"
  38. crclient "sigs.k8s.io/controller-runtime/pkg/client"
  39. // nolint
  40. . "github.com/onsi/ginkgo/v2"
  41. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  42. esv1alpha1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  43. genv1alpha1 "github.com/external-secrets/external-secrets/apis/generators/v1alpha1"
  44. )
  45. var scheme = runtime.NewScheme()
  46. func init() {
  47. // kubernetes schemes
  48. utilruntime.Must(clientgoscheme.AddToScheme(scheme))
  49. utilruntime.Must(apiextensionsv1.AddToScheme(scheme))
  50. // external-secrets schemes
  51. utilruntime.Must(esv1.AddToScheme(scheme))
  52. utilruntime.Must(esv1alpha1.AddToScheme(scheme))
  53. utilruntime.Must(genv1alpha1.AddToScheme(scheme))
  54. // other schemes
  55. utilruntime.Must(fluxhelm.AddToScheme(scheme))
  56. utilruntime.Must(fluxsrc.AddToScheme(scheme))
  57. }
  58. const (
  59. // How often to poll for conditions.
  60. Poll = 2 * time.Second
  61. )
  62. // CreateKubeNamespace creates a new Kubernetes Namespace for a test.
  63. func CreateKubeNamespace(baseName string, kubeClientSet kubernetes.Interface) (*v1.Namespace, error) {
  64. ns := &v1.Namespace{
  65. ObjectMeta: metav1.ObjectMeta{
  66. GenerateName: fmt.Sprintf("e2e-tests-%v-", baseName),
  67. },
  68. }
  69. return kubeClientSet.CoreV1().Namespaces().Create(GinkgoT().Context(), ns, metav1.CreateOptions{})
  70. }
  71. // DeleteKubeNamespace will delete a namespace resource.
  72. func DeleteKubeNamespace(namespace string, kubeClientSet kubernetes.Interface) error {
  73. return kubeClientSet.CoreV1().Namespaces().Delete(GinkgoT().Context(), namespace, metav1.DeleteOptions{})
  74. }
  75. // WaitForKubeNamespaceNotExist will wait for the namespace with the given name
  76. // to not exist for up to 2 minutes.
  77. func WaitForKubeNamespaceNotExist(namespace string, kubeClientSet kubernetes.Interface) error {
  78. return wait.PollUntilContextTimeout(GinkgoT().Context(), Poll, time.Minute*2, true, namespaceNotExist(kubeClientSet, namespace))
  79. }
  80. func namespaceNotExist(c kubernetes.Interface, namespace string) wait.ConditionWithContextFunc {
  81. return func(ctx context.Context) (bool, error) {
  82. _, err := c.CoreV1().Namespaces().Get(ctx, namespace, metav1.GetOptions{})
  83. if apierrors.IsNotFound(err) {
  84. return true, nil
  85. }
  86. if err != nil {
  87. return false, err
  88. }
  89. return false, nil
  90. }
  91. }
  92. // ExecCmd exec command on specific pod and wait the command's output.
  93. func ExecCmd(client kubernetes.Interface, config *restclient.Config, podName, namespace string,
  94. command string) (string, error) {
  95. return execCmd(client, config, podName, "", namespace, command)
  96. }
  97. // ExecCmdWithContainer exec command on specific container in a specific pod and wait the command's output.
  98. func ExecCmdWithContainer(client kubernetes.Interface, config *restclient.Config, podName, containerName, namespace string,
  99. command string) (string, error) {
  100. return execCmd(client, config, podName, containerName, namespace, command)
  101. }
  102. func execCmd(client kubernetes.Interface, config *restclient.Config, podName, containerName, namespace string,
  103. command string) (string, error) {
  104. cmd := []string{
  105. "sh",
  106. "-c",
  107. command,
  108. }
  109. req := client.CoreV1().RESTClient().Post().Resource("pods").Name(podName).
  110. Namespace(namespace).SubResource("exec")
  111. option := &v1.PodExecOptions{
  112. Command: cmd,
  113. Container: containerName,
  114. Stdin: false,
  115. Stdout: true,
  116. Stderr: true,
  117. TTY: false,
  118. }
  119. req.VersionedParams(
  120. option,
  121. clientgoscheme.ParameterCodec,
  122. )
  123. exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
  124. if err != nil {
  125. return "", err
  126. }
  127. var stdout, stderr bytes.Buffer
  128. err = exec.Stream(remotecommand.StreamOptions{
  129. Stdout: &stdout,
  130. Stderr: &stderr,
  131. Tty: false,
  132. })
  133. if err != nil {
  134. return "", fmt.Errorf("unable to exec stream: %w: \n%s\n%s", err, stdout.String(), stderr.String())
  135. }
  136. return stdout.String() + stderr.String(), nil
  137. }
  138. // WaitForPodsRunning waits for a given amount of time until a group of Pods is running in the given namespace.
  139. func WaitForPodsRunning(kubeClientSet kubernetes.Interface, expectedReplicas int, namespace string, opts metav1.ListOptions) (*v1.PodList, error) {
  140. var pods *v1.PodList
  141. err := wait.PollUntilContextTimeout(GinkgoT().Context(), 1*time.Second, time.Minute*5, true, func(ctx context.Context) (bool, error) {
  142. pl, err := kubeClientSet.CoreV1().Pods(namespace).List(ctx, opts)
  143. if err != nil {
  144. return false, nil
  145. }
  146. r := 0
  147. for i := range pl.Items {
  148. if pl.Items[i].Status.Phase == v1.PodRunning {
  149. r++
  150. }
  151. }
  152. if r == expectedReplicas {
  153. pods = pl
  154. return true, nil
  155. }
  156. return false, nil
  157. })
  158. return pods, err
  159. }
  160. // WaitForPodsReady waits for a given amount of time until a group of Pods is running in the given namespace.
  161. func WaitForPodsReady(kubeClientSet kubernetes.Interface, expectedReplicas int, namespace string, opts metav1.ListOptions) error {
  162. return wait.PollUntilContextTimeout(GinkgoT().Context(), 1*time.Second, time.Minute*5, true, func(ctx context.Context) (bool, error) {
  163. pl, err := kubeClientSet.CoreV1().Pods(namespace).List(ctx, opts)
  164. if err != nil {
  165. return false, nil
  166. }
  167. r := 0
  168. for i := range pl.Items {
  169. if isRunning, _ := podRunningReady(&pl.Items[i]); isRunning {
  170. r++
  171. }
  172. }
  173. if r == expectedReplicas {
  174. return true, nil
  175. }
  176. return false, nil
  177. })
  178. }
  179. // podRunningReady checks whether pod p's phase is running and it has a ready
  180. // condition of status true.
  181. func podRunningReady(p *v1.Pod) (bool, error) {
  182. // Check the phase is running.
  183. if p.Status.Phase != v1.PodRunning {
  184. return false, fmt.Errorf("want pod '%s' on '%s' to be '%v' but was '%v'",
  185. p.ObjectMeta.Name, p.Spec.NodeName, v1.PodRunning, p.Status.Phase)
  186. }
  187. // Check the ready condition is true.
  188. if !isPodReady(p) {
  189. return false, fmt.Errorf("pod '%s' on '%s' didn't have condition {%v %v}; conditions: %v",
  190. p.ObjectMeta.Name, p.Spec.NodeName, v1.PodReady, v1.ConditionTrue, p.Status.Conditions)
  191. }
  192. return true, nil
  193. }
  194. func isPodReady(p *v1.Pod) bool {
  195. for _, condition := range p.Status.Conditions {
  196. if condition.Type != v1.ContainersReady {
  197. continue
  198. }
  199. return condition.Status == v1.ConditionTrue
  200. }
  201. return false
  202. }
  203. // WaitForURL tests the provided url. Once a http 200 is returned the func returns with no error.
  204. // Timeout is 5min.
  205. func WaitForURL(url string) error {
  206. return wait.PollUntilContextTimeout(GinkgoT().Context(), 2*time.Second, time.Minute*5, true, func(ctx context.Context) (bool, error) {
  207. req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
  208. if err != nil {
  209. return false, nil
  210. }
  211. res, err := http.DefaultClient.Do(req)
  212. if err != nil {
  213. return false, nil
  214. }
  215. defer func() {
  216. _ = res.Body.Close()
  217. }()
  218. if res.StatusCode == http.StatusOK {
  219. return true, nil
  220. }
  221. return false, err
  222. })
  223. }
  224. // UpdateKubeSA updates a new Kubernetes Service Account for a test.
  225. func UpdateKubeSA(baseName string, kubeClientSet kubernetes.Interface, ns string, annotations map[string]string) (*v1.ServiceAccount, error) {
  226. sa := &v1.ServiceAccount{
  227. ObjectMeta: metav1.ObjectMeta{
  228. Name: baseName,
  229. Annotations: annotations,
  230. },
  231. }
  232. return kubeClientSet.CoreV1().ServiceAccounts(ns).Update(GinkgoT().Context(), sa, metav1.UpdateOptions{})
  233. }
  234. // UpdateKubeSA updates a new Kubernetes Service Account for a test.
  235. func GetKubeSA(baseName string, kubeClientSet kubernetes.Interface, ns string) (*v1.ServiceAccount, error) {
  236. return kubeClientSet.CoreV1().ServiceAccounts(ns).Get(GinkgoT().Context(), baseName, metav1.GetOptions{})
  237. }
  238. func GetKubeSecret(client kubernetes.Interface, namespace, secretName string) (*v1.Secret, error) {
  239. return client.CoreV1().Secrets(namespace).Get(GinkgoT().Context(), secretName, metav1.GetOptions{})
  240. }
  241. // NewConfig loads and returns the kubernetes credentials from the environment.
  242. // KUBECONFIG env var takes precedence, falls back to in-cluster config, then to default KUBECONFIG location.
  243. func NewConfig() (*restclient.Config, *kubernetes.Clientset, crclient.Client) {
  244. cfg, err := BuildKubeConfig()
  245. if err != nil {
  246. Fail(err.Error())
  247. }
  248. kubeClientSet, err := kubernetes.NewForConfig(cfg)
  249. if err != nil {
  250. Fail(err.Error())
  251. }
  252. CRClient, err := crclient.New(cfg, crclient.Options{Scheme: scheme})
  253. if err != nil {
  254. Fail(err.Error())
  255. }
  256. return cfg, kubeClientSet, CRClient
  257. }
  258. func BuildKubeConfig() (*rest.Config, error) {
  259. // 1. If KUBECONFIG is explicitly set, use it
  260. if kubeconfigEnv := os.Getenv("KUBECONFIG"); kubeconfigEnv != "" {
  261. cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfigEnv)
  262. if err == nil {
  263. return cfg, nil
  264. }
  265. return nil, fmt.Errorf("failed to load KUBECONFIG=%s: %w", kubeconfigEnv, err)
  266. }
  267. // 2. Try default kubeconfig location (~/.kube/config)
  268. if home := homedir.HomeDir(); home != "" {
  269. kubeconfigPath := filepath.Join(home, ".kube", "config")
  270. if _, err := os.Stat(kubeconfigPath); err == nil {
  271. cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfigPath)
  272. if err == nil {
  273. return cfg, nil
  274. }
  275. return nil, fmt.Errorf("failed to load default kubeconfig: %w", err)
  276. }
  277. }
  278. // 3. Fallback to in-cluster config
  279. cfg, err := rest.InClusterConfig()
  280. if err != nil {
  281. return nil, fmt.Errorf("failed to load in-cluster config: %w", err)
  282. }
  283. return cfg, nil
  284. }