create.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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. // Setting node
  78. pod.Spec.NodeName = node.Name
  79. pod.Spec.NodeSelector = node.Selector
  80. pod.Spec.Affinity = node.Affinity
  81. pod, err := client.CoreV1().Pods(namespace).Create(context.TODO(), pod, metav1.CreateOptions{})
  82. if err != nil {
  83. return nil, fmt.Errorf("pod Create API error: %v", err)
  84. }
  85. // Waiting for pod to be running
  86. err = WaitTimeoutForPodRunningInNamespace(client, pod.Name, namespace, timeout)
  87. if err != nil {
  88. return pod, fmt.Errorf("pod %q is not Running: %v", pod.Name, err)
  89. }
  90. // get fresh pod info
  91. pod, err = client.CoreV1().Pods(namespace).Get(context.TODO(), pod.Name, metav1.GetOptions{})
  92. if err != nil {
  93. return pod, fmt.Errorf("pod Get API error: %v", err)
  94. }
  95. return pod, nil
  96. }
  97. // MakePod returns a pod definition based on the namespace. The pod references the PVC's
  98. // name. A slice of BASH commands can be supplied as args to be run by the pod
  99. func MakePod(ns string, nodeSelector map[string]string, pvclaims []*v1.PersistentVolumeClaim, isPrivileged bool, command string) *v1.Pod {
  100. if len(command) == 0 {
  101. command = "trap exit TERM; while true; do sleep 1; done"
  102. }
  103. podSpec := &v1.Pod{
  104. TypeMeta: metav1.TypeMeta{
  105. Kind: "Pod",
  106. APIVersion: "v1",
  107. },
  108. ObjectMeta: metav1.ObjectMeta{
  109. GenerateName: "pvc-tester-",
  110. Namespace: ns,
  111. },
  112. Spec: v1.PodSpec{
  113. Containers: []v1.Container{
  114. {
  115. Name: "write-pod",
  116. Image: BusyBoxImage,
  117. Command: []string{"/bin/sh"},
  118. Args: []string{"-c", command},
  119. SecurityContext: &v1.SecurityContext{
  120. Privileged: &isPrivileged,
  121. },
  122. },
  123. },
  124. RestartPolicy: v1.RestartPolicyOnFailure,
  125. },
  126. }
  127. var volumeMounts = make([]v1.VolumeMount, len(pvclaims))
  128. var volumes = make([]v1.Volume, len(pvclaims))
  129. for index, pvclaim := range pvclaims {
  130. volumename := fmt.Sprintf("volume%v", index+1)
  131. volumeMounts[index] = v1.VolumeMount{Name: volumename, MountPath: "/mnt/" + volumename}
  132. volumes[index] = v1.Volume{Name: volumename, VolumeSource: v1.VolumeSource{PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ClaimName: pvclaim.Name, ReadOnly: false}}}
  133. }
  134. podSpec.Spec.Containers[0].VolumeMounts = volumeMounts
  135. podSpec.Spec.Volumes = volumes
  136. if nodeSelector != nil {
  137. podSpec.Spec.NodeSelector = nodeSelector
  138. }
  139. return podSpec
  140. }
  141. // MakeSecPod returns a pod definition based on the namespace. The pod references the PVC's
  142. // name. A slice of BASH commands can be supplied as args to be run by the pod.
  143. // SELinux testing requires to pass HostIPC and HostPID as booleansi arguments.
  144. 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 {
  145. if len(command) == 0 {
  146. command = "trap exit TERM; while true; do sleep 1; done"
  147. }
  148. podName := "security-context-" + string(uuid.NewUUID())
  149. if fsGroup == nil {
  150. fsGroup = func(i int64) *int64 {
  151. return &i
  152. }(1000)
  153. }
  154. podSpec := &v1.Pod{
  155. TypeMeta: metav1.TypeMeta{
  156. Kind: "Pod",
  157. APIVersion: "v1",
  158. },
  159. ObjectMeta: metav1.ObjectMeta{
  160. Name: podName,
  161. Namespace: ns,
  162. },
  163. Spec: v1.PodSpec{
  164. HostIPC: hostIPC,
  165. HostPID: hostPID,
  166. SecurityContext: &v1.PodSecurityContext{
  167. FSGroup: fsGroup,
  168. },
  169. Containers: []v1.Container{
  170. {
  171. Name: "write-pod",
  172. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  173. Command: []string{"/bin/sh"},
  174. Args: []string{"-c", command},
  175. SecurityContext: &v1.SecurityContext{
  176. Privileged: &isPrivileged,
  177. },
  178. },
  179. },
  180. RestartPolicy: v1.RestartPolicyOnFailure,
  181. },
  182. }
  183. var volumeMounts = make([]v1.VolumeMount, 0)
  184. var volumeDevices = make([]v1.VolumeDevice, 0)
  185. var volumes = make([]v1.Volume, len(pvclaims)+len(inlineVolumeSources))
  186. volumeIndex := 0
  187. for _, pvclaim := range pvclaims {
  188. volumename := fmt.Sprintf("volume%v", volumeIndex+1)
  189. if pvclaim.Spec.VolumeMode != nil && *pvclaim.Spec.VolumeMode == v1.PersistentVolumeBlock {
  190. volumeDevices = append(volumeDevices, v1.VolumeDevice{Name: volumename, DevicePath: "/mnt/" + volumename})
  191. } else {
  192. volumeMounts = append(volumeMounts, v1.VolumeMount{Name: volumename, MountPath: "/mnt/" + volumename})
  193. }
  194. volumes[volumeIndex] = v1.Volume{Name: volumename, VolumeSource: v1.VolumeSource{PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ClaimName: pvclaim.Name, ReadOnly: false}}}
  195. volumeIndex++
  196. }
  197. for _, src := range inlineVolumeSources {
  198. volumename := fmt.Sprintf("volume%v", volumeIndex+1)
  199. // In-line volumes can be only filesystem, not block.
  200. volumeMounts = append(volumeMounts, v1.VolumeMount{Name: volumename, MountPath: "/mnt/" + volumename})
  201. volumes[volumeIndex] = v1.Volume{Name: volumename, VolumeSource: *src}
  202. volumeIndex++
  203. }
  204. podSpec.Spec.Containers[0].VolumeMounts = volumeMounts
  205. podSpec.Spec.Containers[0].VolumeDevices = volumeDevices
  206. podSpec.Spec.Volumes = volumes
  207. podSpec.Spec.SecurityContext.SELinuxOptions = seLinuxLabel
  208. return podSpec
  209. }