util.go 5.8 KB

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