util.go 7.3 KB

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