nsenter.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. // +build linux
  2. /*
  3. Copyright 2017 The Kubernetes Authors.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package nsenter
  15. import (
  16. "context"
  17. "errors"
  18. "fmt"
  19. "os"
  20. "path/filepath"
  21. "strings"
  22. "k8s.io/klog"
  23. "k8s.io/utils/exec"
  24. )
  25. const (
  26. // DefaultHostRootFsPath is path to host's filesystem mounted into container
  27. // with kubelet.
  28. DefaultHostRootFsPath = "/rootfs"
  29. // mountNsPath is the default mount namespace of the host
  30. mountNsPath = "/proc/1/ns/mnt"
  31. // nsenterPath is the default nsenter command
  32. nsenterPath = "nsenter"
  33. )
  34. // Nsenter is a type alias for backward compatibility
  35. type Nsenter = NSEnter
  36. // NSEnter is part of experimental support for running the kubelet
  37. // in a container.
  38. //
  39. // NSEnter requires:
  40. //
  41. // 1. Docker >= 1.6 due to the dependency on the slave propagation mode
  42. // of the bind-mount of the kubelet root directory in the container.
  43. // Docker 1.5 used a private propagation mode for bind-mounts, so mounts
  44. // performed in the host's mount namespace do not propagate out to the
  45. // bind-mount in this docker version.
  46. // 2. The host's root filesystem must be available at /rootfs
  47. // 3. The nsenter binary must be on the Kubelet process' PATH in the container's
  48. // filesystem.
  49. // 4. The Kubelet process must have CAP_SYS_ADMIN (required by nsenter); at
  50. // the present, this effectively means that the kubelet is running in a
  51. // privileged container.
  52. // 5. The volume path used by the Kubelet must be the same inside and outside
  53. // the container and be writable by the container (to initialize volume)
  54. // contents. TODO: remove this requirement.
  55. // 6. The host image must have "mount", "findmnt", "umount", "stat", "touch",
  56. // "mkdir", "ls", "sh" and "chmod" binaries in /bin, /usr/sbin, or /usr/bin
  57. // 7. The host image should have systemd-run in /bin, /usr/sbin, or /usr/bin if
  58. // systemd is installed/enabled in the operating system.
  59. // For more information about mount propagation modes, see:
  60. // https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt
  61. type NSEnter struct {
  62. // a map of commands to their paths on the host filesystem
  63. paths map[string]string
  64. // Path to the host filesystem, typically "/rootfs". Used only for testing.
  65. hostRootFsPath string
  66. // Exec implementation
  67. executor exec.Interface
  68. }
  69. // NewNsenter constructs a new instance of NSEnter
  70. func NewNsenter(hostRootFsPath string, executor exec.Interface) (*NSEnter, error) {
  71. ne := &NSEnter{
  72. hostRootFsPath: hostRootFsPath,
  73. executor: executor,
  74. }
  75. if err := ne.initPaths(); err != nil {
  76. return nil, err
  77. }
  78. return ne, nil
  79. }
  80. func (ne *NSEnter) initPaths() error {
  81. ne.paths = map[string]string{}
  82. binaries := []string{
  83. "mount",
  84. "findmnt",
  85. "umount",
  86. "systemd-run",
  87. "stat",
  88. "touch",
  89. "mkdir",
  90. "sh",
  91. "chmod",
  92. "realpath",
  93. }
  94. // search for the required commands in other locations besides /usr/bin
  95. for _, binary := range binaries {
  96. // check for binary under the following directories
  97. for _, path := range []string{"/", "/bin", "/usr/sbin", "/usr/bin"} {
  98. binPath := filepath.Join(path, binary)
  99. if _, err := os.Stat(filepath.Join(ne.hostRootFsPath, binPath)); err != nil {
  100. continue
  101. }
  102. ne.paths[binary] = binPath
  103. break
  104. }
  105. // systemd-run is optional, bailout if we don't find any of the other binaries
  106. if ne.paths[binary] == "" && binary != "systemd-run" {
  107. return fmt.Errorf("unable to find %v", binary)
  108. }
  109. }
  110. return nil
  111. }
  112. // Exec executes nsenter commands in hostProcMountNsPath mount namespace
  113. func (ne *NSEnter) Exec(cmd string, args []string) exec.Cmd {
  114. hostProcMountNsPath := filepath.Join(ne.hostRootFsPath, mountNsPath)
  115. fullArgs := append([]string{fmt.Sprintf("--mount=%s", hostProcMountNsPath), "--"},
  116. append([]string{ne.AbsHostPath(cmd)}, args...)...)
  117. klog.V(5).Infof("Running nsenter command: %v %v", nsenterPath, fullArgs)
  118. return ne.executor.Command(nsenterPath, fullArgs...)
  119. }
  120. // Command returns a command wrapped with nsenter
  121. func (ne *NSEnter) Command(cmd string, args ...string) exec.Cmd {
  122. return ne.Exec(cmd, args)
  123. }
  124. // CommandContext returns a CommandContext wrapped with nsenter
  125. func (ne *NSEnter) CommandContext(ctx context.Context, cmd string, args ...string) exec.Cmd {
  126. hostProcMountNsPath := filepath.Join(ne.hostRootFsPath, mountNsPath)
  127. fullArgs := append([]string{fmt.Sprintf("--mount=%s", hostProcMountNsPath), "--"},
  128. append([]string{ne.AbsHostPath(cmd)}, args...)...)
  129. klog.V(5).Infof("Running nsenter command: %v %v", nsenterPath, fullArgs)
  130. return ne.executor.CommandContext(ctx, nsenterPath, fullArgs...)
  131. }
  132. // LookPath returns a LookPath wrapped with nsenter
  133. func (ne *NSEnter) LookPath(file string) (string, error) {
  134. return "", fmt.Errorf("not implemented, error looking up : %s", file)
  135. }
  136. // AbsHostPath returns the absolute runnable path for a specified command
  137. func (ne *NSEnter) AbsHostPath(command string) string {
  138. path, ok := ne.paths[command]
  139. if !ok {
  140. return command
  141. }
  142. return path
  143. }
  144. // SupportsSystemd checks whether command systemd-run exists
  145. func (ne *NSEnter) SupportsSystemd() (string, bool) {
  146. systemdRunPath, ok := ne.paths["systemd-run"]
  147. return systemdRunPath, ok && systemdRunPath != ""
  148. }
  149. // EvalSymlinks returns the path name on the host after evaluating symlinks on the
  150. // host.
  151. // mustExist makes EvalSymlinks to return error when the path does not
  152. // exist. When it's false, it evaluates symlinks of the existing part and
  153. // blindly adds the non-existing part:
  154. // pathname: /mnt/volume/non/existing/directory
  155. // /mnt/volume exists
  156. // non/existing/directory does not exist
  157. // -> It resolves symlinks in /mnt/volume to say /mnt/foo and returns
  158. // /mnt/foo/non/existing/directory.
  159. //
  160. // BEWARE! EvalSymlinks is not able to detect symlink looks with mustExist=false!
  161. // If /tmp/link is symlink to /tmp/link, EvalSymlinks(/tmp/link/foo) returns /tmp/link/foo.
  162. func (ne *NSEnter) EvalSymlinks(pathname string, mustExist bool) (string, error) {
  163. var args []string
  164. if mustExist {
  165. // "realpath -e: all components of the path must exist"
  166. args = []string{"-e", pathname}
  167. } else {
  168. // "realpath -m: no path components need exist or be a directory"
  169. args = []string{"-m", pathname}
  170. }
  171. outBytes, err := ne.Exec("realpath", args).CombinedOutput()
  172. if err != nil {
  173. klog.Infof("failed to resolve symbolic links on %s: %v", pathname, err)
  174. return "", err
  175. }
  176. return strings.TrimSpace(string(outBytes)), nil
  177. }
  178. // KubeletPath returns the path name that can be accessed by containerized
  179. // kubelet. It is recommended to resolve symlinks on the host by EvalSymlinks
  180. // before calling this function
  181. func (ne *NSEnter) KubeletPath(pathname string) string {
  182. return filepath.Join(ne.hostRootFsPath, pathname)
  183. }
  184. // NewFakeNsenter returns a NSEnter that does not run "nsenter --mount=... --",
  185. // but runs everything in the same mount namespace as the unit test binary.
  186. // rootfsPath is supposed to be a symlink, e.g. /tmp/xyz/rootfs -> /.
  187. // This fake NSEnter is enough for most operations, e.g. to resolve symlinks,
  188. // but it's not enough to call /bin/mount - unit tests don't run as root.
  189. func NewFakeNsenter(rootfsPath string) (*NSEnter, error) {
  190. executor := &fakeExec{
  191. rootfsPath: rootfsPath,
  192. }
  193. // prepare /rootfs/bin, usr/bin and usr/sbin
  194. bin := filepath.Join(rootfsPath, "bin")
  195. if err := os.Symlink("/bin", bin); err != nil {
  196. return nil, err
  197. }
  198. usr := filepath.Join(rootfsPath, "usr")
  199. if err := os.Mkdir(usr, 0755); err != nil {
  200. return nil, err
  201. }
  202. usrbin := filepath.Join(usr, "bin")
  203. if err := os.Symlink("/usr/bin", usrbin); err != nil {
  204. return nil, err
  205. }
  206. usrsbin := filepath.Join(usr, "sbin")
  207. if err := os.Symlink("/usr/sbin", usrsbin); err != nil {
  208. return nil, err
  209. }
  210. return NewNsenter(rootfsPath, executor)
  211. }
  212. type fakeExec struct {
  213. rootfsPath string
  214. }
  215. func (f fakeExec) Command(cmd string, args ...string) exec.Cmd {
  216. // This will intentionaly panic if NSEnter does not provide enough arguments.
  217. realCmd := args[2]
  218. realArgs := args[3:]
  219. return exec.New().Command(realCmd, realArgs...)
  220. }
  221. func (fakeExec) LookPath(file string) (string, error) {
  222. return "", errors.New("not implemented")
  223. }
  224. func (fakeExec) CommandContext(ctx context.Context, cmd string, args ...string) exec.Cmd {
  225. return nil
  226. }
  227. var _ exec.Interface = fakeExec{}
  228. var _ exec.Interface = &NSEnter{}