nsenter_mount.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. // +build linux
  2. /*
  3. Copyright 2014 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. "fmt"
  17. "os"
  18. "path/filepath"
  19. "strings"
  20. "k8s.io/klog"
  21. "k8s.io/kubernetes/pkg/util/mount"
  22. "k8s.io/utils/nsenter"
  23. utilpath "k8s.io/utils/path"
  24. )
  25. const (
  26. // hostProcMountsPath is the default mount path for rootfs
  27. hostProcMountsPath = "/rootfs/proc/1/mounts"
  28. // hostProcMountinfoPath is the default mount info path for rootfs
  29. hostProcMountinfoPath = "/rootfs/proc/1/mountinfo"
  30. )
  31. // Mounter implements mount.Interface
  32. // Currently, all docker containers receive their own mount namespaces.
  33. // Mounter works by executing nsenter to run commands in
  34. // the host's mount namespace.
  35. type Mounter struct {
  36. ne *nsenter.Nsenter
  37. // rootDir is location of /var/lib/kubelet directory.
  38. rootDir string
  39. }
  40. // NewMounter creates a new mounter for kubelet that runs as a container.
  41. func NewMounter(rootDir string, ne *nsenter.Nsenter) *Mounter {
  42. return &Mounter{
  43. rootDir: rootDir,
  44. ne: ne,
  45. }
  46. }
  47. // Mounter implements mount.Interface
  48. var _ = mount.Interface(&Mounter{})
  49. // Mount runs mount(8) in the host's root mount namespace. Aside from this
  50. // aspect, Mount has the same semantics as the mounter returned by mount.New()
  51. func (n *Mounter) Mount(source string, target string, fstype string, options []string) error {
  52. bind, bindOpts, bindRemountOpts := mount.IsBind(options)
  53. if bind {
  54. err := n.doNsenterMount(source, target, fstype, bindOpts)
  55. if err != nil {
  56. return err
  57. }
  58. return n.doNsenterMount(source, target, fstype, bindRemountOpts)
  59. }
  60. return n.doNsenterMount(source, target, fstype, options)
  61. }
  62. // doNsenterMount nsenters the host's mount namespace and performs the
  63. // requested mount.
  64. func (n *Mounter) doNsenterMount(source, target, fstype string, options []string) error {
  65. klog.V(5).Infof("nsenter mount %s %s %s %v", source, target, fstype, options)
  66. cmd, args := n.makeNsenterArgs(source, target, fstype, options)
  67. outputBytes, err := n.ne.Exec(cmd, args).CombinedOutput()
  68. if len(outputBytes) != 0 {
  69. klog.V(5).Infof("Output of mounting %s to %s: %v", source, target, string(outputBytes))
  70. }
  71. return err
  72. }
  73. // makeNsenterArgs makes a list of argument to nsenter in order to do the
  74. // requested mount.
  75. func (n *Mounter) makeNsenterArgs(source, target, fstype string, options []string) (string, []string) {
  76. mountCmd := n.ne.AbsHostPath("mount")
  77. mountArgs := mount.MakeMountArgs(source, target, fstype, options)
  78. if systemdRunPath, hasSystemd := n.ne.SupportsSystemd(); hasSystemd {
  79. // Complete command line:
  80. // nsenter --mount=/rootfs/proc/1/ns/mnt -- /bin/systemd-run --description=... --scope -- /bin/mount -t <type> <what> <where>
  81. // Expected flow is:
  82. // * nsenter breaks out of container's mount namespace and executes
  83. // host's systemd-run.
  84. // * systemd-run creates a transient scope (=~ cgroup) and executes its
  85. // argument (/bin/mount) there.
  86. // * mount does its job, forks a fuse daemon if necessary and finishes.
  87. // (systemd-run --scope finishes at this point, returning mount's exit
  88. // code and stdout/stderr - thats one of --scope benefits).
  89. // * systemd keeps the fuse daemon running in the scope (i.e. in its own
  90. // cgroup) until the fuse daemon dies (another --scope benefit).
  91. // Kubelet container can be restarted and the fuse daemon survives.
  92. // * When the daemon dies (e.g. during unmount) systemd removes the
  93. // scope automatically.
  94. mountCmd, mountArgs = mount.AddSystemdScope(systemdRunPath, target, mountCmd, mountArgs)
  95. } else {
  96. // Fall back to simple mount when the host has no systemd.
  97. // Complete command line:
  98. // nsenter --mount=/rootfs/proc/1/ns/mnt -- /bin/mount -t <type> <what> <where>
  99. // Expected flow is:
  100. // * nsenter breaks out of container's mount namespace and executes host's /bin/mount.
  101. // * mount does its job, forks a fuse daemon if necessary and finishes.
  102. // * Any fuse daemon runs in cgroup of kubelet docker container,
  103. // restart of kubelet container will kill it!
  104. // No code here, mountCmd and mountArgs use /bin/mount
  105. }
  106. return mountCmd, mountArgs
  107. }
  108. // Unmount runs umount(8) in the host's mount namespace.
  109. func (n *Mounter) Unmount(target string) error {
  110. args := []string{target}
  111. // No need to execute systemd-run here, it's enough that unmount is executed
  112. // in the host's mount namespace. It will finish appropriate fuse daemon(s)
  113. // running in any scope.
  114. klog.V(5).Infof("nsenter unmount args: %v", args)
  115. outputBytes, err := n.ne.Exec("umount", args).CombinedOutput()
  116. if len(outputBytes) != 0 {
  117. klog.V(5).Infof("Output of unmounting %s: %v", target, string(outputBytes))
  118. }
  119. return err
  120. }
  121. // List returns a list of all mounted filesystems in the host's mount namespace.
  122. func (*Mounter) List() ([]mount.MountPoint, error) {
  123. return mount.ListProcMounts(hostProcMountsPath)
  124. }
  125. // IsMountPointMatch tests if dir and mp are the same path
  126. func (*Mounter) IsMountPointMatch(mp mount.MountPoint, dir string) bool {
  127. deletedDir := fmt.Sprintf("%s\\040(deleted)", dir)
  128. return (mp.Path == dir) || (mp.Path == deletedDir)
  129. }
  130. // IsLikelyNotMountPoint determines whether a path is a mountpoint by calling findmnt
  131. // in the host's root mount namespace.
  132. func (n *Mounter) IsLikelyNotMountPoint(file string) (bool, error) {
  133. file, err := filepath.Abs(file)
  134. if err != nil {
  135. return true, err
  136. }
  137. // Check the directory exists
  138. if _, err = os.Stat(file); os.IsNotExist(err) {
  139. klog.V(5).Infof("findmnt: directory %s does not exist", file)
  140. return true, err
  141. }
  142. // Resolve any symlinks in file, kernel would do the same and use the resolved path in /proc/mounts
  143. resolvedFile, err := n.EvalHostSymlinks(file)
  144. if err != nil {
  145. return true, err
  146. }
  147. // Add --first-only option: since we are testing for the absence of a mountpoint, it is sufficient to get only
  148. // the first of multiple possible mountpoints using --first-only.
  149. // Also add fstype output to make sure that the output of target file will give the full path
  150. // TODO: Need more refactoring for this function. Track the solution with issue #26996
  151. args := []string{"-o", "target,fstype", "--noheadings", "--first-only", "--target", resolvedFile}
  152. klog.V(5).Infof("nsenter findmnt args: %v", args)
  153. out, err := n.ne.Exec("findmnt", args).CombinedOutput()
  154. if err != nil {
  155. klog.V(2).Infof("Failed findmnt command for path %s: %s %v", resolvedFile, out, err)
  156. // Different operating systems behave differently for paths which are not mount points.
  157. // On older versions (e.g. 2.20.1) we'd get error, on newer ones (e.g. 2.26.2) we'd get "/".
  158. // It's safer to assume that it's not a mount point.
  159. return true, nil
  160. }
  161. mountTarget, err := parseFindMnt(string(out))
  162. if err != nil {
  163. return false, err
  164. }
  165. klog.V(5).Infof("IsLikelyNotMountPoint findmnt output for path %s: %v:", resolvedFile, mountTarget)
  166. if mountTarget == resolvedFile {
  167. klog.V(5).Infof("IsLikelyNotMountPoint: %s is a mount point", resolvedFile)
  168. return false, nil
  169. }
  170. klog.V(5).Infof("IsLikelyNotMountPoint: %s is not a mount point", resolvedFile)
  171. return true, nil
  172. }
  173. // parse output of "findmnt -o target,fstype" and return just the target
  174. func parseFindMnt(out string) (string, error) {
  175. // cut trailing newline
  176. out = strings.TrimSuffix(out, "\n")
  177. // cut everything after the last space - it's the filesystem type
  178. i := strings.LastIndex(out, " ")
  179. if i == -1 {
  180. return "", fmt.Errorf("error parsing findmnt output, expected at least one space: %q", out)
  181. }
  182. return out[:i], nil
  183. }
  184. // DeviceOpened checks if block device in use by calling Open with O_EXCL flag.
  185. // Returns true if open returns errno EBUSY, and false if errno is nil.
  186. // Returns an error if errno is any error other than EBUSY.
  187. // Returns with error if pathname is not a device.
  188. func (n *Mounter) DeviceOpened(pathname string) (bool, error) {
  189. return mount.ExclusiveOpenFailsOnDevice(pathname)
  190. }
  191. // PathIsDevice uses FileInfo returned from os.Stat to check if path refers
  192. // to a device.
  193. func (n *Mounter) PathIsDevice(pathname string) (bool, error) {
  194. pathType, err := n.GetFileType(pathname)
  195. isDevice := pathType == mount.FileTypeCharDev || pathType == mount.FileTypeBlockDev
  196. return isDevice, err
  197. }
  198. //GetDeviceNameFromMount given a mount point, find the volume id from checking /proc/mounts
  199. func (n *Mounter) GetDeviceNameFromMount(mountPath, pluginMountDir string) (string, error) {
  200. return mount.GetDeviceNameFromMountLinux(n, mountPath, pluginMountDir)
  201. }
  202. // MakeRShared checks if path is shared and bind-mounts it as rshared if needed.
  203. func (n *Mounter) MakeRShared(path string) error {
  204. return mount.DoMakeRShared(path, hostProcMountinfoPath)
  205. }
  206. // GetFileType checks for file/directory/socket/block/character devices.
  207. func (n *Mounter) GetFileType(pathname string) (mount.FileType, error) {
  208. var pathType mount.FileType
  209. outputBytes, err := n.ne.Exec("stat", []string{"-L", "--printf=%F", pathname}).CombinedOutput()
  210. if err != nil {
  211. if strings.Contains(string(outputBytes), "No such file") {
  212. err = fmt.Errorf("%s does not exist", pathname)
  213. } else {
  214. err = fmt.Errorf("stat %s error: %v", pathname, string(outputBytes))
  215. }
  216. return pathType, err
  217. }
  218. switch string(outputBytes) {
  219. case "socket":
  220. return mount.FileTypeSocket, nil
  221. case "character special file":
  222. return mount.FileTypeCharDev, nil
  223. case "block special file":
  224. return mount.FileTypeBlockDev, nil
  225. case "directory":
  226. return mount.FileTypeDirectory, nil
  227. case "regular file", "regular empty file":
  228. return mount.FileTypeFile, nil
  229. }
  230. return pathType, fmt.Errorf("only recognise file, directory, socket, block device and character device")
  231. }
  232. // MakeDir creates a new directory.
  233. func (n *Mounter) MakeDir(pathname string) error {
  234. args := []string{"-p", pathname}
  235. if _, err := n.ne.Exec("mkdir", args).CombinedOutput(); err != nil {
  236. return err
  237. }
  238. return nil
  239. }
  240. // MakeFile creates an empty file.
  241. func (n *Mounter) MakeFile(pathname string) error {
  242. args := []string{pathname}
  243. if _, err := n.ne.Exec("touch", args).CombinedOutput(); err != nil {
  244. return err
  245. }
  246. return nil
  247. }
  248. // ExistsPath checks if pathname exists.
  249. // Error is returned on any other error than "file not found".
  250. func (n *Mounter) ExistsPath(pathname string) (bool, error) {
  251. // Resolve the symlinks but allow the target not to exist. EvalSymlinks
  252. // would return an generic error when the target does not exist.
  253. hostPath, err := n.ne.EvalSymlinks(pathname, false /* mustExist */)
  254. if err != nil {
  255. return false, err
  256. }
  257. kubeletpath := n.ne.KubeletPath(hostPath)
  258. return utilpath.Exists(utilpath.CheckFollowSymlink, kubeletpath)
  259. }
  260. // EvalHostSymlinks returns the path name after evaluating symlinks.
  261. func (n *Mounter) EvalHostSymlinks(pathname string) (string, error) {
  262. return n.ne.EvalSymlinks(pathname, true)
  263. }
  264. // GetMountRefs finds all mount references to the path, returns a
  265. // list of paths. Path could be a mountpoint path, device or a normal
  266. // directory (for bind mount).
  267. func (n *Mounter) GetMountRefs(pathname string) ([]string, error) {
  268. pathExists, pathErr := mount.PathExists(pathname)
  269. if !pathExists || mount.IsCorruptedMnt(pathErr) {
  270. return []string{}, nil
  271. } else if pathErr != nil {
  272. return nil, fmt.Errorf("Error checking path %s: %v", pathname, pathErr)
  273. }
  274. hostpath, err := n.ne.EvalSymlinks(pathname, true /* mustExist */)
  275. if err != nil {
  276. return nil, err
  277. }
  278. return mount.SearchMountPoints(hostpath, hostProcMountinfoPath)
  279. }
  280. // GetFSGroup returns FSGroup of pathname.
  281. func (n *Mounter) GetFSGroup(pathname string) (int64, error) {
  282. hostPath, err := n.ne.EvalSymlinks(pathname, true /* mustExist */)
  283. if err != nil {
  284. return -1, err
  285. }
  286. kubeletpath := n.ne.KubeletPath(hostPath)
  287. return mount.GetFSGroupLinux(kubeletpath)
  288. }
  289. // GetSELinuxSupport tests if pathname is on a mount that supports SELinux.
  290. func (n *Mounter) GetSELinuxSupport(pathname string) (bool, error) {
  291. return mount.GetSELinux(pathname, hostProcMountsPath)
  292. }
  293. // GetMode returns permissions of pathname.
  294. func (n *Mounter) GetMode(pathname string) (os.FileMode, error) {
  295. hostPath, err := n.ne.EvalSymlinks(pathname, true /* mustExist */)
  296. if err != nil {
  297. return 0, err
  298. }
  299. kubeletpath := n.ne.KubeletPath(hostPath)
  300. return mount.GetModeLinux(kubeletpath)
  301. }