fixtures.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  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. /*
  14. * This test checks that various VolumeSources are working.
  15. *
  16. * There are two ways, how to test the volumes:
  17. * 1) With containerized server (NFS, Ceph, Gluster, iSCSI, ...)
  18. * The test creates a server pod, exporting simple 'index.html' file.
  19. * Then it uses appropriate VolumeSource to import this file into a client pod
  20. * and checks that the pod can see the file. It does so by importing the file
  21. * into web server root and loadind the index.html from it.
  22. *
  23. * These tests work only when privileged containers are allowed, exporting
  24. * various filesystems (NFS, GlusterFS, ...) usually needs some mounting or
  25. * other privileged magic in the server pod.
  26. *
  27. * Note that the server containers are for testing purposes only and should not
  28. * be used in production.
  29. *
  30. * 2) With server outside of Kubernetes (Cinder, ...)
  31. * Appropriate server (e.g. OpenStack Cinder) must exist somewhere outside
  32. * the tested Kubernetes cluster. The test itself creates a new volume,
  33. * and checks, that Kubernetes can use it as a volume.
  34. */
  35. package volume
  36. import (
  37. "fmt"
  38. "path/filepath"
  39. "strconv"
  40. "time"
  41. "k8s.io/api/core/v1"
  42. apierrs "k8s.io/apimachinery/pkg/api/errors"
  43. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  44. "k8s.io/apimachinery/pkg/util/rand"
  45. clientset "k8s.io/client-go/kubernetes"
  46. "k8s.io/kubernetes/test/e2e/framework"
  47. e2elog "k8s.io/kubernetes/test/e2e/framework/log"
  48. imageutils "k8s.io/kubernetes/test/utils/image"
  49. "github.com/onsi/ginkgo"
  50. "github.com/onsi/gomega"
  51. )
  52. const (
  53. // Kb is byte size of kilobyte
  54. Kb int64 = 1000
  55. // Mb is byte size of megabyte
  56. Mb int64 = 1000 * Kb
  57. // Gb is byte size of gigabyte
  58. Gb int64 = 1000 * Mb
  59. // Tb is byte size of terabyte
  60. Tb int64 = 1000 * Gb
  61. // KiB is byte size of kibibyte
  62. KiB int64 = 1024
  63. // MiB is byte size of mebibyte
  64. MiB int64 = 1024 * KiB
  65. // GiB is byte size of gibibyte
  66. GiB int64 = 1024 * MiB
  67. // TiB is byte size of tebibyte
  68. TiB int64 = 1024 * GiB
  69. // VolumeServerPodStartupTimeout is a waiting period for volume server (Ceph, ...) to initialize itself.
  70. VolumeServerPodStartupTimeout = 3 * time.Minute
  71. // PodCleanupTimeout is a waiting period for pod to be cleaned up and unmount its volumes so we
  72. // don't tear down containers with NFS/Ceph/Gluster server too early.
  73. PodCleanupTimeout = 20 * time.Second
  74. // Template for iSCSI IQN.
  75. iSCSIIQNTemplate = "iqn.2003-01.io.k8s:e2e.%s"
  76. )
  77. // TestConfig is a struct for configuration of one tests. The test consist of:
  78. // - server pod - runs serverImage, exports ports[]
  79. // - client pod - does not need any special configuration
  80. type TestConfig struct {
  81. Namespace string
  82. // Prefix of all pods. Typically the test name.
  83. Prefix string
  84. // Name of container image for the server pod.
  85. ServerImage string
  86. // Ports to export from the server pod. TCP only.
  87. ServerPorts []int
  88. // Commands to run in the container image.
  89. ServerCmds []string
  90. // Arguments to pass to the container image.
  91. ServerArgs []string
  92. // Volumes needed to be mounted to the server container from the host
  93. // map <host (source) path> -> <container (dst.) path>
  94. // if <host (source) path> is empty, mount a tmpfs emptydir
  95. ServerVolumes map[string]string
  96. // Message to wait for before starting clients
  97. ServerReadyMessage string
  98. // Use HostNetwork for the server
  99. ServerHostNetwork bool
  100. // Wait for the pod to terminate successfully
  101. // False indicates that the pod is long running
  102. WaitForCompletion bool
  103. // ServerNodeName is the spec.nodeName to run server pod on. Default is any node.
  104. ServerNodeName string
  105. // ClientNodeName is the spec.nodeName to run client pod on. Default is any node.
  106. ClientNodeName string
  107. // NodeSelector to use in pod spec (server, client and injector pods).
  108. NodeSelector map[string]string
  109. }
  110. // Test contains a volume to mount into a client pod and its
  111. // expected content.
  112. type Test struct {
  113. Volume v1.VolumeSource
  114. File string
  115. ExpectedContent string
  116. }
  117. // NewNFSServer is a NFS-specific wrapper for CreateStorageServer.
  118. func NewNFSServer(cs clientset.Interface, namespace string, args []string) (config TestConfig, pod *v1.Pod, ip string) {
  119. config = TestConfig{
  120. Namespace: namespace,
  121. Prefix: "nfs",
  122. ServerImage: imageutils.GetE2EImage(imageutils.VolumeNFSServer),
  123. ServerPorts: []int{2049},
  124. ServerVolumes: map[string]string{"": "/exports"},
  125. ServerReadyMessage: "NFS started",
  126. }
  127. if len(args) > 0 {
  128. config.ServerArgs = args
  129. }
  130. pod, ip = CreateStorageServer(cs, config)
  131. return config, pod, ip
  132. }
  133. // NewGlusterfsServer is a GlusterFS-specific wrapper for CreateStorageServer. Also creates the gluster endpoints object.
  134. func NewGlusterfsServer(cs clientset.Interface, namespace string) (config TestConfig, pod *v1.Pod, ip string) {
  135. config = TestConfig{
  136. Namespace: namespace,
  137. Prefix: "gluster",
  138. ServerImage: imageutils.GetE2EImage(imageutils.VolumeGlusterServer),
  139. ServerPorts: []int{24007, 24008, 49152},
  140. }
  141. pod, ip = CreateStorageServer(cs, config)
  142. ginkgo.By("creating Gluster endpoints")
  143. endpoints := &v1.Endpoints{
  144. TypeMeta: metav1.TypeMeta{
  145. Kind: "Endpoints",
  146. APIVersion: "v1",
  147. },
  148. ObjectMeta: metav1.ObjectMeta{
  149. Name: config.Prefix + "-server",
  150. },
  151. Subsets: []v1.EndpointSubset{
  152. {
  153. Addresses: []v1.EndpointAddress{
  154. {
  155. IP: ip,
  156. },
  157. },
  158. Ports: []v1.EndpointPort{
  159. {
  160. Name: "gluster",
  161. Port: 24007,
  162. Protocol: v1.ProtocolTCP,
  163. },
  164. },
  165. },
  166. },
  167. }
  168. endpoints, err := cs.CoreV1().Endpoints(namespace).Create(endpoints)
  169. framework.ExpectNoError(err, "failed to create endpoints for Gluster server")
  170. return config, pod, ip
  171. }
  172. // NewISCSIServer is an iSCSI-specific wrapper for CreateStorageServer.
  173. func NewISCSIServer(cs clientset.Interface, namespace string) (config TestConfig, pod *v1.Pod, ip, iqn string) {
  174. // Generate cluster-wide unique IQN
  175. iqn = fmt.Sprintf(iSCSIIQNTemplate, namespace)
  176. config = TestConfig{
  177. Namespace: namespace,
  178. Prefix: "iscsi",
  179. ServerImage: imageutils.GetE2EImage(imageutils.VolumeISCSIServer),
  180. ServerArgs: []string{iqn},
  181. ServerVolumes: map[string]string{
  182. // iSCSI container needs to insert modules from the host
  183. "/lib/modules": "/lib/modules",
  184. // iSCSI container needs to configure kernel
  185. "/sys/kernel": "/sys/kernel",
  186. // iSCSI source "block devices" must be available on the host
  187. "/srv/iscsi": "/srv/iscsi",
  188. },
  189. ServerReadyMessage: "iscsi target started",
  190. ServerHostNetwork: true,
  191. }
  192. pod, ip = CreateStorageServer(cs, config)
  193. // Make sure the client runs on the same node as server so we don't need to open any firewalls.
  194. config.ClientNodeName = pod.Spec.NodeName
  195. return config, pod, ip, iqn
  196. }
  197. // NewRBDServer is a CephRBD-specific wrapper for CreateStorageServer.
  198. func NewRBDServer(cs clientset.Interface, namespace string) (config TestConfig, pod *v1.Pod, secret *v1.Secret, ip string) {
  199. config = TestConfig{
  200. Namespace: namespace,
  201. Prefix: "rbd",
  202. ServerImage: imageutils.GetE2EImage(imageutils.VolumeRBDServer),
  203. ServerPorts: []int{6789},
  204. ServerVolumes: map[string]string{
  205. "/lib/modules": "/lib/modules",
  206. },
  207. ServerReadyMessage: "Ceph is ready",
  208. }
  209. pod, ip = CreateStorageServer(cs, config)
  210. // create secrets for the server
  211. secret = &v1.Secret{
  212. TypeMeta: metav1.TypeMeta{
  213. Kind: "Secret",
  214. APIVersion: "v1",
  215. },
  216. ObjectMeta: metav1.ObjectMeta{
  217. Name: config.Prefix + "-secret",
  218. },
  219. Data: map[string][]byte{
  220. // from test/images/volumes-tester/rbd/keyring
  221. "key": []byte("AQDRrKNVbEevChAAEmRC+pW/KBVHxa0w/POILA=="),
  222. },
  223. Type: "kubernetes.io/rbd",
  224. }
  225. secret, err := cs.CoreV1().Secrets(config.Namespace).Create(secret)
  226. if err != nil {
  227. framework.Failf("Failed to create secrets for Ceph RBD: %v", err)
  228. }
  229. return config, pod, secret, ip
  230. }
  231. // CreateStorageServer is a wrapper for StartVolumeServer(). A storage server config is passed in, and a pod pointer
  232. // and ip address string are returned.
  233. // Note: Expect() is called so no error is returned.
  234. func CreateStorageServer(cs clientset.Interface, config TestConfig) (pod *v1.Pod, ip string) {
  235. pod = StartVolumeServer(cs, config)
  236. gomega.Expect(pod).NotTo(gomega.BeNil(), "storage server pod should not be nil")
  237. ip = pod.Status.PodIP
  238. gomega.Expect(len(ip)).NotTo(gomega.BeZero(), fmt.Sprintf("pod %s's IP should not be empty", pod.Name))
  239. e2elog.Logf("%s server pod IP address: %s", config.Prefix, ip)
  240. return pod, ip
  241. }
  242. // StartVolumeServer starts a container specified by config.serverImage and exports all
  243. // config.serverPorts from it. The returned pod should be used to get the server
  244. // IP address and create appropriate VolumeSource.
  245. func StartVolumeServer(client clientset.Interface, config TestConfig) *v1.Pod {
  246. podClient := client.CoreV1().Pods(config.Namespace)
  247. portCount := len(config.ServerPorts)
  248. serverPodPorts := make([]v1.ContainerPort, portCount)
  249. for i := 0; i < portCount; i++ {
  250. portName := fmt.Sprintf("%s-%d", config.Prefix, i)
  251. serverPodPorts[i] = v1.ContainerPort{
  252. Name: portName,
  253. ContainerPort: int32(config.ServerPorts[i]),
  254. Protocol: v1.ProtocolTCP,
  255. }
  256. }
  257. volumeCount := len(config.ServerVolumes)
  258. volumes := make([]v1.Volume, volumeCount)
  259. mounts := make([]v1.VolumeMount, volumeCount)
  260. i := 0
  261. for src, dst := range config.ServerVolumes {
  262. mountName := fmt.Sprintf("path%d", i)
  263. volumes[i].Name = mountName
  264. if src == "" {
  265. volumes[i].VolumeSource.EmptyDir = &v1.EmptyDirVolumeSource{}
  266. } else {
  267. volumes[i].VolumeSource.HostPath = &v1.HostPathVolumeSource{
  268. Path: src,
  269. }
  270. }
  271. mounts[i].Name = mountName
  272. mounts[i].ReadOnly = false
  273. mounts[i].MountPath = dst
  274. i++
  275. }
  276. serverPodName := fmt.Sprintf("%s-server", config.Prefix)
  277. ginkgo.By(fmt.Sprint("creating ", serverPodName, " pod"))
  278. privileged := new(bool)
  279. *privileged = true
  280. restartPolicy := v1.RestartPolicyAlways
  281. if config.WaitForCompletion {
  282. restartPolicy = v1.RestartPolicyNever
  283. }
  284. serverPod := &v1.Pod{
  285. TypeMeta: metav1.TypeMeta{
  286. Kind: "Pod",
  287. APIVersion: "v1",
  288. },
  289. ObjectMeta: metav1.ObjectMeta{
  290. Name: serverPodName,
  291. Labels: map[string]string{
  292. "role": serverPodName,
  293. },
  294. },
  295. Spec: v1.PodSpec{
  296. HostNetwork: config.ServerHostNetwork,
  297. Containers: []v1.Container{
  298. {
  299. Name: serverPodName,
  300. Image: config.ServerImage,
  301. SecurityContext: &v1.SecurityContext{
  302. Privileged: privileged,
  303. },
  304. Command: config.ServerCmds,
  305. Args: config.ServerArgs,
  306. Ports: serverPodPorts,
  307. VolumeMounts: mounts,
  308. },
  309. },
  310. Volumes: volumes,
  311. RestartPolicy: restartPolicy,
  312. NodeName: config.ServerNodeName,
  313. NodeSelector: config.NodeSelector,
  314. },
  315. }
  316. var pod *v1.Pod
  317. serverPod, err := podClient.Create(serverPod)
  318. // ok if the server pod already exists. TODO: make this controllable by callers
  319. if err != nil {
  320. if apierrs.IsAlreadyExists(err) {
  321. e2elog.Logf("Ignore \"already-exists\" error, re-get pod...")
  322. ginkgo.By(fmt.Sprintf("re-getting the %q server pod", serverPodName))
  323. serverPod, err = podClient.Get(serverPodName, metav1.GetOptions{})
  324. framework.ExpectNoError(err, "Cannot re-get the server pod %q: %v", serverPodName, err)
  325. pod = serverPod
  326. } else {
  327. framework.ExpectNoError(err, "Failed to create %q pod: %v", serverPodName, err)
  328. }
  329. }
  330. if config.WaitForCompletion {
  331. framework.ExpectNoError(framework.WaitForPodSuccessInNamespace(client, serverPod.Name, serverPod.Namespace))
  332. framework.ExpectNoError(podClient.Delete(serverPod.Name, nil))
  333. } else {
  334. framework.ExpectNoError(framework.WaitForPodRunningInNamespace(client, serverPod))
  335. if pod == nil {
  336. ginkgo.By(fmt.Sprintf("locating the %q server pod", serverPodName))
  337. pod, err = podClient.Get(serverPodName, metav1.GetOptions{})
  338. framework.ExpectNoError(err, "Cannot locate the server pod %q: %v", serverPodName, err)
  339. }
  340. }
  341. if config.ServerReadyMessage != "" {
  342. _, err := framework.LookForStringInLog(pod.Namespace, pod.Name, serverPodName, config.ServerReadyMessage, VolumeServerPodStartupTimeout)
  343. framework.ExpectNoError(err, "Failed to find %q in pod logs: %s", config.ServerReadyMessage, err)
  344. }
  345. return pod
  346. }
  347. // CleanUpVolumeServer is a wrapper of cleanup function for volume server without secret created by specific CreateStorageServer function.
  348. func CleanUpVolumeServer(f *framework.Framework, serverPod *v1.Pod) {
  349. CleanUpVolumeServerWithSecret(f, serverPod, nil)
  350. }
  351. // CleanUpVolumeServerWithSecret is a wrapper of cleanup function for volume server with secret created by specific CreateStorageServer function.
  352. func CleanUpVolumeServerWithSecret(f *framework.Framework, serverPod *v1.Pod, secret *v1.Secret) {
  353. cs := f.ClientSet
  354. ns := f.Namespace
  355. if secret != nil {
  356. e2elog.Logf("Deleting server secret %q...", secret.Name)
  357. err := cs.CoreV1().Secrets(ns.Name).Delete(secret.Name, &metav1.DeleteOptions{})
  358. if err != nil {
  359. e2elog.Logf("Delete secret failed: %v", err)
  360. }
  361. }
  362. e2elog.Logf("Deleting server pod %q...", serverPod.Name)
  363. err := framework.DeletePodWithWait(f, cs, serverPod)
  364. if err != nil {
  365. e2elog.Logf("Server pod delete failed: %v", err)
  366. }
  367. }
  368. // TestCleanup cleans both server and client pods.
  369. func TestCleanup(f *framework.Framework, config TestConfig) {
  370. ginkgo.By(fmt.Sprint("cleaning the environment after ", config.Prefix))
  371. defer ginkgo.GinkgoRecover()
  372. cs := f.ClientSet
  373. err := framework.DeletePodWithWaitByName(f, cs, config.Prefix+"-client", config.Namespace)
  374. gomega.Expect(err).To(gomega.BeNil(), "Failed to delete pod %v in namespace %v", config.Prefix+"-client", config.Namespace)
  375. if config.ServerImage != "" {
  376. err := framework.DeletePodWithWaitByName(f, cs, config.Prefix+"-server", config.Namespace)
  377. gomega.Expect(err).To(gomega.BeNil(), "Failed to delete pod %v in namespace %v", config.Prefix+"-server", config.Namespace)
  378. }
  379. }
  380. // TestVolumeClient start a client pod using given VolumeSource (exported by startVolumeServer())
  381. // and check that the pod sees expected data, e.g. from the server pod.
  382. // Multiple Tests can be specified to mount multiple volumes to a single
  383. // pod.
  384. func TestVolumeClient(client clientset.Interface, config TestConfig, fsGroup *int64, fsType string, tests []Test) {
  385. ginkgo.By(fmt.Sprint("starting ", config.Prefix, "-client"))
  386. var gracePeriod int64 = 1
  387. var command string
  388. if !framework.NodeOSDistroIs("windows") {
  389. command = "while true ; do cat /opt/0/index.html ; sleep 2 ; ls -altrh /opt/ ; sleep 2 ; done "
  390. } else {
  391. command = "while(1) {cat /opt/0/index.html ; sleep 2 ; ls /opt/; sleep 2}"
  392. }
  393. seLinuxOptions := &v1.SELinuxOptions{Level: "s0:c0,c1"}
  394. clientPod := &v1.Pod{
  395. TypeMeta: metav1.TypeMeta{
  396. Kind: "Pod",
  397. APIVersion: "v1",
  398. },
  399. ObjectMeta: metav1.ObjectMeta{
  400. Name: config.Prefix + "-client",
  401. Labels: map[string]string{
  402. "role": config.Prefix + "-client",
  403. },
  404. },
  405. Spec: v1.PodSpec{
  406. Containers: []v1.Container{
  407. {
  408. Name: config.Prefix + "-client",
  409. Image: GetTestImage(framework.BusyBoxImage),
  410. WorkingDir: "/opt",
  411. // An imperative and easily debuggable container which reads vol contents for
  412. // us to scan in the tests or by eye.
  413. // We expect that /opt is empty in the minimal containers which we use in this test.
  414. Command: GenerateScriptCmd(command),
  415. VolumeMounts: []v1.VolumeMount{},
  416. },
  417. },
  418. TerminationGracePeriodSeconds: &gracePeriod,
  419. SecurityContext: GeneratePodSecurityContext(fsGroup, seLinuxOptions),
  420. Volumes: []v1.Volume{},
  421. NodeName: config.ClientNodeName,
  422. NodeSelector: config.NodeSelector,
  423. },
  424. }
  425. podsNamespacer := client.CoreV1().Pods(config.Namespace)
  426. for i, test := range tests {
  427. volumeName := fmt.Sprintf("%s-%s-%d", config.Prefix, "volume", i)
  428. clientPod.Spec.Containers[0].VolumeMounts = append(clientPod.Spec.Containers[0].VolumeMounts, v1.VolumeMount{
  429. Name: volumeName,
  430. MountPath: fmt.Sprintf("/opt/%d", i),
  431. })
  432. clientPod.Spec.Volumes = append(clientPod.Spec.Volumes, v1.Volume{
  433. Name: volumeName,
  434. VolumeSource: test.Volume,
  435. })
  436. }
  437. clientPod, err := podsNamespacer.Create(clientPod)
  438. if err != nil {
  439. framework.Failf("Failed to create %s pod: %v", clientPod.Name, err)
  440. }
  441. framework.ExpectNoError(framework.WaitForPodRunningInNamespace(client, clientPod))
  442. ginkgo.By("Checking that text file contents are perfect.")
  443. for i, test := range tests {
  444. fileName := fmt.Sprintf("/opt/%d/%s", i, test.File)
  445. commands := GenerateReadFileCmd(fileName)
  446. _, err = framework.LookForStringInPodExec(config.Namespace, clientPod.Name, commands, test.ExpectedContent, time.Minute)
  447. framework.ExpectNoError(err, "failed: finding the contents of the mounted file %s.", fileName)
  448. }
  449. if !framework.NodeOSDistroIs("windows") {
  450. if fsGroup != nil {
  451. ginkgo.By("Checking fsGroup is correct.")
  452. _, err = framework.LookForStringInPodExec(config.Namespace, clientPod.Name, []string{"ls", "-ld", "/opt/0"}, strconv.Itoa(int(*fsGroup)), time.Minute)
  453. framework.ExpectNoError(err, "failed: getting the right privileges in the file %v", int(*fsGroup))
  454. }
  455. if fsType != "" {
  456. ginkgo.By("Checking fsType is correct.")
  457. _, err = framework.LookForStringInPodExec(config.Namespace, clientPod.Name, []string{"grep", " /opt/0 ", "/proc/mounts"}, fsType, time.Minute)
  458. framework.ExpectNoError(err, "failed: getting the right fsType %s", fsType)
  459. }
  460. }
  461. }
  462. // InjectHTML inserts index.html with given content into given volume. It does so by
  463. // starting and auxiliary pod which writes the file there.
  464. // The volume must be writable.
  465. func InjectHTML(client clientset.Interface, config TestConfig, fsGroup *int64, volume v1.VolumeSource, content string) {
  466. ginkgo.By(fmt.Sprint("starting ", config.Prefix, " injector"))
  467. podClient := client.CoreV1().Pods(config.Namespace)
  468. podName := fmt.Sprintf("%s-injector-%s", config.Prefix, rand.String(4))
  469. volMountName := fmt.Sprintf("%s-volume-%s", config.Prefix, rand.String(4))
  470. fileName := "/mnt/index.html"
  471. injectPod := &v1.Pod{
  472. TypeMeta: metav1.TypeMeta{
  473. Kind: "Pod",
  474. APIVersion: "v1",
  475. },
  476. ObjectMeta: metav1.ObjectMeta{
  477. Name: podName,
  478. Labels: map[string]string{
  479. "role": config.Prefix + "-injector",
  480. },
  481. },
  482. Spec: v1.PodSpec{
  483. Containers: []v1.Container{
  484. {
  485. Name: config.Prefix + "-injector",
  486. Image: GetTestImage(framework.BusyBoxImage),
  487. Command: GenerateWriteFileCmd(content, fileName),
  488. VolumeMounts: []v1.VolumeMount{
  489. {
  490. Name: volMountName,
  491. MountPath: "/mnt",
  492. },
  493. },
  494. SecurityContext: GenerateSecurityContext(true),
  495. },
  496. },
  497. SecurityContext: GeneratePodSecurityContext(fsGroup, nil),
  498. RestartPolicy: v1.RestartPolicyNever,
  499. Volumes: []v1.Volume{
  500. {
  501. Name: volMountName,
  502. VolumeSource: volume,
  503. },
  504. },
  505. NodeName: config.ClientNodeName,
  506. NodeSelector: config.NodeSelector,
  507. },
  508. }
  509. defer func() {
  510. podClient.Delete(podName, nil)
  511. }()
  512. injectPod, err := podClient.Create(injectPod)
  513. framework.ExpectNoError(err, "Failed to create injector pod: %v", err)
  514. err = framework.WaitForPodSuccessInNamespace(client, injectPod.Name, injectPod.Namespace)
  515. framework.ExpectNoError(err)
  516. }
  517. // CreateGCEVolume creates PersistentVolumeSource for GCEVolume.
  518. func CreateGCEVolume() (*v1.PersistentVolumeSource, string) {
  519. diskName, err := framework.CreatePDWithRetry()
  520. framework.ExpectNoError(err)
  521. return &v1.PersistentVolumeSource{
  522. GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{
  523. PDName: diskName,
  524. FSType: "ext3",
  525. ReadOnly: false,
  526. },
  527. }, diskName
  528. }
  529. // GenerateScriptCmd generates the corresponding command lines to execute a command.
  530. // Depending on the Node OS is Windows or linux, the command will use powershell or /bin/sh
  531. func GenerateScriptCmd(command string) []string {
  532. var commands []string
  533. if !framework.NodeOSDistroIs("windows") {
  534. commands = []string{"/bin/sh", "-c", command}
  535. } else {
  536. commands = []string{"powershell", "/c", command}
  537. }
  538. return commands
  539. }
  540. // GenerateWriteFileCmd generates the corresponding command lines to write a file with the given content and file path.
  541. // Depending on the Node OS is Windows or linux, the command will use powershell or /bin/sh
  542. func GenerateWriteFileCmd(content, fullPath string) []string {
  543. var commands []string
  544. if !framework.NodeOSDistroIs("windows") {
  545. commands = []string{"/bin/sh", "-c", "echo '" + content + "' > " + fullPath}
  546. } else {
  547. commands = []string{"powershell", "/c", "echo '" + content + "' > " + fullPath}
  548. }
  549. return commands
  550. }
  551. // GenerateReadFileCmd generates the corresponding command lines to read from a file with the given file path.
  552. // Depending on the Node OS is Windows or linux, the command will use powershell or /bin/sh
  553. func GenerateReadFileCmd(fullPath string) []string {
  554. var commands []string
  555. if !framework.NodeOSDistroIs("windows") {
  556. commands = []string{"cat", fullPath}
  557. } else {
  558. commands = []string{"powershell", "/c", "type " + fullPath}
  559. }
  560. return commands
  561. }
  562. // GenerateWriteandExecuteScriptFileCmd generates the corresponding command lines to write a file with the given file path
  563. // and also execute this file.
  564. // Depending on the Node OS is Windows or linux, the command will use powershell or /bin/sh
  565. func GenerateWriteandExecuteScriptFileCmd(content, fileName, filePath string) []string {
  566. // for windows cluster, modify the Pod spec.
  567. if framework.NodeOSDistroIs("windows") {
  568. scriptName := fmt.Sprintf("%s.ps1", fileName)
  569. fullPath := filepath.Join(filePath, scriptName)
  570. cmd := "echo \"" + content + "\" > " + fullPath + "; .\\" + fullPath
  571. e2elog.Logf("generated pod command %s", cmd)
  572. return []string{"powershell", "/c", cmd}
  573. }
  574. scriptName := fmt.Sprintf("%s.sh", fileName)
  575. fullPath := filepath.Join(filePath, scriptName)
  576. cmd := fmt.Sprintf("echo \"%s\" > %s; chmod u+x %s; %s;", content, fullPath, fullPath, fullPath)
  577. return []string{"/bin/sh", "-ec", cmd}
  578. }
  579. // GenerateSecurityContext generates the corresponding container security context with the given inputs
  580. // If the Node OS is windows, currently we will ignore the inputs and return nil.
  581. // TODO: Will modify it after windows has its own security context
  582. func GenerateSecurityContext(privileged bool) *v1.SecurityContext {
  583. if framework.NodeOSDistroIs("windows") {
  584. return nil
  585. }
  586. return &v1.SecurityContext{
  587. Privileged: &privileged,
  588. }
  589. }
  590. // GeneratePodSecurityContext generates the corresponding pod security context with the given inputs
  591. // If the Node OS is windows, currently we will ignore the inputs and return nil.
  592. // TODO: Will modify it after windows has its own security context
  593. func GeneratePodSecurityContext(fsGroup *int64, seLinuxOptions *v1.SELinuxOptions) *v1.PodSecurityContext {
  594. if framework.NodeOSDistroIs("windows") {
  595. return nil
  596. }
  597. return &v1.PodSecurityContext{
  598. SELinuxOptions: seLinuxOptions,
  599. FSGroup: fsGroup,
  600. }
  601. }
  602. // GetTestImage returns the image name with the given input
  603. // If the Node OS is windows, currently we return Nettest image for Windows node
  604. // due to the issue of #https://github.com/kubernetes-sigs/windows-testing/pull/35.
  605. func GetTestImage(image string) string {
  606. if framework.NodeOSDistroIs("windows") {
  607. return imageutils.GetE2EImage(imageutils.Nettest)
  608. }
  609. return image
  610. }