Debian Codegraph @

mount/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 "fmt"
23 "os"
24 "os/exec"
25 "path/filepath"
26 "slices"
27 "strconv"
28 "strings"
29 "syscall"
30
31 "k8s.io/klog/v2"
32
33 utilexec "k8s.io/utils/exec"
34 utilio "k8s.io/utils/io"
35 )
36
37 const (
38 // Number of fields per line in /proc/mounts as per the fstab man page.
39 expectedNumFieldsPerLine = 6
40 // Location of the mount file to use
41 procMountsPath = "/proc/mounts"
42 // Location of the mountinfo file
43 procMountInfoPath = "/proc/self/mountinfo"
44 // 'fsck' found errors and corrected them
45 fsckErrorsCorrected = 1
46 // 'fsck' found errors but exited without correcting them
47 fsckErrorsUncorrected = 4
48 )
49
50 // Mounter provides the default implementation of mount.Interface
51 // for the linux platform. This implementation assumes that the
52 // kubelet is running in the host's root mount namespace.
53 type Mounter struct {
54 mounterPath string
55 withSystemd bool
56 }
57
58 // New returns a mount.Interface for the current system.
59 // It provides options to override the default mounter behavior.
60 // mounterPath allows using an alternative to `/bin/mount` for mounting.
61 func New(mounterPath string) Interface {
62 return &Mounter{
63 mounterPath: mounterPath,
64 withSystemd: detectSystemd(),
65 }
66 }
67
68 // Mount mounts source to target as fstype with given options. 'source' and 'fstype' must
69 // be an empty string in case it's not required, e.g. for remount, or for auto filesystem
70 // type, where kernel handles fstype for you. The mount 'options' is a list of options,
71 // currently come from mount(8), e.g. "ro", "remount", "bind", etc. If no more option is
72 // required, call Mount with an empty string list or nil.
73 func (mounter *Mounter) Mount(source string, target string, fstype string, options []string) error {
74 return mounter.MountSensitive(source, target, fstype, options, nil)
75 }
76
77 // MountSensitive is the same as Mount() but this method allows
78 // sensitiveOptions to be passed in a separate parameter from the normal
79 // mount options and ensures the sensitiveOptions are never logged. This
80 // method should be used by callers that pass sensitive material (like
81 // passwords) as mount options.
82 func (mounter *Mounter) MountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error {
83 // Path to mounter binary if containerized mounter is needed. Otherwise, it is set to empty.
84 // All Linux distros are expected to be shipped with a mount utility that a support bind mounts.
85 mounterPath := ""
86 bind, bindOpts, bindRemountOpts, bindRemountOptsSensitive := MakeBindOptsSensitive(options, sensitiveOptions)
87 if bind {
88 err := mounter.doMount(mounterPath, defaultMountCommand, source, target, fstype, bindOpts, bindRemountOptsSensitive)
89 if err != nil {
90 return err
91 }
92 return mounter.doMount(mounterPath, defaultMountCommand, source, target, fstype, bindRemountOpts, bindRemountOptsSensitive)
93 }
94 // The list of filesystems that require containerized mounter on GCI image cluster
95 fsTypesNeedMounter := map[string]struct{}{
96 "nfs": {},
97 "glusterfs": {},
98 "ceph": {},
99 "cifs": {},
100 }
101 if _, ok := fsTypesNeedMounter[fstype]; ok {
102 mounterPath = mounter.mounterPath
103 }
104 return mounter.doMount(mounterPath, defaultMountCommand, source, target, fstype, options, sensitiveOptions)
105 }
106
107 // doMount runs the mount command. mounterPath is the path to mounter binary if containerized mounter is used.
108 // sensitiveOptions is an extension of options except they will not be logged (because they may contain sensitive material)
109 func (mounter *Mounter) doMount(mounterPath string, mountCmd string, source string, target string, fstype string, options []string, sensitiveOptions []string) error {
110 mountArgs, mountArgsLogStr := MakeMountArgsSensitive(source, target, fstype, options, sensitiveOptions)
111 if len(mounterPath) > 0 {
112 mountArgs = append([]string{mountCmd}, mountArgs...)
113 mountArgsLogStr = mountCmd + " " + mountArgsLogStr
114 mountCmd = mounterPath
115 }
116
117 // If systemd-run is available, run mount in a transient scope.
118 // Otherwise, assume kubelet is not running as a systemd service and
119 // use the pre-populated mount command and arguments.
120 if mounter.withSystemd {
121 // Try to run mount via systemd-run --scope. This will escape the
122 // service where kubelet runs and any fuse daemons will be started in a
123 // specific scope. kubelet service than can be restarted without killing
124 // these fuse daemons.
125 //
126 // Complete command line (when mounterPath is not used):
127 // systemd-run --description=... --scope -- mount -t <type> <what> <where>
128 //
129 // Expected flow:
130 // * systemd-run creates a transient scope (=~ cgroup) and executes its
131 // argument (/bin/mount) there.
132 // * mount does its job, forks a fuse daemon if necessary and finishes.
133 // (systemd-run --scope finishes at this point, returning mount's exit
134 // code and stdout/stderr - thats one of --scope benefits).
135 // * systemd keeps the fuse daemon running in the scope (i.e. in its own
136 // cgroup) until the fuse daemon dies (another --scope benefit).
137 // Kubelet service can be restarted and the fuse daemon survives.
138 // * When the fuse daemon dies (e.g. during unmount) systemd removes the
139 // scope automatically.
140 //
141 // systemd-mount is not used because it's too new for older distros
142 // (CentOS 7, Debian Jessie).
143 mountCmd, mountArgs, mountArgsLogStr = AddSystemdScopeSensitive("systemd-run", target, mountCmd, mountArgs, mountArgsLogStr)
144 }
145
146 // Logging with sensitive mount options removed.
147 klog.V(4).Infof("Mounting cmd (%s) with arguments (%s)", mountCmd, mountArgsLogStr)
148 command := exec.Command(mountCmd, mountArgs...)
149 output, err := command.CombinedOutput()
150 if err != nil {
151 klog.Errorf("Mount failed: %v\nMounting command: %s\nMounting arguments: %s\nOutput: %s\n", err, mountCmd, mountArgsLogStr, string(output))
152 return fmt.Errorf("mount failed: %v\nMounting command: %s\nMounting arguments: %s\nOutput: %s",
153 err, mountCmd, mountArgsLogStr, string(output))
154 }
155 return err
156 }
157
158 // detectSystemd returns true if OS runs with systemd as init. When not sure
159 // (permission errors, ...), it returns false.
160 // There may be different ways how to detect systemd, this one makes sure that
161 // systemd-runs (needed by Mount()) works.
162 func detectSystemd() bool {
163 if _, err := exec.LookPath("systemd-run"); err != nil {
164 klog.V(2).Infof("Detected OS without systemd")
165 return false
166 }
167 // Try to run systemd-run --scope /bin/true, that should be enough
168 // to make sure that systemd is really running and not just installed,
169 // which happens when running in a container with a systemd-based image
170 // but with different pid 1.
171 cmd := exec.Command("systemd-run", "--description=Kubernetes systemd probe", "--scope", "true")
172 output, err := cmd.CombinedOutput()
173 if err != nil {
174 klog.V(2).Infof("Cannot run systemd-run, assuming non-systemd OS")
175 klog.V(4).Infof("systemd-run failed with: %v", err)
176 klog.V(4).Infof("systemd-run output: %s", string(output))
177 return false
178 }
179 klog.V(2).Infof("Detected OS with systemd")
180 return true
181 }
182
183 // MakeMountArgs makes the arguments to the mount(8) command.
184 // options MUST not contain sensitive material (like passwords).
185 func MakeMountArgs(source, target, fstype string, options []string) (mountArgs []string) {
186 mountArgs, _ = MakeMountArgsSensitive(source, target, fstype, options, nil /* sensitiveOptions */)
187 return mountArgs
188 }
189
190 // MakeMountArgsSensitive makes the arguments to the mount(8) command.
191 // sensitiveOptions is an extension of options except they will not be logged (because they may contain sensitive material)
192 func MakeMountArgsSensitive(source, target, fstype string, options []string, sensitiveOptions []string) (mountArgs []string, mountArgsLogStr string) {
193 // Build mount command as follows:
194 // mount [-t $fstype] [-o $options] [$source] $target
195 mountArgs = []string{}
196 mountArgsLogStr = ""
197 if len(fstype) > 0 {
198 mountArgs = append(mountArgs, "-t", fstype)
199 mountArgsLogStr += strings.Join(mountArgs, " ")
200 }
201 if len(options) > 0 || len(sensitiveOptions) > 0 {
202 combinedOptions := []string{}
203 combinedOptions = append(combinedOptions, options...)
204 combinedOptions = append(combinedOptions, sensitiveOptions...)
205 mountArgs = append(mountArgs, "-o", strings.Join(combinedOptions, ","))
206 // exclude sensitiveOptions from log string
207 mountArgsLogStr += " -o " + sanitizedOptionsForLogging(options, sensitiveOptions)
208 }
209 if len(source) > 0 {
210 mountArgs = append(mountArgs, source)
211 mountArgsLogStr += " " + source
212 }
213 mountArgs = append(mountArgs, target)
214 mountArgsLogStr += " " + target
215
216 return mountArgs, mountArgsLogStr
217 }
218
219 // AddSystemdScope adds "system-run --scope" to given command line
220 // If args contains sensitive material, use AddSystemdScopeSensitive to construct
221 // a safe to log string.
222 func AddSystemdScope(systemdRunPath, mountName, command string, args []string) (string, []string) {
223 descriptionArg := fmt.Sprintf("--description=Kubernetes transient mount for %s", mountName)
224 systemdRunArgs := []string{descriptionArg, "--scope", "--", command}
225 return systemdRunPath, append(systemdRunArgs, args...)
226 }
227
228 // AddSystemdScopeSensitive adds "system-run --scope" to given command line
229 // It also accepts takes a sanitized string containing mount arguments, mountArgsLogStr,
230 // and returns the string appended to the systemd command for logging.
231 func AddSystemdScopeSensitive(systemdRunPath, mountName, command string, args []string, mountArgsLogStr string) (string, []string, string) {
232 descriptionArg := fmt.Sprintf("--description=Kubernetes transient mount for %s", mountName)
233 systemdRunArgs := []string{descriptionArg, "--scope", "--", command}
234 return systemdRunPath, append(systemdRunArgs, args...), strings.Join(systemdRunArgs, " ") + " " + mountArgsLogStr
235 }
236
237 // Unmount unmounts the target.
238 func (mounter *Mounter) Unmount(target string) error {
239 klog.V(4).Infof("Unmounting %s", target)
240 command := exec.Command("umount", target)
241 output, err := command.CombinedOutput()
242 if err != nil {
243 return fmt.Errorf("unmount failed: %v\nUnmounting arguments: %s\nOutput: %s", err, target, string(output))
244 }
245 return nil
246 }
247
248 // List returns a list of all mounted filesystems.
249 func (*Mounter) List() ([]MountPoint, error) {
250 return ListProcMounts(procMountsPath)
251 }
252
253 // IsLikelyNotMountPoint determines if a directory is not a mountpoint.
254 // It is fast but not necessarily ALWAYS correct. If the path is in fact
255 // a bind mount from one part of a mount to another it will not be detected.
256 // It also can not distinguish between mountpoints and symbolic links.
257 // mkdir /tmp/a /tmp/b; mount --bind /tmp/a /tmp/b; IsLikelyNotMountPoint("/tmp/b")
258 // will return true. When in fact /tmp/b is a mount point. If this situation
259 // is of interest to you, don't use this function...
260 func (mounter *Mounter) IsLikelyNotMountPoint(file string) (bool, error) {
261 stat, err := os.Stat(file)
262 if err != nil {
263 return true, err
264 }
265 rootStat, err := os.Stat(filepath.Dir(strings.TrimSuffix(file, "/")))
266 if err != nil {
267 return true, err
268 }
269 // If the directory has a different device as parent, then it is a mountpoint.
270 if stat.Sys().(*syscall.Stat_t).Dev != rootStat.Sys().(*syscall.Stat_t).Dev {
271 return false, nil
272 }
273
274 return true, nil
275 }
276
277 // GetMountRefs finds all mount references to pathname, returns a
278 // list of paths. Path could be a mountpoint or a normal
279 // directory (for bind mount).
280 func (mounter *Mounter) GetMountRefs(pathname string) ([]string, error) {
281 pathExists, pathErr := PathExists(pathname)
282 if !pathExists {
283 return []string{}, nil
284 } else if IsCorruptedMnt(pathErr) {
285 klog.Warningf("GetMountRefs found corrupted mount at %s, treating as unmounted path", pathname)
286 return []string{}, nil
287 } else if pathErr != nil {
288 return nil, fmt.Errorf("error checking path %s: %v", pathname, pathErr)
289 }
290 realpath, err := filepath.EvalSymlinks(pathname)
291 if err != nil {
292 return nil, err
293 }
294 return SearchMountPoints(realpath, procMountInfoPath)
295 }
296
297 // checkAndRepairFileSystem checks and repairs filesystems using command fsck.
298 func (mounter *SafeFormatAndMount) checkAndRepairFilesystem(source string) error {
299 klog.V(4).Infof("Checking for issues with fsck on disk: %s", source)
300 args := []string{"-a", source}
301 out, err := mounter.Exec.Command("fsck", args...).CombinedOutput()
302 if err != nil {
303 ee, isExitError := err.(utilexec.ExitError)
304 switch {
305 case err == utilexec.ErrExecutableNotFound:
306 klog.Warningf("'fsck' not found on system; continuing mount without running 'fsck'.")
307 case isExitError && ee.ExitStatus() == fsckErrorsCorrected:
308 klog.Infof("Device %s has errors which were corrected by fsck.", source)
309 case isExitError && ee.ExitStatus() == fsckErrorsUncorrected:
310 return NewMountError(HasFilesystemErrors, "'fsck' found errors on device %s but could not correct them: %s", source, string(out))
311 case isExitError && ee.ExitStatus() > fsckErrorsUncorrected:
312 klog.Infof("`fsck` error %s", string(out))
313 }
314 }
315 return nil
316 }
317
318 // formatAndMount uses unix utils to format and mount the given disk
319 func (mounter *SafeFormatAndMount) formatAndMountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error {
320 readOnly := slices.Contains(options, "ro") || slices.Contains(sensitiveOptions, "ro")
321
322 options = append(options, "defaults")
323 mountErrorValue := UnknownMountError
324
325 // Check if the disk is already formatted
326 existingFormat, err := mounter.GetDiskFormat(source)
327 if err != nil {
328 return NewMountError(GetDiskFormatFailed, "failed to get disk format of disk %s: %v", source, err)
329 }
330
331 // Use 'ext4' as the default
332 if len(fstype) == 0 {
333 fstype = "ext4"
334 }
335
336 if existingFormat == "" {
337 // Do not attempt to format the disk if mounting as readonly, return an error to reflect this.
338 if readOnly {
339 return NewMountError(UnformattedReadOnly, "cannot mount unformatted disk %s as we are manipulating it in read-only mode", source)
340 }
341
342 // Disk is unformatted so format it.
343 args := []string{source}
344 if fstype == "ext4" || fstype == "ext3" {
345 args = []string{
346 "-F", // Force flag
347 "-m0", // Zero blocks reserved for super-user
348 source,
349 }
350 }
351
352 klog.Infof("Disk %q appears to be unformatted, attempting to format as type: %q with options: %v", source, fstype, args)
353 output, err := mounter.Exec.Command("mkfs."+fstype, args...).CombinedOutput()
354 if err != nil {
355 // Do not log sensitiveOptions only options
356 sensitiveOptionsLog := sanitizedOptionsForLogging(options, sensitiveOptions)
357 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))
358 klog.Error(detailedErr)
359 return NewMountError(FormatFailed, "%s", detailedErr)
360 }
361
362 klog.Infof("Disk successfully formatted (mkfs): %s - %s %s", fstype, source, target)
363 } else {
364 if fstype != existingFormat {
365 // Verify that the disk is formatted with filesystem type we are expecting
366 mountErrorValue = FilesystemMismatch
367 klog.Warningf("Configured to mount disk %s as %s but current format is %s, things might break", source, existingFormat, fstype)
368 }
369
370 if !readOnly {
371 // Run check tools on the disk to fix repairable issues, only do this for formatted volumes requested as rw.
372 err := mounter.checkAndRepairFilesystem(source)
373 if err != nil {
374 return err
375 }
376 }
377 }
378
379 // Mount the disk
380 klog.V(4).Infof("Attempting to mount disk %s in %s format at %s", source, fstype, target)
381 if err := mounter.MountSensitive(source, target, fstype, options, sensitiveOptions); err != nil {
382 return NewMountError(mountErrorValue, "%s", err.Error())
383 }
384
385 return nil
386 }
387
388 // GetDiskFormat uses 'blkid' to see if the given disk is unformatted
389 func (mounter *SafeFormatAndMount) GetDiskFormat(disk string) (string, error) {
390 args := []string{"-p", "-s", "TYPE", "-s", "PTTYPE", "-o", "export", disk}
391 klog.V(4).Infof("Attempting to determine if disk %q is formatted using blkid with args: (%v)", disk, args)
392 dataOut, err := mounter.Exec.Command("blkid", args...).CombinedOutput()
393 output := string(dataOut)
394 klog.V(4).Infof("Output: %q, err: %v", output, err)
395
396 if err != nil {
397 if exit, ok := err.(utilexec.ExitError); ok {
398 if exit.ExitStatus() == 2 {
399 // Disk device is unformatted.
400 // For `blkid`, if the specified token (TYPE/PTTYPE, etc) was
401 // not found, or no (specified) devices could be identified, an
402 // exit code of 2 is returned.
403 return "", nil
404 }
405 }
406 klog.Errorf("Could not determine if disk %q is formatted (%v)", disk, err)
407 return "", err
408 }
409
410 var fstype, pttype string
411
412 for l := range strings.SplitSeq(output, "\n") {
413 if len(l) <= 0 {
414 // Ignore empty line.
415 continue
416 }
417 cs := strings.Split(l, "=")
418 if len(cs) != 2 {
419 return "", fmt.Errorf("blkid returns invalid output: %s", output)
420 }
421 // TYPE is filesystem type, and PTTYPE is partition table type, according
422 // to https://www.kernel.org/pub/linux/utils/util-linux/v2.21/libblkid-docs/.
423 if cs[0] == "TYPE" {
424 fstype = cs[1]
425 } else if cs[0] == "PTTYPE" {
426 pttype = cs[1]
427 }
428 }
429
430 if len(pttype) > 0 {
431 klog.V(4).Infof("Disk %s detected partition table type: %s", disk, pttype)
432 // Returns a special non-empty string as filesystem type, then kubelet
433 // will not format it.
434 return "unknown data, probably partitions", nil
435 }
436
437 return fstype, nil
438 }
439
440 // ListProcMounts is shared with NsEnterMounter
441 func ListProcMounts(mountFilePath string) ([]MountPoint, error) {
442 content, err := utilio.ConsistentRead(mountFilePath, maxListTries)
443 if err != nil {
444 return nil, err
445 }
446 return parseProcMounts(content)
447 }
448
449 func parseProcMounts(content []byte) ([]MountPoint, error) {
450 out := []MountPoint{}
451 for line := range strings.SplitSeq(string(content), "\n") {
452 if line == "" {
453 // the last split() item is empty string following the last \n
454 continue
455 }
456 fields := strings.Fields(line)
457 if len(fields) != expectedNumFieldsPerLine {
458 // Do not log line in case it contains sensitive Mount options
459 return nil, fmt.Errorf("wrong number of fields (expected %d, got %d)", expectedNumFieldsPerLine, len(fields))
460 }
461
462 mp := MountPoint{
463 Device: fields[0],
464 Path: fields[1],
465 Type: fields[2],
466 Opts: strings.Split(fields[3], ","),
467 }
468
469 freq, err := strconv.Atoi(fields[4])
470 if err != nil {
471 return nil, err
472 }
473 mp.Freq = freq
474
475 pass, err := strconv.Atoi(fields[5])
476 if err != nil {
477 return nil, err
478 }
479 mp.Pass = pass
480
481 out = append(out, mp)
482 }
483 return out, nil
484 }
485
486 // SearchMountPoints finds all mount references to the source, returns a list of
487 // mountpoints.
488 // The source can be a mount point or a normal directory (bind mount). We
489 // didn't support device because there is no use case by now.
490 // Some filesystems may share a source name, e.g. tmpfs. And for bind mounting,
491 // it's possible to mount a non-root path of a filesystem, so we need to use
492 // root path and major:minor to represent mount source uniquely.
493 // This implementation is shared between Linux and NsEnterMounter
494 func SearchMountPoints(hostSource, mountInfoPath string) ([]string, error) {
495 mis, err := ParseMountInfo(mountInfoPath)
496 if err != nil {
497 return nil, err
498 }
499
500 mountID := 0
501 rootPath := ""
502 major := -1
503 minor := -1
504
505 // Finding the underlying root path and major:minor if possible.
506 // We need search in backward order because it's possible for later mounts
507 // to overlap earlier mounts.
508 for i := len(mis) - 1; i >= 0; i-- {
509 if hostSource == mis[i].MountPoint || PathWithinBase(hostSource, mis[i].MountPoint) {
510 // If it's a mount point or path under a mount point.
511 mountID = mis[i].ID
512 rootPath = filepath.Join(mis[i].Root, strings.TrimPrefix(hostSource, mis[i].MountPoint))
513 major = mis[i].Major
514 minor = mis[i].Minor
515 break
516 }
517 }
518
519 if rootPath == "" || major == -1 || minor == -1 {
520 return nil, fmt.Errorf("failed to get root path and major:minor for %s", hostSource)
521 }
522
523 var refs []string
524 for i := range mis {
525 if mis[i].ID == mountID {
526 // Ignore mount entry for mount source itself.
527 continue
528 }
529 if mis[i].Root == rootPath && mis[i].Major == major && mis[i].Minor == minor {
530 refs = append(refs, mis[i].MountPoint)
531 }
532 }
533
534 return refs, nil
535 }