util.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. /*
  2. Copyright 2016 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 common
  14. import (
  15. "bytes"
  16. "context"
  17. "fmt"
  18. "text/template"
  19. "time"
  20. v1 "k8s.io/api/core/v1"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/util/intstr"
  23. "k8s.io/apimachinery/pkg/util/sets"
  24. "k8s.io/apimachinery/pkg/util/wait"
  25. clientset "k8s.io/client-go/kubernetes"
  26. "k8s.io/kubernetes/test/e2e/framework"
  27. e2erc "k8s.io/kubernetes/test/e2e/framework/rc"
  28. imageutils "k8s.io/kubernetes/test/utils/image"
  29. "github.com/onsi/ginkgo"
  30. )
  31. // Suite represents test suite.
  32. type Suite string
  33. const (
  34. // E2E represents a test suite for e2e.
  35. E2E Suite = "e2e"
  36. // NodeE2E represents a test suite for node e2e.
  37. NodeE2E Suite = "node e2e"
  38. )
  39. var (
  40. // non-Administrator Windows user used in tests. This is the Windows equivalent of the Linux non-root UID usage.
  41. nonAdminTestUserName = "ContainerUser"
  42. // non-root UID used in tests.
  43. nonRootTestUserID = int64(1000)
  44. )
  45. // CurrentSuite represents current test suite.
  46. var CurrentSuite Suite
  47. // CommonImageWhiteList is the list of images used in common test. These images should be prepulled
  48. // before a tests starts, so that the tests won't fail due image pulling flakes. Currently, this is
  49. // only used by node e2e test.
  50. // TODO(random-liu): Change the image puller pod to use similar mechanism.
  51. var CommonImageWhiteList = sets.NewString(
  52. imageutils.GetE2EImage(imageutils.Agnhost),
  53. imageutils.GetE2EImage(imageutils.BusyBox),
  54. imageutils.GetE2EImage(imageutils.IpcUtils),
  55. imageutils.GetE2EImage(imageutils.Mounttest),
  56. imageutils.GetE2EImage(imageutils.MounttestUser),
  57. imageutils.GetE2EImage(imageutils.Nginx),
  58. imageutils.GetE2EImage(imageutils.Httpd),
  59. imageutils.GetE2EImage(imageutils.VolumeNFSServer),
  60. imageutils.GetE2EImage(imageutils.VolumeGlusterServer),
  61. imageutils.GetE2EImage(imageutils.NonRoot),
  62. )
  63. type testImagesStruct struct {
  64. AgnhostImage string
  65. BusyBoxImage string
  66. KittenImage string
  67. MounttestImage string
  68. NautilusImage string
  69. NginxImage string
  70. NginxNewImage string
  71. HttpdImage string
  72. HttpdNewImage string
  73. PauseImage string
  74. RedisImage string
  75. }
  76. var testImages testImagesStruct
  77. func init() {
  78. testImages = testImagesStruct{
  79. imageutils.GetE2EImage(imageutils.Agnhost),
  80. imageutils.GetE2EImage(imageutils.BusyBox),
  81. imageutils.GetE2EImage(imageutils.Kitten),
  82. imageutils.GetE2EImage(imageutils.Mounttest),
  83. imageutils.GetE2EImage(imageutils.Nautilus),
  84. imageutils.GetE2EImage(imageutils.Nginx),
  85. imageutils.GetE2EImage(imageutils.NginxNew),
  86. imageutils.GetE2EImage(imageutils.Httpd),
  87. imageutils.GetE2EImage(imageutils.HttpdNew),
  88. imageutils.GetE2EImage(imageutils.Pause),
  89. imageutils.GetE2EImage(imageutils.Redis),
  90. }
  91. }
  92. // SubstituteImageName replaces image name in content.
  93. func SubstituteImageName(content string) string {
  94. contentWithImageName := new(bytes.Buffer)
  95. tmpl, err := template.New("imagemanifest").Parse(content)
  96. if err != nil {
  97. framework.Failf("Failed Parse the template: %v", err)
  98. }
  99. err = tmpl.Execute(contentWithImageName, testImages)
  100. if err != nil {
  101. framework.Failf("Failed executing template: %v", err)
  102. }
  103. return contentWithImageName.String()
  104. }
  105. func svcByName(name string, port int) *v1.Service {
  106. return &v1.Service{
  107. ObjectMeta: metav1.ObjectMeta{
  108. Name: name,
  109. },
  110. Spec: v1.ServiceSpec{
  111. Type: v1.ServiceTypeNodePort,
  112. Selector: map[string]string{
  113. "name": name,
  114. },
  115. Ports: []v1.ServicePort{{
  116. Port: int32(port),
  117. TargetPort: intstr.FromInt(port),
  118. }},
  119. },
  120. }
  121. }
  122. // NewSVCByName creates a service by name.
  123. func NewSVCByName(c clientset.Interface, ns, name string) error {
  124. const testPort = 9376
  125. _, err := c.CoreV1().Services(ns).Create(context.TODO(), svcByName(name, testPort), metav1.CreateOptions{})
  126. return err
  127. }
  128. // NewRCByName creates a replication controller with a selector by name of name.
  129. func NewRCByName(c clientset.Interface, ns, name string, replicas int32, gracePeriod *int64, containerArgs []string) (*v1.ReplicationController, error) {
  130. ginkgo.By(fmt.Sprintf("creating replication controller %s", name))
  131. if containerArgs == nil {
  132. containerArgs = []string{"serve-hostname"}
  133. }
  134. return c.CoreV1().ReplicationControllers(ns).Create(context.TODO(), rcByNamePort(
  135. name, replicas, framework.ServeHostnameImage, containerArgs, 9376, v1.ProtocolTCP, map[string]string{}, gracePeriod), metav1.CreateOptions{})
  136. }
  137. // RestartNodes restarts specific nodes.
  138. func RestartNodes(c clientset.Interface, nodes []v1.Node) error {
  139. // Build mapping from zone to nodes in that zone.
  140. nodeNamesByZone := make(map[string][]string)
  141. for i := range nodes {
  142. node := &nodes[i]
  143. zone := framework.TestContext.CloudConfig.Zone
  144. if z, ok := node.Labels[v1.LabelZoneFailureDomain]; ok {
  145. zone = z
  146. }
  147. nodeNamesByZone[zone] = append(nodeNamesByZone[zone], node.Name)
  148. }
  149. // Reboot the nodes.
  150. for zone, nodeNames := range nodeNamesByZone {
  151. args := []string{
  152. "compute",
  153. fmt.Sprintf("--project=%s", framework.TestContext.CloudConfig.ProjectID),
  154. "instances",
  155. "reset",
  156. }
  157. args = append(args, nodeNames...)
  158. args = append(args, fmt.Sprintf("--zone=%s", zone))
  159. stdout, stderr, err := framework.RunCmd("gcloud", args...)
  160. if err != nil {
  161. return fmt.Errorf("error restarting nodes: %s\nstdout: %s\nstderr: %s", err, stdout, stderr)
  162. }
  163. }
  164. // Wait for their boot IDs to change.
  165. for i := range nodes {
  166. node := &nodes[i]
  167. if err := wait.Poll(30*time.Second, framework.RestartNodeReadyAgainTimeout, func() (bool, error) {
  168. newNode, err := c.CoreV1().Nodes().Get(context.TODO(), node.Name, metav1.GetOptions{})
  169. if err != nil {
  170. return false, fmt.Errorf("error getting node info after reboot: %s", err)
  171. }
  172. return node.Status.NodeInfo.BootID != newNode.Status.NodeInfo.BootID, nil
  173. }); err != nil {
  174. return fmt.Errorf("error waiting for node %s boot ID to change: %s", node.Name, err)
  175. }
  176. }
  177. return nil
  178. }
  179. // rcByNamePort returns a ReplicationController with specified name and port
  180. func rcByNamePort(name string, replicas int32, image string, containerArgs []string, port int, protocol v1.Protocol,
  181. labels map[string]string, gracePeriod *int64) *v1.ReplicationController {
  182. return e2erc.ByNameContainer(name, replicas, labels, v1.Container{
  183. Name: name,
  184. Image: image,
  185. Args: containerArgs,
  186. Ports: []v1.ContainerPort{{ContainerPort: int32(port), Protocol: protocol}},
  187. }, gracePeriod)
  188. }
  189. // setPodNonRootUser configures the Pod to run as a non-root user.
  190. // For Windows, it sets the RunAsUserName field to ContainerUser, and for Linux, it sets the RunAsUser field to 1000.
  191. func setPodNonRootUser(pod *v1.Pod) {
  192. if framework.NodeOSDistroIs("windows") {
  193. pod.Spec.SecurityContext.WindowsOptions = &v1.WindowsSecurityContextOptions{RunAsUserName: &nonAdminTestUserName}
  194. } else {
  195. pod.Spec.SecurityContext.RunAsUser = &nonRootTestUserID
  196. }
  197. }