util.go 9.3 KB

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