fixtures.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package deployment
  14. import (
  15. "context"
  16. "fmt"
  17. "time"
  18. "github.com/onsi/ginkgo"
  19. apps "k8s.io/api/apps/v1"
  20. v1 "k8s.io/api/core/v1"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/util/uuid"
  23. "k8s.io/apimachinery/pkg/util/wait"
  24. "k8s.io/apimachinery/pkg/watch"
  25. clientset "k8s.io/client-go/kubernetes"
  26. watchtools "k8s.io/client-go/tools/watch"
  27. deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util"
  28. "k8s.io/kubernetes/test/e2e/framework"
  29. e2elog "k8s.io/kubernetes/test/e2e/framework/log"
  30. testutils "k8s.io/kubernetes/test/utils"
  31. imageutils "k8s.io/kubernetes/test/utils/image"
  32. )
  33. // UpdateDeploymentWithRetries updates the specified deployment with retries.
  34. func UpdateDeploymentWithRetries(c clientset.Interface, namespace, name string, applyUpdate testutils.UpdateDeploymentFunc) (*apps.Deployment, error) {
  35. return testutils.UpdateDeploymentWithRetries(c, namespace, name, applyUpdate, e2elog.Logf, poll, pollShortTimeout)
  36. }
  37. // CheckDeploymentRevisionAndImage checks if the input deployment's and its new replica set's revision and image are as expected.
  38. func CheckDeploymentRevisionAndImage(c clientset.Interface, ns, deploymentName, revision, image string) error {
  39. return testutils.CheckDeploymentRevisionAndImage(c, ns, deploymentName, revision, image)
  40. }
  41. // WatchRecreateDeployment watches Recreate deployments and ensures no new pods will run at the same time with
  42. // old pods.
  43. func WatchRecreateDeployment(c clientset.Interface, d *apps.Deployment) error {
  44. if d.Spec.Strategy.Type != apps.RecreateDeploymentStrategyType {
  45. return fmt.Errorf("deployment %q does not use a Recreate strategy: %s", d.Name, d.Spec.Strategy.Type)
  46. }
  47. w, err := c.AppsV1().Deployments(d.Namespace).Watch(metav1.SingleObject(metav1.ObjectMeta{Name: d.Name, ResourceVersion: d.ResourceVersion}))
  48. if err != nil {
  49. return err
  50. }
  51. status := d.Status
  52. condition := func(event watch.Event) (bool, error) {
  53. d := event.Object.(*apps.Deployment)
  54. status = d.Status
  55. if d.Status.UpdatedReplicas > 0 && d.Status.Replicas != d.Status.UpdatedReplicas {
  56. _, allOldRSs, err := deploymentutil.GetOldReplicaSets(d, c.AppsV1())
  57. newRS, nerr := deploymentutil.GetNewReplicaSet(d, c.AppsV1())
  58. if err == nil && nerr == nil {
  59. e2elog.Logf("%+v", d)
  60. logReplicaSetsOfDeployment(d, allOldRSs, newRS)
  61. logPodsOfDeployment(c, d, append(allOldRSs, newRS))
  62. }
  63. return false, fmt.Errorf("deployment %q is running new pods alongside old pods: %#v", d.Name, status)
  64. }
  65. return *(d.Spec.Replicas) == d.Status.Replicas &&
  66. *(d.Spec.Replicas) == d.Status.UpdatedReplicas &&
  67. d.Generation <= d.Status.ObservedGeneration, nil
  68. }
  69. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
  70. defer cancel()
  71. _, err = watchtools.UntilWithoutRetry(ctx, w, condition)
  72. if err == wait.ErrWaitTimeout {
  73. err = fmt.Errorf("deployment %q never completed: %#v", d.Name, status)
  74. }
  75. return err
  76. }
  77. // NewDeployment returns a deployment spec with the specified argument.
  78. func NewDeployment(deploymentName string, replicas int32, podLabels map[string]string, imageName, image string, strategyType apps.DeploymentStrategyType) *apps.Deployment {
  79. zero := int64(0)
  80. return &apps.Deployment{
  81. ObjectMeta: metav1.ObjectMeta{
  82. Name: deploymentName,
  83. Labels: podLabels,
  84. },
  85. Spec: apps.DeploymentSpec{
  86. Replicas: &replicas,
  87. Selector: &metav1.LabelSelector{MatchLabels: podLabels},
  88. Strategy: apps.DeploymentStrategy{
  89. Type: strategyType,
  90. },
  91. Template: v1.PodTemplateSpec{
  92. ObjectMeta: metav1.ObjectMeta{
  93. Labels: podLabels,
  94. },
  95. Spec: v1.PodSpec{
  96. TerminationGracePeriodSeconds: &zero,
  97. Containers: []v1.Container{
  98. {
  99. Name: imageName,
  100. Image: image,
  101. SecurityContext: &v1.SecurityContext{},
  102. },
  103. },
  104. },
  105. },
  106. },
  107. }
  108. }
  109. // CreateDeployment creates a deployment.
  110. func CreateDeployment(client clientset.Interface, replicas int32, podLabels map[string]string, nodeSelector map[string]string, namespace string, pvclaims []*v1.PersistentVolumeClaim, command string) (*apps.Deployment, error) {
  111. deploymentSpec := testDeployment(replicas, podLabels, nodeSelector, namespace, pvclaims, false, command)
  112. deployment, err := client.AppsV1().Deployments(namespace).Create(deploymentSpec)
  113. if err != nil {
  114. return nil, fmt.Errorf("deployment %q Create API error: %v", deploymentSpec.Name, err)
  115. }
  116. e2elog.Logf("Waiting deployment %q to complete", deploymentSpec.Name)
  117. err = WaitForDeploymentComplete(client, deployment)
  118. if err != nil {
  119. return nil, fmt.Errorf("deployment %q failed to complete: %v", deploymentSpec.Name, err)
  120. }
  121. return deployment, nil
  122. }
  123. // GetPodsForDeployment gets pods for the given deployment
  124. func GetPodsForDeployment(client clientset.Interface, deployment *apps.Deployment) (*v1.PodList, error) {
  125. replicaSet, err := deploymentutil.GetNewReplicaSet(deployment, client.AppsV1())
  126. if err != nil {
  127. return nil, fmt.Errorf("Failed to get new replica set for deployment %q: %v", deployment.Name, err)
  128. }
  129. if replicaSet == nil {
  130. return nil, fmt.Errorf("expected a new replica set for deployment %q, found none", deployment.Name)
  131. }
  132. podListFunc := func(namespace string, options metav1.ListOptions) (*v1.PodList, error) {
  133. return client.CoreV1().Pods(namespace).List(options)
  134. }
  135. rsList := []*apps.ReplicaSet{replicaSet}
  136. podList, err := deploymentutil.ListPods(deployment, rsList, podListFunc)
  137. if err != nil {
  138. return nil, fmt.Errorf("Failed to list Pods of Deployment %q: %v", deployment.Name, err)
  139. }
  140. return podList, nil
  141. }
  142. // RunDeployment runs a delopyment with the specified config.
  143. func RunDeployment(config testutils.DeploymentConfig) error {
  144. ginkgo.By(fmt.Sprintf("creating deployment %s in namespace %s", config.Name, config.Namespace))
  145. config.NodeDumpFunc = framework.DumpNodeDebugInfo
  146. config.ContainerDumpFunc = framework.LogFailedContainers
  147. return testutils.RunDeployment(config)
  148. }
  149. // testDeployment creates a deployment definition based on the namespace. The deployment references the PVC's
  150. // name. A slice of BASH commands can be supplied as args to be run by the pod
  151. func testDeployment(replicas int32, podLabels map[string]string, nodeSelector map[string]string, namespace string, pvclaims []*v1.PersistentVolumeClaim, isPrivileged bool, command string) *apps.Deployment {
  152. if len(command) == 0 {
  153. command = "trap exit TERM; while true; do sleep 1; done"
  154. }
  155. zero := int64(0)
  156. deploymentName := "deployment-" + string(uuid.NewUUID())
  157. deploymentSpec := &apps.Deployment{
  158. ObjectMeta: metav1.ObjectMeta{
  159. Name: deploymentName,
  160. Namespace: namespace,
  161. },
  162. Spec: apps.DeploymentSpec{
  163. Replicas: &replicas,
  164. Selector: &metav1.LabelSelector{
  165. MatchLabels: podLabels,
  166. },
  167. Template: v1.PodTemplateSpec{
  168. ObjectMeta: metav1.ObjectMeta{
  169. Labels: podLabels,
  170. },
  171. Spec: v1.PodSpec{
  172. TerminationGracePeriodSeconds: &zero,
  173. Containers: []v1.Container{
  174. {
  175. Name: "write-pod",
  176. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  177. Command: []string{"/bin/sh"},
  178. Args: []string{"-c", command},
  179. SecurityContext: &v1.SecurityContext{
  180. Privileged: &isPrivileged,
  181. },
  182. },
  183. },
  184. RestartPolicy: v1.RestartPolicyAlways,
  185. },
  186. },
  187. },
  188. }
  189. var volumeMounts = make([]v1.VolumeMount, len(pvclaims))
  190. var volumes = make([]v1.Volume, len(pvclaims))
  191. for index, pvclaim := range pvclaims {
  192. volumename := fmt.Sprintf("volume%v", index+1)
  193. volumeMounts[index] = v1.VolumeMount{Name: volumename, MountPath: "/mnt/" + volumename}
  194. volumes[index] = v1.Volume{Name: volumename, VolumeSource: v1.VolumeSource{PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ClaimName: pvclaim.Name, ReadOnly: false}}}
  195. }
  196. deploymentSpec.Spec.Template.Spec.Containers[0].VolumeMounts = volumeMounts
  197. deploymentSpec.Spec.Template.Spec.Volumes = volumes
  198. if nodeSelector != nil {
  199. deploymentSpec.Spec.Template.Spec.NodeSelector = nodeSelector
  200. }
  201. return deploymentSpec
  202. }