util.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. "time"
  21. fluxhelm "github.com/fluxcd/helm-controller/api/v2beta1"
  22. fluxsrc "github.com/fluxcd/source-controller/api/v1beta2"
  23. v1 "k8s.io/api/core/v1"
  24. apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  25. apierrors "k8s.io/apimachinery/pkg/api/errors"
  26. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  27. "k8s.io/apimachinery/pkg/runtime"
  28. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  29. "k8s.io/apimachinery/pkg/util/wait"
  30. "k8s.io/client-go/kubernetes"
  31. clientgoscheme "k8s.io/client-go/kubernetes/scheme"
  32. restclient "k8s.io/client-go/rest"
  33. "k8s.io/client-go/tools/clientcmd"
  34. "k8s.io/client-go/tools/remotecommand"
  35. crclient "sigs.k8s.io/controller-runtime/pkg/client"
  36. // nolint
  37. . "github.com/onsi/ginkgo/v2"
  38. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  39. esv1alpha1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  40. genv1alpha1 "github.com/external-secrets/external-secrets/apis/generators/v1alpha1"
  41. )
  42. var scheme = runtime.NewScheme()
  43. func init() {
  44. // kubernetes schemes
  45. utilruntime.Must(clientgoscheme.AddToScheme(scheme))
  46. utilruntime.Must(apiextensionsv1.AddToScheme(scheme))
  47. // external-secrets schemes
  48. utilruntime.Must(esv1.AddToScheme(scheme))
  49. utilruntime.Must(esv1alpha1.AddToScheme(scheme))
  50. utilruntime.Must(genv1alpha1.AddToScheme(scheme))
  51. // other schemes
  52. utilruntime.Must(fluxhelm.AddToScheme(scheme))
  53. utilruntime.Must(fluxsrc.AddToScheme(scheme))
  54. }
  55. const (
  56. // How often to poll for conditions.
  57. Poll = 2 * time.Second
  58. )
  59. // CreateKubeNamespace creates a new Kubernetes Namespace for a test.
  60. func CreateKubeNamespace(baseName string, kubeClientSet kubernetes.Interface) (*v1.Namespace, error) {
  61. ns := &v1.Namespace{
  62. ObjectMeta: metav1.ObjectMeta{
  63. GenerateName: fmt.Sprintf("e2e-tests-%v-", baseName),
  64. },
  65. }
  66. return kubeClientSet.CoreV1().Namespaces().Create(context.TODO(), ns, metav1.CreateOptions{})
  67. }
  68. // DeleteKubeNamespace will delete a namespace resource.
  69. func DeleteKubeNamespace(namespace string, kubeClientSet kubernetes.Interface) error {
  70. return kubeClientSet.CoreV1().Namespaces().Delete(context.TODO(), namespace, metav1.DeleteOptions{})
  71. }
  72. // WaitForKubeNamespaceNotExist will wait for the namespace with the given name
  73. // to not exist for up to 2 minutes.
  74. func WaitForKubeNamespaceNotExist(namespace string, kubeClientSet kubernetes.Interface) error {
  75. return wait.PollImmediate(Poll, time.Minute*2, namespaceNotExist(kubeClientSet, namespace))
  76. }
  77. func namespaceNotExist(c kubernetes.Interface, namespace string) wait.ConditionFunc {
  78. return func() (bool, error) {
  79. _, err := c.CoreV1().Namespaces().Get(context.TODO(), namespace, metav1.GetOptions{})
  80. if apierrors.IsNotFound(err) {
  81. return true, nil
  82. }
  83. if err != nil {
  84. return false, err
  85. }
  86. return false, nil
  87. }
  88. }
  89. // ExecCmd exec command on specific pod and wait the command's output.
  90. func ExecCmd(client kubernetes.Interface, config *restclient.Config, podName, namespace string,
  91. command string) (string, error) {
  92. return execCmd(client, config, podName, "", namespace, command)
  93. }
  94. // ExecCmdWithContainer exec command on specific container in a specific pod and wait the command's output.
  95. func ExecCmdWithContainer(client kubernetes.Interface, config *restclient.Config, podName, containerName, namespace string,
  96. command string) (string, error) {
  97. return execCmd(client, config, podName, containerName, namespace, command)
  98. }
  99. func execCmd(client kubernetes.Interface, config *restclient.Config, podName, containerName, namespace string,
  100. command string) (string, error) {
  101. cmd := []string{
  102. "sh",
  103. "-c",
  104. command,
  105. }
  106. req := client.CoreV1().RESTClient().Post().Resource("pods").Name(podName).
  107. Namespace(namespace).SubResource("exec")
  108. option := &v1.PodExecOptions{
  109. Command: cmd,
  110. Container: containerName,
  111. Stdin: false,
  112. Stdout: true,
  113. Stderr: true,
  114. TTY: false,
  115. }
  116. req.VersionedParams(
  117. option,
  118. clientgoscheme.ParameterCodec,
  119. )
  120. exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
  121. if err != nil {
  122. return "", err
  123. }
  124. var stdout, stderr bytes.Buffer
  125. err = exec.Stream(remotecommand.StreamOptions{
  126. Stdout: &stdout,
  127. Stderr: &stderr,
  128. Tty: false,
  129. })
  130. if err != nil {
  131. return "", fmt.Errorf("unable to exec stream: %w: \n%s\n%s", err, stdout.String(), stderr.String())
  132. }
  133. return stdout.String() + stderr.String(), nil
  134. }
  135. // WaitForPodsRunning waits for a given amount of time until a group of Pods is running in the given namespace.
  136. func WaitForPodsRunning(kubeClientSet kubernetes.Interface, expectedReplicas int, namespace string, opts metav1.ListOptions) (*v1.PodList, error) {
  137. var pods *v1.PodList
  138. err := wait.PollImmediate(1*time.Second, time.Minute*5, func() (bool, error) {
  139. pl, err := kubeClientSet.CoreV1().Pods(namespace).List(context.TODO(), opts)
  140. if err != nil {
  141. return false, nil
  142. }
  143. r := 0
  144. for i := range pl.Items {
  145. if pl.Items[i].Status.Phase == v1.PodRunning {
  146. r++
  147. }
  148. }
  149. if r == expectedReplicas {
  150. pods = pl
  151. return true, nil
  152. }
  153. return false, nil
  154. })
  155. return pods, err
  156. }
  157. // WaitForPodsReady waits for a given amount of time until a group of Pods is running in the given namespace.
  158. func WaitForPodsReady(kubeClientSet kubernetes.Interface, expectedReplicas int, namespace string, opts metav1.ListOptions) error {
  159. return wait.PollImmediate(1*time.Second, time.Minute*5, func() (bool, error) {
  160. pl, err := kubeClientSet.CoreV1().Pods(namespace).List(context.TODO(), opts)
  161. if err != nil {
  162. return false, nil
  163. }
  164. r := 0
  165. for i := range pl.Items {
  166. if isRunning, _ := podRunningReady(&pl.Items[i]); isRunning {
  167. r++
  168. }
  169. }
  170. if r == expectedReplicas {
  171. return true, nil
  172. }
  173. return false, nil
  174. })
  175. }
  176. // podRunningReady checks whether pod p's phase is running and it has a ready
  177. // condition of status true.
  178. func podRunningReady(p *v1.Pod) (bool, error) {
  179. // Check the phase is running.
  180. if p.Status.Phase != v1.PodRunning {
  181. return false, fmt.Errorf("want pod '%s' on '%s' to be '%v' but was '%v'",
  182. p.ObjectMeta.Name, p.Spec.NodeName, v1.PodRunning, p.Status.Phase)
  183. }
  184. // Check the ready condition is true.
  185. if !isPodReady(p) {
  186. return false, fmt.Errorf("pod '%s' on '%s' didn't have condition {%v %v}; conditions: %v",
  187. p.ObjectMeta.Name, p.Spec.NodeName, v1.PodReady, v1.ConditionTrue, p.Status.Conditions)
  188. }
  189. return true, nil
  190. }
  191. func isPodReady(p *v1.Pod) bool {
  192. for _, condition := range p.Status.Conditions {
  193. if condition.Type != v1.ContainersReady {
  194. continue
  195. }
  196. return condition.Status == v1.ConditionTrue
  197. }
  198. return false
  199. }
  200. // WaitForURL tests the provided url. Once a http 200 is returned the func returns with no error.
  201. // Timeout is 5min.
  202. func WaitForURL(url string) error {
  203. return wait.PollImmediate(2*time.Second, time.Minute*5, func() (bool, error) {
  204. req, err := http.NewRequest(http.MethodGet, url, http.NoBody)
  205. if err != nil {
  206. return false, nil
  207. }
  208. res, err := http.DefaultClient.Do(req)
  209. if err != nil {
  210. return false, nil
  211. }
  212. defer func() {
  213. _ = res.Body.Close()
  214. }()
  215. if res.StatusCode == http.StatusOK {
  216. return true, nil
  217. }
  218. return false, err
  219. })
  220. }
  221. // UpdateKubeSA updates a new Kubernetes Service Account for a test.
  222. func UpdateKubeSA(baseName string, kubeClientSet kubernetes.Interface, ns string, annotations map[string]string) (*v1.ServiceAccount, error) {
  223. sa := &v1.ServiceAccount{
  224. ObjectMeta: metav1.ObjectMeta{
  225. Name: baseName,
  226. Annotations: annotations,
  227. },
  228. }
  229. return kubeClientSet.CoreV1().ServiceAccounts(ns).Update(context.TODO(), sa, metav1.UpdateOptions{})
  230. }
  231. // UpdateKubeSA updates a new Kubernetes Service Account for a test.
  232. func GetKubeSA(baseName string, kubeClientSet kubernetes.Interface, ns string) (*v1.ServiceAccount, error) {
  233. return kubeClientSet.CoreV1().ServiceAccounts(ns).Get(context.TODO(), baseName, metav1.GetOptions{})
  234. }
  235. func GetKubeSecret(client kubernetes.Interface, namespace, secretName string) (*v1.Secret, error) {
  236. return client.CoreV1().Secrets(namespace).Get(context.TODO(), secretName, metav1.GetOptions{})
  237. }
  238. // NewConfig loads and returns the kubernetes credentials from the environment.
  239. // KUBECONFIG env var takes precedence and falls back to in-cluster config.
  240. func NewConfig() (*restclient.Config, *kubernetes.Clientset, crclient.Client) {
  241. var kubeConfig *restclient.Config
  242. var err error
  243. kcPath := os.Getenv("KUBECONFIG")
  244. if kcPath != "" {
  245. kubeConfig, err = clientcmd.BuildConfigFromFlags("", kcPath)
  246. if err != nil {
  247. Fail(err.Error())
  248. }
  249. } else {
  250. kubeConfig, err = restclient.InClusterConfig()
  251. if err != nil {
  252. Fail(err.Error())
  253. }
  254. }
  255. kubeClientSet, err := kubernetes.NewForConfig(kubeConfig)
  256. if err != nil {
  257. Fail(err.Error())
  258. }
  259. CRClient, err := crclient.New(kubeConfig, crclient.Options{Scheme: scheme})
  260. if err != nil {
  261. Fail(err.Error())
  262. }
  263. return kubeConfig, kubeClientSet, CRClient
  264. }