Debian Codegraph @

mount_linux.go

raw
1 //go:build linux
2
3 /*
4 Copyright 2014 The Kubernetes Authors.
5
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17 */
18
19 package mount
20
21 import (
22 "context"
23 "errors"
24 "fmt"
25 "io/fs"
26 "os"
27 "os/exec"
28 "path/filepath"
29 "strconv"
30 "strings"
31 "syscall"
32 "time"
33
34 "github.com/moby/sys/mountinfo"
35 "golang.org/x/sys/unix"
36
37 "k8s.io/klog/v2"
38 utilexec "k8s.io/utils/exec"
39 )
40
41 const (
42 // Number of fields per line in /proc/mounts as per the fstab man page.
43 expectedNumFieldsPerLine = 6
44 // Location of the mount file to use
45 procMountsPath = "/proc/mounts"
46 // Location of the mountinfo file
47 procMountInfoPath = "/proc/self/mountinfo"
48 // 'fsck' found errors and corrected them
49 fsckErrorsCorrected = 1
50 // 'fsck' found errors but exited without correcting them
51 fsckErrorsUncorrected = 4
52 // Error thrown by exec cmd.Run() when process spawned by cmd.Start() completes before cmd.Wait() is called (see - k/k issue #103753)
53 errNoChildProcesses = "wait: no child processes"
54 // Error returned by some `umount` implementations when the specified path is not a mount point
55 errNotMounted = "not mounted"
56 )
57
58 var (
59 // Error statx support since Linux 4.11, https://man7.org/linux/man-pages/man2/statx.2.html
60 errStatxNotSupport = errors.New("the statx syscall is not supported. At least Linux kernel 4.11 is needed")
61 )
62
63 // Mounter provides the default implementation of mount.Interface
64 // for the linux platform. This implementation assumes that the
65 // kubelet is running in the host's root mount namespace.
66 type Mounter struct {
67 mounterPath string
68 withSystemd *bool
69 trySystemd bool
70 withSafeNotMountedBehavior bool
71 }
72
73 var _ MounterForceUnmounter = &Mounter{}
74
75 // New returns a mount.Interface for the current system.
76 // It provides options to override the default mounter behavior.
77 // mounterPath allows using an alternative to `/bin/mount` for mounting.
78 func New(mounterPath string) Interface {
79 return &Mounter{
80 mounterPath: mounterPath,
81 trySystemd: true,
82 withSafeNotMountedBehavior: detectSafeNotMountedBehavior(),
83 }
84 }
85
86 // NewWithoutSystemd returns a Linux specific mount.Interface for the current
87 // system. It provides options to override the default mounter behavior.
88 // mounterPath allows using an alternative to `/bin/mount` for mounting. Any
89 // detection for systemd functionality is disabled with this Mounter.
90 func NewWithoutSystemd(mounterPath string) Interface {
91 return &Mounter{
92 mounterPath: mounterPath,
93 trySystemd: false,
94 withSafeNotMountedBehavior: detectSafeNotMountedBehavior(),
95 }
96 }
97
98 // hasSystemd validates that the withSystemd bool is set, if it is not,
99 // detectSystemd will be called once for this Mounter instance.
100 func (mounter *Mounter) hasSystemd() bool {
101 if !mounter.trySystemd {
102 mounter.withSystemd = &mounter.trySystemd
103 }
104
105 if mounter.withSystemd == nil {
106 withSystemd := detectSystemd()
107 mounter.withSystemd = &withSystemd
108 }
109
110 return *mounter.withSystemd
111 }
112
113 // Map unix.Statfs mount flags ro, nodev, noexec, nosuid, noatime, relatime,
114 // nodiratime to mount option flag strings.
115 func getBindMountOptions(path string, statfs func(path string, buf *unix.Statfs_t) (err error)) ([]string, error) {
116 var s unix.Statfs_t
117 var mountOpts []string
118 if err := statfs(path, &s); err != nil {
119 return nil, &os.PathError{Op: "statfs", Path: path, Err: err}
120 }
121 flagMapping := map[int]string{
122 unix.MS_RDONLY: "ro",
123 unix.MS_NODEV: "nodev",
124 unix.MS_NOEXEC: "noexec",
125 unix.MS_NOSUID: "nosuid",
126 unix.MS_NOATIME: "noatime",
127 unix.MS_RELATIME: "relatime",
128 unix.MS_NODIRATIME: "nodiratime",
129 }
130 for k, v := range flagMapping {
131 if int(s.Flags)&k == k {
132 mountOpts = append(mountOpts, v)
133 }
134 }
135 return mountOpts, nil
136 }
137
138 // Performs a bind mount with the specified options, and then remounts
139 // the mount point with the same `nodev`, `nosuid`, `noexec`, `nosuid`, `noatime`,
140 // `relatime`, `nodiratime` options as the original mount point.
141 func (mounter *Mounter) bindMountSensitive(mounterPath string, mountCmd string, source string, target string, fstype string, bindOpts []string, bindRemountOpts []string, bindRemountOptsSensitive []string, mountFlags []string, systemdMountRequired bool) error {
142 err := mounter.doMount(mounterPath, mountCmd, source, target, fstype, bindOpts, bindRemountOptsSensitive, mountFlags, systemdMountRequired)
143 if err != nil {
144 return err
145 }
146 // Check if the source has ro, nodev, noexec, nosuid, noatime, relatime,
147 // nodiratime flag...
148 fixMountOpts, err := getBindMountOptions(source, unix.Statfs)
149 if err != nil {
150 return &os.PathError{Op: "statfs", Path: source, Err: err}
151 }
152 // ... and retry the mount with flags found above.
153 bindRemountOpts = append(bindRemountOpts, fixMountOpts...)
154 return mounter.doMount(mounterPath, mountCmd, source, target, fstype, bindRemountOpts, bindRemountOptsSensitive, mountFlags, systemdMountRequired)
155 }
156
157 // Mount mounts source to target as fstype with given options. 'source' and 'fstype' must
158 // be an empty string in case it's not required, e.g. for remount, or for auto filesystem
159 // type, where kernel handles fstype for you. The mount 'options' is a list of options,
160 // currently come from mount(8), e.g. "ro", "remount", "bind", etc. If no more option is
161 // required, call Mount with an empty string list or nil.
162 func (mounter *Mounter) Mount(source string, target string, fstype string, options []string) error {
163 return mounter.MountSensitive(source, target, fstype, options, nil)
164 }
165
166 // MountSensitive is the same as Mount() but this method allows
167 // sensitiveOptions to be passed in a separate parameter from the normal
168 // mount options and ensures the sensitiveOptions are never logged. This
169 // method should be used by callers that pass sensitive material (like
170 // passwords) as mount options.
171 func (mounter *Mounter) MountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error {
172 // Path to mounter binary if containerized mounter is needed. Otherwise, it is set to empty.
173 // All Linux distros are expected to be shipped with a mount utility that a support bind mounts.
174 mounterPath := ""
175 bind, bindOpts, bindRemountOpts, bindRemountOptsSensitive := MakeBindOptsSensitive(options, sensitiveOptions)
176 if bind {
177 return mounter.bindMountSensitive(mounterPath, defaultMountCommand, source, target, fstype, bindOpts, bindRemountOpts, bindRemountOptsSensitive, nil /* mountFlags */, mounter.trySystemd)
178 }
179 // The list of filesystems that require containerized mounter on GCI image cluster
180 fsTypesNeedMounter := map[string]struct{}{
181 "nfs": {},
182 "glusterfs": {},
183 "ceph": {},
184 "cifs": {},
185 }
186 if _, ok := fsTypesNeedMounter[fstype]; ok {
187 mounterPath = mounter.mounterPath
188 }
189 return mounter.doMount(mounterPath, defaultMountCommand, source, target, fstype, options, sensitiveOptions, nil /* mountFlags */, mounter.trySystemd)
190 }
191
192 // MountSensitiveWithoutSystemd is the same as MountSensitive() but disable using systemd mount.
193 func (mounter *Mounter) MountSensitiveWithoutSystemd(source string, target string, fstype string, options []string, sensitiveOptions []string) error {
194 return mounter.MountSensitiveWithoutSystemdWithMountFlags(source, target, fstype, options, sensitiveOptions, nil /* mountFlags */)
195 }
196
197 // MountSensitiveWithoutSystemdWithMountFlags is the same as MountSensitiveWithoutSystemd with additional mount flags.
198 func (mounter *Mounter) MountSensitiveWithoutSystemdWithMountFlags(source string, target string, fstype string, options []string, sensitiveOptions []string, mountFlags []string) error {
199 mounterPath := ""
200 bind, bindOpts, bindRemountOpts, bindRemountOptsSensitive := MakeBindOptsSensitive(options, sensitiveOptions)
201 if bind {
202 return mounter.bindMountSensitive(mounterPath, defaultMountCommand, source, target, fstype, bindOpts, bindRemountOpts, bindRemountOptsSensitive, mountFlags, false)
203 }
204 // The list of filesystems that require containerized mounter on GCI image cluster
205 fsTypesNeedMounter := map[string]struct{}{
206 "nfs": {},
207 "glusterfs": {},
208 "ceph": {},
209 "cifs": {},
210 }
211 if _, ok := fsTypesNeedMounter[fstype]; ok {
212 mounterPath = mounter.mounterPath
213 }
214 return mounter.doMount(mounterPath, defaultMountCommand, source, target, fstype, options, sensitiveOptions, mountFlags, false)
215 }
216
217 // doMount runs the mount command. mounterPath is the path to mounter binary if containerized mounter is used.
218 // sensitiveOptions is an extension of options except they will not be logged (because they may contain sensitive material)
219 // systemdMountRequired is an extension of option to decide whether uses systemd mount.
220 func (mounter *Mounter) doMount(mounterPath string, mountCmd string, source string, target string, fstype string, options []string, sensitiveOptions []string, mountFlags []string, systemdMountRequired bool) error {
221 mountArgs, mountArgsLogStr := MakeMountArgsSensitiveWithMountFlags(source, target, fstype, options, sensitiveOptions, mountFlags)
222 if len(mounterPath) > 0 {
223 mountArgs = append([]string{mountCmd}, mountArgs...)
224 mountArgsLogStr = mountCmd + " " + mountArgsLogStr
225 mountCmd = mounterPath
226 }
227
228 if systemdMountRequired && mounter.hasSystemd() {
229 // Try to run mount via systemd-run --scope. This will escape the
230 // service where kubelet runs and any fuse daemons will be started in a
231 // specific scope. kubelet service than can be restarted without killing
232 // these fuse daemons.
233 //
234 // Complete command line (when mounterPath is not used):
235 // systemd-run --description=... --scope -- mount -t <type> <what> <where>
236 //
237 // Expected flow:
238 // * systemd-run creates a transient scope (=~ cgroup) and executes its
239 // argument (/bin/mount) there.
240 // * mount does its job, forks a fuse daemon if necessary and finishes.
241 // (systemd-run --scope finishes at this point, returning mount's exit
242 // code and stdout/stderr - thats one of --scope benefits).
243 // * systemd keeps the fuse daemon running in the scope (i.e. in its own
244 // cgroup) until the fuse daemon dies (another --scope benefit).
245 // Kubelet service can be restarted and the fuse daemon survives.
246 // * When the fuse daemon dies (e.g. during unmount) systemd removes the
247 // scope automatically.
248 //
249 // systemd-mount is not used because it's too new for older distros
250 // (CentOS 7, Debian Jessie).
251 mountCmd, mountArgs, mountArgsLogStr = AddSystemdScopeSensitive("systemd-run", target, mountCmd, mountArgs, mountArgsLogStr)
252 // } else {
253 // No systemd-run on the host (or we failed to check it), assume kubelet
254 // does not run as a systemd service.
255 // No code here, mountCmd and mountArgs are already populated.
256 }
257
258 // Logging with sensitive mount options removed.
259 klog.V(4).Infof("Mounting cmd (%s) with arguments (%s)", mountCmd, mountArgsLogStr)
260 command := exec.Command(mountCmd, mountArgs...)
261 output, err := command.CombinedOutput()
262 if err != nil {
263 if err.Error() == errNoChildProcesses {
264 if command.ProcessState.Success() {
265 // We don't consider errNoChildProcesses an error if the process itself succeeded (see - k/k issue #103753).
266 return nil
267 }
268 // Rewrite err with the actual exit error of the process.
269 err = &exec.ExitError{ProcessState: command.ProcessState}
270 }
271 klog.Errorf("Mount failed: %v\nMounting command: %s\nMounting arguments: %s\nOutput: %s\n", err, mountCmd, mountArgsLogStr, string(output))
272 return fmt.Errorf("mount failed: %v\nMounting command: %s\nMounting arguments: %s\nOutput: %s",
273 err, mountCmd, mountArgsLogStr, string(output))
274 }
275 return err
276 }
277
278 // detectSystemd returns true if OS runs with systemd as init. When not sure
279 // (permission errors, ...), it returns false.
280 // There may be different ways how to detect systemd, this one makes sure that
281 // systemd-runs (needed by Mount()) works.
282 func detectSystemd() bool {
283 if _, err := exec.LookPath("systemd-run"); err != nil {
284 klog.V(2).Infof("Detected OS without systemd")
285 return false
286 }
287 // Try to run systemd-run --scope /bin/true, that should be enough
288 // to make sure that systemd is really running and not just installed,
289 // which happens when running in a container with a systemd-based image
290 // but with different pid 1.
291 cmd := exec.Command("systemd-run", "--description=Kubernetes systemd probe", "--scope", "true")
292 output, err := cmd.CombinedOutput()
293 if err != nil {
294 klog.V(2).Infof("Cannot run systemd-run, assuming non-systemd OS")
295 klog.V(4).Infof("systemd-run output: %s, failed with: %v", string(output), err)
296 return false
297 }
298 klog.V(2).Infof("Detected OS with systemd")
299 return true
300 }
301
302 // detectSafeNotMountedBehavior returns true if the umount implementation replies "not mounted"
303 // when the specified path is not mounted. When not sure (permission errors, ...), it returns false.
304 // When possible, we will trust umount's message and avoid doing our own mount point checks.
305 // More info: https://github.com/util-linux/util-linux/blob/v2.2/mount/umount.c#L179
306 func detectSafeNotMountedBehavior() bool {
307 return detectSafeNotMountedBehaviorWithExec(utilexec.New())
308 }
309
310 // detectSafeNotMountedBehaviorWithExec is for testing with FakeExec.
311 func detectSafeNotMountedBehaviorWithExec(exec utilexec.Interface) bool {
312 // create a temp dir and try to umount it
313 path, err := os.MkdirTemp("", "kubelet-detect-safe-umount")
314 if err != nil {
315 klog.V(4).Infof("Cannot create temp dir to detect safe 'not mounted' behavior: %v", err)
316 return false
317 }
318 defer os.RemoveAll(path)
319 cmd := exec.Command("umount", path)
320 output, err := cmd.CombinedOutput()
321 if err != nil {
322 if strings.Contains(string(output), errNotMounted) {
323 klog.V(4).Infof("Detected umount with safe 'not mounted' behavior")
324 return true
325 }
326 klog.V(4).Infof("'umount %s' failed with: %v, output: %s", path, err, string(output))
327 }
328 klog.V(4).Infof("Detected umount with unsafe 'not mounted' behavior")
329 return false
330 }
331
332 // MakeMountArgs makes the arguments to the mount(8) command.
333 // options MUST not contain sensitive material (like passwords).
334 func MakeMountArgs(source, target, fstype string, options []string) (mountArgs []string) {
335 mountArgs, _ = MakeMountArgsSensitive(source, target, fstype, options, nil /* sensitiveOptions */)
336 return mountArgs
337 }
338
339 // MakeMountArgsSensitive makes the arguments to the mount(8) command.
340 // sensitiveOptions is an extension of options except they will not be logged (because they may contain sensitive material)
341 func MakeMountArgsSensitive(source, target, fstype string, options []string, sensitiveOptions []string) (mountArgs []string, mountArgsLogStr string) {
342 return MakeMountArgsSensitiveWithMountFlags(source, target, fstype, options, sensitiveOptions, nil /* mountFlags */)
343 }
344
345 // MakeMountArgsSensitiveWithMountFlags makes the arguments to the mount(8) command.
346 // sensitiveOptions is an extension of options except they will not be logged (because they may contain sensitive material)
347 // mountFlags are additional mount flags that are not related with the fstype
348 // and mount options
349 func MakeMountArgsSensitiveWithMountFlags(source, target, fstype string, options []string, sensitiveOptions []string, mountFlags []string) (mountArgs []string, mountArgsLogStr string) {
350 // Build mount command as follows:
351 // mount [$mountFlags] [-t $fstype] [-o $options] [$source] $target
352 mountArgs = []string{}
353 mountArgsLogStr = ""
354
355 mountArgs = append(mountArgs, mountFlags...)
356 mountArgsLogStr += strings.Join(mountFlags, " ")
357
358 if len(fstype) > 0 {
359 mountArgs = append(mountArgs, "-t", fstype)
360 mountArgsLogStr += strings.Join(mountArgs, " ")
361 }
362 if len(options) > 0 || len(sensitiveOptions) > 0 {
363 combinedOptions := []string{}
364 combinedOptions = append(combinedOptions, options...)
365 combinedOptions = append(combinedOptions, sensitiveOptions...)
366 mountArgs = append(mountArgs, "-o", strings.Join(combinedOptions, ","))
367 // exclude sensitiveOptions from log string
368 mountArgsLogStr += " -o " + sanitizedOptionsForLogging(options, sensitiveOptions)
369 }
370 if len(source) > 0 {
371 mountArgs = append(mountArgs, source)
372 mountArgsLogStr += " " + source
373 }
374 mountArgs = append(mountArgs, target)
375 mountArgsLogStr += " " + target
376
377 return mountArgs, mountArgsLogStr
378 }
379
380 // AddSystemdScope adds "system-run --scope" to given command line
381 // If args contains sensitive material, use AddSystemdScopeSensitive to construct
382 // a safe to log string.
383 func AddSystemdScope(systemdRunPath, mountName, command string, args []string) (string, []string) {
384 descriptionArg := fmt.Sprintf("--description=Kubernetes transient mount for %s", mountName)
385 systemdRunArgs := []string{descriptionArg, "--scope", "--", command}
386 return systemdRunPath, append(systemdRunArgs, args...)
387 }
388
389 // AddSystemdScopeSensitive adds "system-run --scope" to given command line
390 // It also accepts takes a sanitized string containing mount arguments, mountArgsLogStr,
391 // and returns the string appended to the systemd command for logging.
392 func AddSystemdScopeSensitive(systemdRunPath, mountName, command string, args []string, mountArgsLogStr string) (string, []string, string) {
393 descriptionArg := fmt.Sprintf("--description=Kubernetes transient mount for %s", mountName)
394 systemdRunArgs := []string{descriptionArg, "--scope", "--", command}
395 return systemdRunPath, append(systemdRunArgs, args...), strings.Join(systemdRunArgs, " ") + " " + mountArgsLogStr
396 }
397
398 // Unmount unmounts the target.
399 // If the mounter has safe "not mounted" behavior, no error will be returned when the target is not a mount point.
400 func (mounter *Mounter) Unmount(target string) error {
401 klog.V(4).Infof("Unmounting %s", target)
402 command := exec.Command("umount", target)
403 output, err := command.CombinedOutput()
404 if err != nil {
405 return checkUmountError(target, command, output, err, mounter.withSafeNotMountedBehavior)
406 }
407 return nil
408 }
409
410 // UnmountWithForce unmounts given target but will retry unmounting with force option
411 // after given timeout.
412 func (mounter *Mounter) UnmountWithForce(target string, umountTimeout time.Duration) error {
413 err := tryUnmount(target, mounter.withSafeNotMountedBehavior, umountTimeout)
414 if err != nil {
415 if err == context.DeadlineExceeded {
416 klog.V(2).Infof("Timed out waiting for unmount of %s, trying with -f", target)
417 err = forceUmount(target, mounter.withSafeNotMountedBehavior)
418 }
419 return err
420 }
421 return nil
422 }
423
424 // List returns a list of all mounted filesystems.
425 func (*Mounter) List() ([]MountPoint, error) {
426 return ListProcMounts(procMountsPath)
427 }
428
429 func statx(file string) (unix.Statx_t, error) {
430 var stat unix.Statx_t
431 if err := unix.Statx(unix.AT_FDCWD, file, unix.AT_STATX_DONT_SYNC, 0, &stat); err != nil {
432 if err == unix.ENOSYS {
433 return stat, errStatxNotSupport
434 }
435
436 return stat, err
437 }
438
439 return stat, nil
440 }
441
442 func (mounter *Mounter) isLikelyNotMountPointStat(file string) (bool, error) {
443 stat, err := os.Stat(file)
444 if err != nil {
445 return true, err
446 }
447 rootStat, err := os.Stat(filepath.Dir(strings.TrimSuffix(file, "/")))
448 if err != nil {
449 return true, err
450 }
451 // If the directory has a different device as parent, then it is a mountpoint.
452 if stat.Sys().(*syscall.Stat_t).Dev != rootStat.Sys().(*syscall.Stat_t).Dev {
453 return false, nil
454 }
455
456 return true, nil
457 }
458
459 func (mounter *Mounter) isLikelyNotMountPointStatx(file string) (bool, error) {
460 var stat, rootStat unix.Statx_t
461 var err error
462
463 if stat, err = statx(file); err != nil {
464 return true, err
465 }
466
467 if stat.Attributes_mask != 0 {
468 if stat.Attributes_mask&unix.STATX_ATTR_MOUNT_ROOT != 0 {
469 if stat.Attributes&unix.STATX_ATTR_MOUNT_ROOT != 0 {
470 // file is a mountpoint
471 return false, nil
472 } else {
473 // no need to check rootStat if unix.STATX_ATTR_MOUNT_ROOT supported
474 return true, nil
475 }
476 }
477 }
478
479 root := filepath.Dir(strings.TrimSuffix(file, "/"))
480 if rootStat, err = statx(root); err != nil {
481 return true, err
482 }
483
484 return (stat.Dev_major == rootStat.Dev_major && stat.Dev_minor == rootStat.Dev_minor), nil
485 }
486
487 // IsLikelyNotMountPoint determines if a directory is not a mountpoint.
488 // It is fast but not necessarily ALWAYS correct. If the path is in fact
489 // a bind mount from one part of a mount to another it will not be detected.
490 // It also can not distinguish between mountpoints and symbolic links.
491 // mkdir /tmp/a /tmp/b; mount --bind /tmp/a /tmp/b; IsLikelyNotMountPoint("/tmp/b")
492 // will return true. When in fact /tmp/b is a mount point. If this situation
493 // is of interest to you, don't use this function...
494 func (mounter *Mounter) IsLikelyNotMountPoint(file string) (bool, error) {
495 notMountPoint, err := mounter.isLikelyNotMountPointStatx(file)
496 if errors.Is(err, errStatxNotSupport) {
497 // fall back to isLikelyNotMountPointStat
498 return mounter.isLikelyNotMountPointStat(file)
499 }
500
501 return notMountPoint, err
502 }
503
504 // CanSafelySkipMountPointCheck relies on the detected behavior of umount when given a target that is not a mount point.
505 func (mounter *Mounter) CanSafelySkipMountPointCheck() bool {
506 return mounter.withSafeNotMountedBehavior
507 }
508
509 // GetMountRefs finds all mount references to pathname, returns a
510 // list of paths. Path could be a mountpoint or a normal
511 // directory (for bind mount).
512 func (mounter *Mounter) GetMountRefs(pathname string) ([]string, error) {
513 pathExists, pathErr := PathExists(pathname)
514 if !pathExists {
515 return []string{}, nil
516 } else if IsCorruptedMnt(pathErr) {
517 klog.Warningf("GetMountRefs found corrupted mount at %s, treating as unmounted path", pathname)
518 return []string{}, nil
519 } else if pathErr != nil {
520 return nil, fmt.Errorf("error checking path %s: %v", pathname, pathErr)
521 }
522 realpath, err := filepath.EvalSymlinks(pathname)
523 if err != nil {
524 return nil, err
525 }
526 return SearchMountPoints(realpath, procMountInfoPath)
527 }
528
529 // checkAndRepairFileSystem checks and repairs filesystems using command fsck.
530 func (mounter *SafeFormatAndMount) checkAndRepairFilesystem(source string) error {
531 klog.V(4).Infof("Checking for issues with fsck on disk: %s", source)
532 args := []string{"-a", source}
533 out, err := mounter.Exec.Command("fsck", args...).CombinedOutput()
534 if err != nil {
535 ee, isExitError := err.(utilexec.ExitError)
536 switch {
537 case err == utilexec.ErrExecutableNotFound:
538 klog.Warningf("'fsck' not found on system; continuing mount without running 'fsck'.")
539 case isExitError && ee.ExitStatus() == fsckErrorsCorrected:
540 klog.Infof("Device %s has errors which were corrected by fsck.", source)
541 case isExitError && ee.ExitStatus() == fsckErrorsUncorrected:
542 return NewMountError(HasFilesystemErrors, "'fsck' found errors on device %s but could not correct them: %s", source, string(out))
543 case isExitError && ee.ExitStatus() > fsckErrorsUncorrected:
544 klog.Infof("`fsck` error %s", string(out))
545 default:
546 klog.Warningf("fsck on device %s failed with error %v, output: %v", source, err, string(out))
547 }
548 }
549 return nil
550 }
551
552 // formatAndMount uses unix utils to format and mount the given disk
553 func (mounter *SafeFormatAndMount) formatAndMountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string, formatOptions []string) error {
554 readOnly := false
555 for _, option := range options {
556 if option == "ro" {
557 readOnly = true
558 break
559 }
560 }
561 if !readOnly {
562 // Check sensitiveOptions for ro
563 for _, option := range sensitiveOptions {
564 if option == "ro" {
565 readOnly = true
566 break
567 }
568 }
569 }
570
571 options = append(options, "defaults")
572 mountErrorValue := UnknownMountError
573
574 // Check if the disk is already formatted
575 existingFormat, err := mounter.GetDiskFormat(source)
576 if err != nil {
577 return NewMountError(GetDiskFormatFailed, "failed to get disk format of disk %s: %v", source, err)
578 }
579
580 // Use 'ext4' as the default
581 if len(fstype) == 0 {
582 fstype = "ext4"
583 }
584
585 if existingFormat == "" {
586 // Do not attempt to format the disk if mounting as readonly, return an error to reflect this.
587 if readOnly {
588 return NewMountError(UnformattedReadOnly, "cannot mount unformatted disk %s as we are manipulating it in read-only mode", source)
589 }
590
591 // Disk is unformatted so format it.
592 args := []string{source}
593 if fstype == "ext4" || fstype == "ext3" {
594 args = []string{
595 "-F", // Force flag
596 "-m0", // Zero blocks reserved for super-user
597 source,
598 }
599 } else if fstype == "xfs" {
600 args = []string{
601 "-f", // force flag
602 source,
603 }
604 }
605 args = append(formatOptions, args...)
606
607 klog.Infof("Disk %q appears to be unformatted, attempting to format as type: %q with options: %v", source, fstype, args)
608
609 output, err := mounter.format(fstype, args)
610 if err != nil {
611 // Do not log sensitiveOptions only options
612 sensitiveOptionsLog := sanitizedOptionsForLogging(options, sensitiveOptions)
613 detailedErr := fmt.Sprintf("format of disk %q failed: type:(%q) target:(%q) options:(%q) errcode:(%v) output:(%v) ", source, fstype, target, sensitiveOptionsLog, err, string(output))
614 klog.Error(detailedErr)
615 return NewMountError(FormatFailed, "%s", detailedErr)
616 }
617
618 klog.Infof("Disk successfully formatted (mkfs): %s - %s %s", fstype, source, target)
619 } else {
620 if fstype != existingFormat {
621 // Verify that the disk is formatted with filesystem type we are expecting
622 mountErrorValue = FilesystemMismatch
623 klog.Warningf("Configured to mount disk %s as %s but current format is %s, things might break", source, fstype, existingFormat)
624 }
625
626 if !readOnly {
627 // Run check tools on the disk to fix repairable issues, only do this for formatted volumes requested as rw.
628 err := mounter.checkAndRepairFilesystem(source)
629 if err != nil {
630 return err
631 }
632 }
633 }
634
635 // Mount the disk
636 klog.V(4).Infof("Attempting to mount disk %s in %s format at %s", source, fstype, target)
637 if err := mounter.MountSensitive(source, target, fstype, options, sensitiveOptions); err != nil {
638 return NewMountError(mountErrorValue, "%s", err.Error())
639 }
640
641 return nil
642 }
643
644 func (mounter *SafeFormatAndMount) format(fstype string, args []string) ([]byte, error) {
645 if mounter.formatSem != nil {
646 done := make(chan struct{})
647 defer close(done)
648
649 mounter.formatSem <- struct{}{}
650
651 go func() {
652 defer func() { <-mounter.formatSem }()
653
654 timeout := time.NewTimer(mounter.formatTimeout)
655 defer timeout.Stop()
656
657 select {
658 case <-done:
659 case <-timeout.C:
660 }
661 }()
662 }
663
664 return mounter.Exec.Command("mkfs."+fstype, args...).CombinedOutput()
665 }
666
667 func getDiskFormat(exec utilexec.Interface, disk string) (string, error) {
668 args := []string{"-p", "-s", "TYPE", "-s", "PTTYPE", "-o", "export", disk}
669 klog.V(4).Infof("Attempting to determine if disk %q is formatted using blkid with args: (%v)", disk, args)
670 dataOut, err := exec.Command("blkid", args...).CombinedOutput()
671 output := string(dataOut)
672 klog.V(4).Infof("Output: %q", output)
673
674 if err != nil {
675 if exit, ok := err.(utilexec.ExitError); ok {
676 if exit.ExitStatus() == 2 {
677 // Disk device is unformatted.
678 // For `blkid`, if the specified token (TYPE/PTTYPE, etc) was
679 // not found, or no (specified) devices could be identified, an
680 // exit code of 2 is returned.
681 return "", nil
682 }
683 }
684 klog.Errorf("Could not determine if disk %q is formatted (%v)", disk, err)
685 return "", err
686 }
687
688 var fstype, pttype string
689
690 lines := strings.Split(output, "\n")
691 for _, l := range lines {
692 if len(l) <= 0 {
693 // Ignore empty line.
694 continue
695 }
696 cs := strings.Split(l, "=")
697 if len(cs) != 2 {
698 return "", fmt.Errorf("blkid returns invalid output: %s", output)
699 }
700 // TYPE is filesystem type, and PTTYPE is partition table type, according
701 // to https://www.kernel.org/pub/linux/utils/util-linux/v2.21/libblkid-docs/.
702 if cs[0] == "TYPE" {
703 fstype = cs[1]
704 } else if cs[0] == "PTTYPE" {
705 pttype = cs[1]
706 }
707 }
708
709 if len(pttype) > 0 {
710 klog.V(4).Infof("Disk %s detected partition table type: %s", disk, pttype)
711 // Returns a special non-empty string as filesystem type, then kubelet
712 // will not format it.
713 return "unknown data, probably partitions", nil
714 }
715
716 return fstype, nil
717 }
718
719 // GetDiskFormat uses 'blkid' to see if the given disk is unformatted
720 func (mounter *SafeFormatAndMount) GetDiskFormat(disk string) (string, error) {
721 return getDiskFormat(mounter.Exec, disk)
722 }
723
724 // ListProcMounts returns a list of all mounted filesystems.
725 func ListProcMounts(mountFilePath string) ([]MountPoint, error) {
726 content, err := readMountInfo(mountFilePath)
727 if err != nil {
728 return nil, err
729 }
730 return parseProcMounts(content)
731 }
732
733 func parseProcMounts(content []byte) ([]MountPoint, error) {
734 out := []MountPoint{}
735 lines := strings.Split(string(content), "\n")
736 for _, line := range lines {
737 if line == "" {
738 // the last split() item is empty string following the last \n
739 continue
740 }
741 fields := strings.Fields(line)
742 if len(fields) != expectedNumFieldsPerLine {
743 // Do not log line in case it contains sensitive Mount options
744 return nil, fmt.Errorf("wrong number of fields (expected %d, got %d)", expectedNumFieldsPerLine, len(fields))
745 }
746
747 mp := MountPoint{
748 Device: fields[0],
749 Path: fields[1],
750 Type: fields[2],
751 Opts: strings.Split(fields[3], ","),
752 }
753
754 freq, err := strconv.Atoi(fields[4])
755 if err != nil {
756 return nil, err
757 }
758 mp.Freq = freq
759
760 pass, err := strconv.Atoi(fields[5])
761 if err != nil {
762 return nil, err
763 }
764 mp.Pass = pass
765
766 out = append(out, mp)
767 }
768 return out, nil
769 }
770
771 // SearchMountPoints finds all mount references to the source, returns a list of
772 // mountpoints.
773 // The source can be a mount point or a normal directory (bind mount). We
774 // didn't support device because there is no use case by now.
775 // Some filesystems may share a source name, e.g. tmpfs. And for bind mounting,
776 // it's possible to mount a non-root path of a filesystem, so we need to use
777 // root path and major:minor to represent mount source uniquely.
778 func SearchMountPoints(hostSource, mountInfoPath string) ([]string, error) {
779 mis, err := ParseMountInfo(mountInfoPath)
780 if err != nil {
781 return nil, err
782 }
783
784 mountID := 0
785 rootPath := ""
786 major := -1
787 minor := -1
788
789 // Finding the underlying root path and major:minor if possible.
790 // We need search in backward order because it's possible for later mounts
791 // to overlap earlier mounts.
792 for i := len(mis) - 1; i >= 0; i-- {
793 if hostSource == mis[i].MountPoint || PathWithinBase(hostSource, mis[i].MountPoint) {
794 // If it's a mount point or path under a mount point.
795 mountID = mis[i].ID
796 rootPath = filepath.Join(mis[i].Root, strings.TrimPrefix(hostSource, mis[i].MountPoint))
797 major = mis[i].Major
798 minor = mis[i].Minor
799 break
800 }
801 }
802
803 if rootPath == "" || major == -1 || minor == -1 {
804 return nil, fmt.Errorf("failed to get root path and major:minor for %s", hostSource)
805 }
806
807 var refs []string
808 for i := range mis {
809 if mis[i].ID == mountID {
810 // Ignore mount entry for mount source itself.
811 continue
812 }
813 if mis[i].Root == rootPath && mis[i].Major == major && mis[i].Minor == minor {
814 refs = append(refs, mis[i].MountPoint)
815 }
816 }
817
818 return refs, nil
819 }
820
821 // IsMountPoint determines if a file is a mountpoint.
822 // It first detects bind & any other mountpoints using
823 // MountedFast function. If the MountedFast function returns
824 // sure as true and err as nil, then a mountpoint is detected
825 // successfully. When an error is returned by MountedFast, the
826 // following is true:
827 // 1. All errors are returned with IsMountPoint as false
828 // except os.IsPermission.
829 // 2. When os.IsPermission is returned by MountedFast, List()
830 // is called to confirm if the given file is a mountpoint are not.
831 //
832 // os.ErrNotExist should always be returned if a file does not exist
833 // as callers have in past relied on this error and not fallback.
834 //
835 // When MountedFast returns sure as false and err as nil (eg: in
836 // case of bindmounts on kernel version 5.10- ); mounter.List()
837 // endpoint is called to enumerate all the mountpoints and check if
838 // it is mountpoint match or not.
839 func (mounter *Mounter) IsMountPoint(file string) (bool, error) {
840 isMnt, sure, isMntErr := mountinfo.MountedFast(file)
841 if sure && isMntErr == nil {
842 return isMnt, nil
843 }
844 if isMntErr != nil {
845 if errors.Is(isMntErr, fs.ErrNotExist) {
846 return false, fs.ErrNotExist
847 }
848 // We were not allowed to do the simple stat() check, e.g. on NFS with
849 // root_squash. Fall back to /proc/mounts check below when
850 // fs.ErrPermission is returned.
851 if !errors.Is(isMntErr, fs.ErrPermission) {
852 return false, isMntErr
853 }
854 }
855 // Resolve any symlinks in file, kernel would do the same and use the resolved path in /proc/mounts.
856 resolvedFile, err := filepath.EvalSymlinks(file)
857 if err != nil {
858 if errors.Is(err, fs.ErrNotExist) {
859 return false, fs.ErrNotExist
860 }
861 return false, err
862 }
863
864 // check all mountpoints since MountedFast is not sure.
865 // is not reliable for some mountpoint types.
866 mountPoints, mountPointsErr := mounter.List()
867 if mountPointsErr != nil {
868 return false, mountPointsErr
869 }
870 for _, mp := range mountPoints {
871 if isMountPointMatch(mp, resolvedFile) {
872 return true, nil
873 }
874 }
875 return false, nil
876 }
877
878 // tryUnmount calls plain "umount" and waits for unmountTimeout for it to finish.
879 func tryUnmount(target string, withSafeNotMountedBehavior bool, unmountTimeout time.Duration) error {
880 klog.V(4).Infof("Unmounting %s", target)
881 ctx, cancel := context.WithTimeout(context.Background(), unmountTimeout)
882 defer cancel()
883
884 command := exec.CommandContext(ctx, "umount", target)
885 output, err := command.CombinedOutput()
886
887 // CombinedOutput() does not return DeadlineExceeded, make sure it's
888 // propagated on timeout.
889 if ctx.Err() != nil {
890 return ctx.Err()
891 }
892
893 if err != nil {
894 return checkUmountError(target, command, output, err, withSafeNotMountedBehavior)
895 }
896 return nil
897 }
898
899 func forceUmount(target string, withSafeNotMountedBehavior bool) error {
900 command := exec.Command("umount", "-f", target)
901 output, err := command.CombinedOutput()
902 if err != nil {
903 return checkUmountError(target, command, output, err, withSafeNotMountedBehavior)
904 }
905 return nil
906 }
907
908 // checkUmountError checks a result of umount command and determine a return value.
909 func checkUmountError(target string, command *exec.Cmd, output []byte, err error, withSafeNotMountedBehavior bool) error {
910 if err.Error() == errNoChildProcesses {
911 if command.ProcessState.Success() {
912 // We don't consider errNoChildProcesses an error if the process itself succeeded (see - k/k issue #103753).
913 return nil
914 }
915 // Rewrite err with the actual exit error of the process.
916 err = &exec.ExitError{ProcessState: command.ProcessState}
917 }
918 if withSafeNotMountedBehavior && strings.Contains(string(output), errNotMounted) {
919 klog.V(4).Infof("ignoring 'not mounted' error for %s", target)
920 return nil
921 }
922 return fmt.Errorf("unmount failed: %v\nUnmounting arguments: %s\nOutput: %s", err, target, string(output))
923 }