| 1 |
//go:build !windows |
| 2 |
|
| 3 |
/* |
| 4 |
Copyright 2019 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 |
"bytes" |
| 23 |
"errors" |
| 24 |
"fmt" |
| 25 |
"io/fs" |
| 26 |
"os" |
| 27 |
"strconv" |
| 28 |
"strings" |
| 29 |
"sync" |
| 30 |
"syscall" |
| 31 |
|
| 32 |
"golang.org/x/sys/unix" |
| 33 |
"k8s.io/klog/v2" |
| 34 |
utilio "k8s.io/utils/io" |
| 35 |
) |
| 36 |
|
| 37 |
const ( |
| 38 |
// At least number of fields per line in /proc/<pid>/mountinfo. |
| 39 |
expectedAtLeastNumFieldsPerMountInfo = 10 |
| 40 |
// How many times to retry for a consistent read of /proc/mounts. |
| 41 |
maxListTries = 10 |
| 42 |
) |
| 43 |
|
| 44 |
// IsCorruptedMnt return true if err is about corrupted mount point |
| 45 |
func IsCorruptedMnt(err error) bool { |
| 46 |
if err == nil { |
| 47 |
return false |
| 48 |
} |
| 49 |
var underlyingError error |
| 50 |
switch pe := err.(type) { |
| 51 |
case nil: |
| 52 |
return false |
| 53 |
case *os.PathError: |
| 54 |
underlyingError = pe.Err |
| 55 |
case *os.LinkError: |
| 56 |
underlyingError = pe.Err |
| 57 |
case *os.SyscallError: |
| 58 |
underlyingError = pe.Err |
| 59 |
case syscall.Errno: |
| 60 |
underlyingError = err |
| 61 |
} |
| 62 |
|
| 63 |
return errors.Is(underlyingError, syscall.ENOTCONN) || |
| 64 |
errors.Is(underlyingError, syscall.ESTALE) || |
| 65 |
errors.Is(underlyingError, syscall.EIO) || |
| 66 |
errors.Is(underlyingError, syscall.EACCES) || |
| 67 |
errors.Is(underlyingError, syscall.EHOSTDOWN) || |
| 68 |
errors.Is(underlyingError, syscall.EWOULDBLOCK) || |
| 69 |
errors.Is(underlyingError, syscall.ENODEV) |
| 70 |
} |
| 71 |
|
| 72 |
// MountInfo represents a single line in /proc/<pid>/mountinfo. |
| 73 |
type MountInfo struct { |
| 74 |
// Unique ID for the mount (maybe reused after umount). |
| 75 |
ID int |
| 76 |
// The ID of the parent mount (or of self for the root of this mount namespace's mount tree). |
| 77 |
ParentID int |
| 78 |
// Major indicates one half of the device ID which identifies the device class |
| 79 |
// (parsed from `st_dev` for files on this filesystem). |
| 80 |
Major int |
| 81 |
// Minor indicates one half of the device ID which identifies a specific |
| 82 |
// instance of device (parsed from `st_dev` for files on this filesystem). |
| 83 |
Minor int |
| 84 |
// The pathname of the directory in the filesystem which forms the root of this mount. |
| 85 |
Root string |
| 86 |
// Mount source, filesystem-specific information. e.g. device, tmpfs name. |
| 87 |
Source string |
| 88 |
// Mount point, the pathname of the mount point. |
| 89 |
MountPoint string |
| 90 |
// Optional fieds, zero or more fields of the form "tag[:value]". |
| 91 |
OptionalFields []string |
| 92 |
// The filesystem type in the form "type[.subtype]". |
| 93 |
FsType string |
| 94 |
// Per-mount options. |
| 95 |
MountOptions []string |
| 96 |
// Per-superblock options. |
| 97 |
SuperOptions []string |
| 98 |
} |
| 99 |
|
| 100 |
// ParseMountInfo parses /proc/xxx/mountinfo. |
| 101 |
func ParseMountInfo(filename string) ([]MountInfo, error) { |
| 102 |
content, err := readMountInfo(filename) |
| 103 |
if err != nil { |
| 104 |
return []MountInfo{}, err |
| 105 |
} |
| 106 |
contentStr := string(content) |
| 107 |
infos := []MountInfo{} |
| 108 |
|
| 109 |
for _, line := range strings.Split(contentStr, "\n") { |
| 110 |
if line == "" { |
| 111 |
// the last split() item is empty string following the last \n |
| 112 |
continue |
| 113 |
} |
| 114 |
// See `man proc` for authoritative description of format of the file. |
| 115 |
fields := strings.Fields(line) |
| 116 |
if len(fields) < expectedAtLeastNumFieldsPerMountInfo { |
| 117 |
return nil, fmt.Errorf("wrong number of fields in (expected at least %d, got %d): %s", expectedAtLeastNumFieldsPerMountInfo, len(fields), line) |
| 118 |
} |
| 119 |
id, err := strconv.Atoi(fields[0]) |
| 120 |
if err != nil { |
| 121 |
return nil, err |
| 122 |
} |
| 123 |
parentID, err := strconv.Atoi(fields[1]) |
| 124 |
if err != nil { |
| 125 |
return nil, err |
| 126 |
} |
| 127 |
mm := strings.Split(fields[2], ":") |
| 128 |
if len(mm) != 2 { |
| 129 |
return nil, fmt.Errorf("parsing '%s' failed: unexpected minor:major pair %s", line, mm) |
| 130 |
} |
| 131 |
major, err := strconv.Atoi(mm[0]) |
| 132 |
if err != nil { |
| 133 |
return nil, fmt.Errorf("parsing '%s' failed: unable to parse major device id, err:%v", mm[0], err) |
| 134 |
} |
| 135 |
minor, err := strconv.Atoi(mm[1]) |
| 136 |
if err != nil { |
| 137 |
return nil, fmt.Errorf("parsing '%s' failed: unable to parse minor device id, err:%v", mm[1], err) |
| 138 |
} |
| 139 |
|
| 140 |
info := MountInfo{ |
| 141 |
ID: id, |
| 142 |
ParentID: parentID, |
| 143 |
Major: major, |
| 144 |
Minor: minor, |
| 145 |
Root: fields[3], |
| 146 |
MountPoint: fields[4], |
| 147 |
MountOptions: splitMountOptions(fields[5]), |
| 148 |
} |
| 149 |
// All fields until "-" are "optional fields". |
| 150 |
i := 6 |
| 151 |
for ; i < len(fields) && fields[i] != "-"; i++ { |
| 152 |
info.OptionalFields = append(info.OptionalFields, fields[i]) |
| 153 |
} |
| 154 |
// Parse the rest 3 fields. |
| 155 |
i++ |
| 156 |
if len(fields)-i < 3 { |
| 157 |
return nil, fmt.Errorf("expect 3 fields in %s, got %d", line, len(fields)-i) |
| 158 |
} |
| 159 |
info.FsType = fields[i] |
| 160 |
info.Source = fields[i+1] |
| 161 |
info.SuperOptions = splitMountOptions(fields[i+2]) |
| 162 |
infos = append(infos, info) |
| 163 |
} |
| 164 |
return infos, nil |
| 165 |
} |
| 166 |
|
| 167 |
// splitMountOptions parses comma-separated list of mount options into an array. |
| 168 |
// It respects double quotes - commas in them are not considered as the option separator. |
| 169 |
func splitMountOptions(s string) []string { |
| 170 |
inQuotes := false |
| 171 |
list := strings.FieldsFunc(s, func(r rune) bool { |
| 172 |
if r == '"' { |
| 173 |
inQuotes = !inQuotes |
| 174 |
} |
| 175 |
// Report a new field only when outside of double quotes. |
| 176 |
return r == ',' && !inQuotes |
| 177 |
}) |
| 178 |
return list |
| 179 |
} |
| 180 |
|
| 181 |
// isMountPointMatch returns true if the path in mp is the same as dir. |
| 182 |
// Handles case where mountpoint dir has been renamed due to stale NFS mount. |
| 183 |
func isMountPointMatch(mp MountPoint, dir string) bool { |
| 184 |
return strings.TrimSuffix(mp.Path, "\\040(deleted)") == dir |
| 185 |
} |
| 186 |
|
| 187 |
// PathExists returns true if the specified path exists. |
| 188 |
// TODO: clean this up to use pkg/util/file/FileExists |
| 189 |
func PathExists(path string) (bool, error) { |
| 190 |
_, err := os.Stat(path) |
| 191 |
if err == nil { |
| 192 |
return true, nil |
| 193 |
} else if errors.Is(err, fs.ErrNotExist) { |
| 194 |
err = syscall.Access(path, syscall.F_OK) |
| 195 |
if err == nil { |
| 196 |
// The access syscall says the file exists, the stat syscall says it |
| 197 |
// doesn't. This was observed on CIFS when the path was removed at |
| 198 |
// the server somehow. POSIX calls this a stale file handle, let's fake |
| 199 |
// that error and treat the path as existing but corrupted. |
| 200 |
klog.Warningf("Potential stale file handle detected: %s", path) |
| 201 |
return true, syscall.ESTALE |
| 202 |
} |
| 203 |
return false, nil |
| 204 |
} else if IsCorruptedMnt(err) { |
| 205 |
return true, err |
| 206 |
} |
| 207 |
return false, err |
| 208 |
} |
| 209 |
|
| 210 |
// These variables are used solely by kernelHasMountinfoBug. |
| 211 |
var ( |
| 212 |
hasMountinfoBug bool |
| 213 |
checkMountinfoBugOnce sync.Once |
| 214 |
) |
| 215 |
|
| 216 |
// kernelHasMountinfoBug checks if the kernel bug that can lead to incomplete |
| 217 |
// mountinfo being read is fixed. It does so by checking the kernel version. |
| 218 |
// |
| 219 |
// The bug was fixed by the kernel commit 9f6c61f96f2d97 (since Linux 5.8). |
| 220 |
// Alas, there is no better way to check if the bug is fixed other than to |
| 221 |
// rely on the kernel version returned by uname. |
| 222 |
func kernelHasMountinfoBug() bool { |
| 223 |
checkMountinfoBugOnce.Do(func() { |
| 224 |
// Assume old kernel. |
| 225 |
hasMountinfoBug = true |
| 226 |
|
| 227 |
uname := unix.Utsname{} |
| 228 |
err := unix.Uname(&uname) |
| 229 |
if err != nil { |
| 230 |
return |
| 231 |
} |
| 232 |
|
| 233 |
end := bytes.IndexByte(uname.Release[:], 0) |
| 234 |
v := bytes.SplitN(uname.Release[:end], []byte{'.'}, 3) |
| 235 |
if len(v) != 3 { |
| 236 |
return |
| 237 |
} |
| 238 |
major, _ := strconv.Atoi(string(v[0])) |
| 239 |
minor, _ := strconv.Atoi(string(v[1])) |
| 240 |
|
| 241 |
if major > 5 || (major == 5 && minor >= 8) { |
| 242 |
hasMountinfoBug = false |
| 243 |
} |
| 244 |
}) |
| 245 |
|
| 246 |
return hasMountinfoBug |
| 247 |
} |
| 248 |
|
| 249 |
func readMountInfo(path string) ([]byte, error) { |
| 250 |
if kernelHasMountinfoBug() { |
| 251 |
return utilio.ConsistentRead(path, maxListTries) |
| 252 |
} |
| 253 |
|
| 254 |
return os.ReadFile(path) |
| 255 |
} |