host_exec.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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 utils
  14. import (
  15. "context"
  16. "fmt"
  17. v1 "k8s.io/api/core/v1"
  18. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  19. "k8s.io/client-go/util/exec"
  20. "k8s.io/kubernetes/test/e2e/framework"
  21. e2epod "k8s.io/kubernetes/test/e2e/framework/pod"
  22. )
  23. // Result holds the execution result of remote execution command.
  24. type Result struct {
  25. Host string
  26. Cmd string
  27. Stdout string
  28. Stderr string
  29. Code int
  30. }
  31. // LogResult records result log
  32. func LogResult(result Result) {
  33. remote := result.Host
  34. framework.Logf("exec %s: command: %s", remote, result.Cmd)
  35. framework.Logf("exec %s: stdout: %q", remote, result.Stdout)
  36. framework.Logf("exec %s: stderr: %q", remote, result.Stderr)
  37. framework.Logf("exec %s: exit code: %d", remote, result.Code)
  38. }
  39. // HostExec represents interface we require to execute commands on remote host.
  40. type HostExec interface {
  41. Execute(cmd string, node *v1.Node) (Result, error)
  42. IssueCommandWithResult(cmd string, node *v1.Node) (string, error)
  43. IssueCommand(cmd string, node *v1.Node) error
  44. Cleanup()
  45. }
  46. // hostExecutor implements HostExec
  47. type hostExecutor struct {
  48. *framework.Framework
  49. nodeExecPods map[string]*v1.Pod
  50. }
  51. // NewHostExec returns a HostExec
  52. func NewHostExec(framework *framework.Framework) HostExec {
  53. return &hostExecutor{
  54. Framework: framework,
  55. nodeExecPods: make(map[string]*v1.Pod),
  56. }
  57. }
  58. // launchNodeExecPod launches a hostexec pod for local PV and waits
  59. // until it's Running.
  60. func (h *hostExecutor) launchNodeExecPod(node string) *v1.Pod {
  61. f := h.Framework
  62. cs := f.ClientSet
  63. ns := f.Namespace
  64. hostExecPod := e2epod.NewExecPodSpec(ns.Name, "", true)
  65. hostExecPod.GenerateName = fmt.Sprintf("hostexec-%s-", node)
  66. // Use NodeAffinity instead of NodeName so that pods will not
  67. // be immediately Failed by kubelet if it's out of space. Instead
  68. // Pods will be pending in the scheduler until there is space freed
  69. // up.
  70. e2epod.SetNodeAffinity(hostExecPod, node)
  71. hostExecPod.Spec.Volumes = []v1.Volume{
  72. {
  73. // Required to enter into host mount namespace via nsenter.
  74. Name: "rootfs",
  75. VolumeSource: v1.VolumeSource{
  76. HostPath: &v1.HostPathVolumeSource{
  77. Path: "/",
  78. },
  79. },
  80. },
  81. }
  82. hostExecPod.Spec.Containers[0].VolumeMounts = []v1.VolumeMount{
  83. {
  84. Name: "rootfs",
  85. MountPath: "/rootfs",
  86. ReadOnly: true,
  87. },
  88. }
  89. hostExecPod.Spec.Containers[0].SecurityContext = &v1.SecurityContext{
  90. Privileged: func(privileged bool) *bool {
  91. return &privileged
  92. }(true),
  93. }
  94. pod, err := cs.CoreV1().Pods(ns.Name).Create(context.TODO(), hostExecPod, metav1.CreateOptions{})
  95. framework.ExpectNoError(err)
  96. err = e2epod.WaitForPodRunningInNamespace(cs, pod)
  97. framework.ExpectNoError(err)
  98. return pod
  99. }
  100. // Execute executes the command on the given node. If there is no error
  101. // performing the remote command execution, the stdout, stderr and exit code
  102. // are returned.
  103. // This works like ssh.SSH(...) utility.
  104. func (h *hostExecutor) Execute(cmd string, node *v1.Node) (Result, error) {
  105. result, err := h.exec(cmd, node)
  106. if codeExitErr, ok := err.(exec.CodeExitError); ok {
  107. // extract the exit code of remote command and silence the command
  108. // non-zero exit code error
  109. result.Code = codeExitErr.ExitStatus()
  110. err = nil
  111. }
  112. return result, err
  113. }
  114. func (h *hostExecutor) exec(cmd string, node *v1.Node) (Result, error) {
  115. result := Result{
  116. Host: node.Name,
  117. Cmd: cmd,
  118. }
  119. pod, ok := h.nodeExecPods[node.Name]
  120. if !ok {
  121. pod = h.launchNodeExecPod(node.Name)
  122. if pod == nil {
  123. return result, fmt.Errorf("failed to create hostexec pod for node %q", node)
  124. }
  125. h.nodeExecPods[node.Name] = pod
  126. }
  127. args := []string{
  128. "nsenter",
  129. "--mount=/rootfs/proc/1/ns/mnt",
  130. "--",
  131. "sh",
  132. "-c",
  133. cmd,
  134. }
  135. containerName := pod.Spec.Containers[0].Name
  136. var err error
  137. result.Stdout, result.Stderr, err = h.Framework.ExecWithOptions(framework.ExecOptions{
  138. Command: args,
  139. Namespace: pod.Namespace,
  140. PodName: pod.Name,
  141. ContainerName: containerName,
  142. Stdin: nil,
  143. CaptureStdout: true,
  144. CaptureStderr: true,
  145. PreserveWhitespace: true,
  146. })
  147. return result, err
  148. }
  149. // IssueCommandWithResult issues command on the given node and returns stdout as
  150. // result. It returns error if there are some issues executing the command or
  151. // the command exits non-zero.
  152. func (h *hostExecutor) IssueCommandWithResult(cmd string, node *v1.Node) (string, error) {
  153. result, err := h.exec(cmd, node)
  154. if err != nil {
  155. LogResult(result)
  156. }
  157. return result.Stdout, err
  158. }
  159. // IssueCommand works like IssueCommandWithResult, but discards result.
  160. func (h *hostExecutor) IssueCommand(cmd string, node *v1.Node) error {
  161. _, err := h.IssueCommandWithResult(cmd, node)
  162. return err
  163. }
  164. // Cleanup cleanup resources it created during test.
  165. // Note that in most cases it is not necessary to call this because we create
  166. // pods under test namespace which will be destroyed in teardown phase.
  167. func (h *hostExecutor) Cleanup() {
  168. for _, pod := range h.nodeExecPods {
  169. e2epod.DeletePodOrFail(h.Framework.ClientSet, pod.Namespace, pod.Name)
  170. }
  171. h.nodeExecPods = make(map[string]*v1.Pod)
  172. }