create.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. /*
  2. Copyright 2019 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 pod
  14. import (
  15. "context"
  16. "fmt"
  17. "time"
  18. v1 "k8s.io/api/core/v1"
  19. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. "k8s.io/apimachinery/pkg/util/uuid"
  21. clientset "k8s.io/client-go/kubernetes"
  22. imageutils "k8s.io/kubernetes/test/utils/image"
  23. )
  24. var (
  25. // BusyBoxImage is the image URI of BusyBox.
  26. BusyBoxImage = imageutils.GetE2EImage(imageutils.BusyBox)
  27. )
  28. // CreateUnschedulablePod with given claims based on node selector
  29. func CreateUnschedulablePod(client clientset.Interface, namespace string, nodeSelector map[string]string, pvclaims []*v1.PersistentVolumeClaim, isPrivileged bool, command string) (*v1.Pod, error) {
  30. pod := MakePod(namespace, nodeSelector, pvclaims, isPrivileged, command)
  31. pod, err := client.CoreV1().Pods(namespace).Create(context.TODO(), pod, metav1.CreateOptions{})
  32. if err != nil {
  33. return nil, fmt.Errorf("pod Create API error: %v", err)
  34. }
  35. // Waiting for pod to become Unschedulable
  36. err = WaitForPodNameUnschedulableInNamespace(client, pod.Name, namespace)
  37. if err != nil {
  38. return pod, fmt.Errorf("pod %q is not Unschedulable: %v", pod.Name, err)
  39. }
  40. // get fresh pod info
  41. pod, err = client.CoreV1().Pods(namespace).Get(context.TODO(), pod.Name, metav1.GetOptions{})
  42. if err != nil {
  43. return pod, fmt.Errorf("pod Get API error: %v", err)
  44. }
  45. return pod, nil
  46. }
  47. // CreateClientPod defines and creates a pod with a mounted PV. Pod runs infinite loop until killed.
  48. func CreateClientPod(c clientset.Interface, ns string, pvc *v1.PersistentVolumeClaim) (*v1.Pod, error) {
  49. return CreatePod(c, ns, nil, []*v1.PersistentVolumeClaim{pvc}, true, "")
  50. }
  51. // CreatePod with given claims based on node selector
  52. func CreatePod(client clientset.Interface, namespace string, nodeSelector map[string]string, pvclaims []*v1.PersistentVolumeClaim, isPrivileged bool, command string) (*v1.Pod, error) {
  53. pod := MakePod(namespace, nodeSelector, pvclaims, isPrivileged, command)
  54. pod, err := client.CoreV1().Pods(namespace).Create(context.TODO(), pod, metav1.CreateOptions{})
  55. if err != nil {
  56. return nil, fmt.Errorf("pod Create API error: %v", err)
  57. }
  58. // Waiting for pod to be running
  59. err = WaitForPodNameRunningInNamespace(client, pod.Name, namespace)
  60. if err != nil {
  61. return pod, fmt.Errorf("pod %q is not Running: %v", pod.Name, err)
  62. }
  63. // get fresh pod info
  64. pod, err = client.CoreV1().Pods(namespace).Get(context.TODO(), pod.Name, metav1.GetOptions{})
  65. if err != nil {
  66. return pod, fmt.Errorf("pod Get API error: %v", err)
  67. }
  68. return pod, nil
  69. }
  70. // CreateSecPod creates security pod with given claims
  71. func CreateSecPod(client clientset.Interface, namespace string, pvclaims []*v1.PersistentVolumeClaim, inlineVolumeSources []*v1.VolumeSource, isPrivileged bool, command string, hostIPC bool, hostPID bool, seLinuxLabel *v1.SELinuxOptions, fsGroup *int64, timeout time.Duration) (*v1.Pod, error) {
  72. return CreateSecPodWithNodeSelection(client, namespace, pvclaims, inlineVolumeSources, isPrivileged, command, hostIPC, hostPID, seLinuxLabel, fsGroup, NodeSelection{}, timeout)
  73. }
  74. // CreateSecPodWithNodeSelection creates security pod with given claims
  75. func CreateSecPodWithNodeSelection(client clientset.Interface, namespace string, pvclaims []*v1.PersistentVolumeClaim, inlineVolumeSources []*v1.VolumeSource, isPrivileged bool, command string, hostIPC bool, hostPID bool, seLinuxLabel *v1.SELinuxOptions, fsGroup *int64, node NodeSelection, timeout time.Duration) (*v1.Pod, error) {
  76. pod := MakeSecPod(namespace, pvclaims, inlineVolumeSources, isPrivileged, command, hostIPC, hostPID, seLinuxLabel, fsGroup)
  77. SetNodeSelection(pod, node)
  78. pod, err := client.CoreV1().Pods(namespace).Create(context.TODO(), pod, metav1.CreateOptions{})
  79. if err != nil {
  80. return nil, fmt.Errorf("pod Create API error: %v", err)
  81. }
  82. // Waiting for pod to be running
  83. err = WaitTimeoutForPodRunningInNamespace(client, pod.Name, namespace, timeout)
  84. if err != nil {
  85. return pod, fmt.Errorf("pod %q is not Running: %v", pod.Name, err)
  86. }
  87. // get fresh pod info
  88. pod, err = client.CoreV1().Pods(namespace).Get(context.TODO(), pod.Name, metav1.GetOptions{})
  89. if err != nil {
  90. return pod, fmt.Errorf("pod Get API error: %v", err)
  91. }
  92. return pod, nil
  93. }
  94. // MakePod returns a pod definition based on the namespace. The pod references the PVC's
  95. // name. A slice of BASH commands can be supplied as args to be run by the pod
  96. func MakePod(ns string, nodeSelector map[string]string, pvclaims []*v1.PersistentVolumeClaim, isPrivileged bool, command string) *v1.Pod {
  97. if len(command) == 0 {
  98. command = "trap exit TERM; while true; do sleep 1; done"
  99. }
  100. podSpec := &v1.Pod{
  101. TypeMeta: metav1.TypeMeta{
  102. Kind: "Pod",
  103. APIVersion: "v1",
  104. },
  105. ObjectMeta: metav1.ObjectMeta{
  106. GenerateName: "pvc-tester-",
  107. Namespace: ns,
  108. },
  109. Spec: v1.PodSpec{
  110. Containers: []v1.Container{
  111. {
  112. Name: "write-pod",
  113. Image: BusyBoxImage,
  114. Command: []string{"/bin/sh"},
  115. Args: []string{"-c", command},
  116. SecurityContext: &v1.SecurityContext{
  117. Privileged: &isPrivileged,
  118. },
  119. },
  120. },
  121. RestartPolicy: v1.RestartPolicyOnFailure,
  122. },
  123. }
  124. var volumeMounts = make([]v1.VolumeMount, len(pvclaims))
  125. var volumes = make([]v1.Volume, len(pvclaims))
  126. for index, pvclaim := range pvclaims {
  127. volumename := fmt.Sprintf("volume%v", index+1)
  128. volumeMounts[index] = v1.VolumeMount{Name: volumename, MountPath: "/mnt/" + volumename}
  129. volumes[index] = v1.Volume{Name: volumename, VolumeSource: v1.VolumeSource{PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ClaimName: pvclaim.Name, ReadOnly: false}}}
  130. }
  131. podSpec.Spec.Containers[0].VolumeMounts = volumeMounts
  132. podSpec.Spec.Volumes = volumes
  133. if nodeSelector != nil {
  134. podSpec.Spec.NodeSelector = nodeSelector
  135. }
  136. return podSpec
  137. }
  138. // MakeSecPod returns a pod definition based on the namespace. The pod references the PVC's
  139. // name. A slice of BASH commands can be supplied as args to be run by the pod.
  140. // SELinux testing requires to pass HostIPC and HostPID as booleansi arguments.
  141. func MakeSecPod(ns string, pvclaims []*v1.PersistentVolumeClaim, inlineVolumeSources []*v1.VolumeSource, isPrivileged bool, command string, hostIPC bool, hostPID bool, seLinuxLabel *v1.SELinuxOptions, fsGroup *int64) *v1.Pod {
  142. if len(command) == 0 {
  143. command = "trap exit TERM; while true; do sleep 1; done"
  144. }
  145. podName := "security-context-" + string(uuid.NewUUID())
  146. if fsGroup == nil {
  147. fsGroup = func(i int64) *int64 {
  148. return &i
  149. }(1000)
  150. }
  151. podSpec := &v1.Pod{
  152. TypeMeta: metav1.TypeMeta{
  153. Kind: "Pod",
  154. APIVersion: "v1",
  155. },
  156. ObjectMeta: metav1.ObjectMeta{
  157. Name: podName,
  158. Namespace: ns,
  159. },
  160. Spec: v1.PodSpec{
  161. HostIPC: hostIPC,
  162. HostPID: hostPID,
  163. SecurityContext: &v1.PodSecurityContext{
  164. FSGroup: fsGroup,
  165. },
  166. Containers: []v1.Container{
  167. {
  168. Name: "write-pod",
  169. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  170. Command: []string{"/bin/sh"},
  171. Args: []string{"-c", command},
  172. SecurityContext: &v1.SecurityContext{
  173. Privileged: &isPrivileged,
  174. },
  175. },
  176. },
  177. RestartPolicy: v1.RestartPolicyOnFailure,
  178. },
  179. }
  180. var volumeMounts = make([]v1.VolumeMount, 0)
  181. var volumeDevices = make([]v1.VolumeDevice, 0)
  182. var volumes = make([]v1.Volume, len(pvclaims)+len(inlineVolumeSources))
  183. volumeIndex := 0
  184. for _, pvclaim := range pvclaims {
  185. volumename := fmt.Sprintf("volume%v", volumeIndex+1)
  186. if pvclaim.Spec.VolumeMode != nil && *pvclaim.Spec.VolumeMode == v1.PersistentVolumeBlock {
  187. volumeDevices = append(volumeDevices, v1.VolumeDevice{Name: volumename, DevicePath: "/mnt/" + volumename})
  188. } else {
  189. volumeMounts = append(volumeMounts, v1.VolumeMount{Name: volumename, MountPath: "/mnt/" + volumename})
  190. }
  191. volumes[volumeIndex] = v1.Volume{Name: volumename, VolumeSource: v1.VolumeSource{PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ClaimName: pvclaim.Name, ReadOnly: false}}}
  192. volumeIndex++
  193. }
  194. for _, src := range inlineVolumeSources {
  195. volumename := fmt.Sprintf("volume%v", volumeIndex+1)
  196. // In-line volumes can be only filesystem, not block.
  197. volumeMounts = append(volumeMounts, v1.VolumeMount{Name: volumename, MountPath: "/mnt/" + volumename})
  198. volumes[volumeIndex] = v1.Volume{Name: volumename, VolumeSource: *src}
  199. volumeIndex++
  200. }
  201. podSpec.Spec.Containers[0].VolumeMounts = volumeMounts
  202. podSpec.Spec.Containers[0].VolumeDevices = volumeDevices
  203. podSpec.Spec.Volumes = volumes
  204. podSpec.Spec.SecurityContext.SELinuxOptions = seLinuxLabel
  205. return podSpec
  206. }