util.go 7.5 KB

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