util.go 9.0 KB

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