forked from siderolabs/talos
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunmount.go
More file actions
301 lines (247 loc) · 8.38 KB
/
Copy pathunmount.go
File metadata and controls
301 lines (247 loc) · 8.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package mount
import (
"bufio"
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"golang.org/x/sys/unix"
)
func trySyncMount(target string) error {
// Try the directory path first, then fall back to a file mountpoint.
fd, err := unix.Open(target, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
if err != nil {
if errors.Is(err, unix.ENOTDIR) {
fd, err = unix.Open(target, unix.O_RDONLY|unix.O_CLOEXEC, 0)
if err != nil {
return fmt.Errorf("open %q as file: %w", target, err)
}
} else {
return fmt.Errorf("open %q as directory: %w", target, err)
}
}
defer unix.Close(fd) //nolint:errcheck
// sync the filesystem backing this fd
if err := unix.Syncfs(fd); err != nil {
return fmt.Errorf("SYS_SYNCFS %q: %w", target, err)
}
return nil
}
func unmountLoop(ctx context.Context, printer func(string, ...any), target string, flags int, timeout time.Duration, extraMessage string) (bool, error) {
errCh := make(chan error, 1)
// we need to try to sync fs before
if err := trySyncMount(target); err != nil {
printer("sync failed: %s", err)
}
go func() {
errCh <- unix.Unmount(target, flags)
}()
start := time.Now()
progressTicker := time.NewTicker(timeout / 5)
defer progressTicker.Stop()
unmountLoop:
for {
select {
case <-ctx.Done():
return true, ctx.Err()
case err := <-errCh:
return true, err
case <-progressTicker.C:
timeLeft := timeout - time.Since(start)
if timeLeft <= 0 {
break unmountLoop
}
printer("unmounting %s%s is taking longer than expected, still waiting for %s", target, extraMessage, timeLeft)
}
}
return false, nil
}
// SafeUnmount unmounts the target path, first without force, then with force if the first attempt fails.
//
// It makes sure that unmounting has a finite operation timeout.
//
// If recursive is true, it first unmounts all child mounts (and overlays whose
// backing dirs live under target).
//
// If lazy is true, it detaches the target (and any submount it can't unmount)
// with MNT_DETACH as a last resort. This is used to tear down volatile pseudo
// mounts (e.g. /system, /run) on shutdown, where the target may still be pinned
// by kernel references (loop devices, peer mounts in other namespaces, ...)
// that no regular unmount can release. It should not be set for real
// filesystems, where a busy mount is better left for the caller to retry and
// diagnose.
//
//nolint:gocyclo
func SafeUnmount(ctx context.Context, printer func(string, ...any), target string, recursive, lazy bool) error {
const (
unmountTimeout = 90 * time.Second
unmountForceTimeout = 10 * time.Second
)
if printer == nil {
printer = discard
}
if recursive {
submounts, err := getSubmounts(target)
if err != nil {
printer("failed to get submounts for %s: %v", target, err)
} else {
for _, submount := range submounts {
printer("recursively unmounting submount %s", submount)
if err := safeUnmountSingle(ctx, printer, submount, unmountTimeout, lazy); err != nil {
printer("failed to unmount submount %s: %v", submount, err)
}
}
}
}
ok, err := unmountLoop(ctx, printer, target, 0, unmountTimeout, "")
// the unmount syscall completed within the timeout: a hung unmount (ok ==
// false) is the only case the force flag can help with, otherwise the
// result (success or e.g. EBUSY) is final for the regular attempt.
if !ok {
printer("unmounting %s with force", target)
ok, err = unmountLoop(ctx, printer, target, unix.MNT_FORCE, unmountForceTimeout, " with force flag")
}
switch {
case ok && err == nil:
return nil
case lazy:
// volatile pseudo mount still busy or hung: detach it lazily so it
// leaves the tree immediately and the kernel reaps it once the
// remaining references are gone.
return lazyDetach(printer, target)
case ok:
return err
default:
return fmt.Errorf("unmounting %s with force flag timed out", target)
}
}
// safeUnmountSingle unmounts a single submount that keeps a parent mount busy.
//
// When lazy is set, it falls back to a lazy detach (MNT_DETACH) if the regular
// unmount fails or times out: detaching the submount from the tree is enough to
// let the parent be unmounted, and the kernel reaps it once it's no longer in
// use. Otherwise it reports the unmount result for the caller to log.
func safeUnmountSingle(ctx context.Context, printer func(string, ...any), target string, timeout time.Duration, lazy bool) error {
ok, err := unmountLoop(ctx, printer, target, 0, timeout, "")
switch {
case ok && (err == nil || errors.Is(err, unix.EINVAL)):
// unmounted, or already unmounted
return nil
case !lazy:
if ok {
return err
}
return nil
}
return lazyDetach(printer, target)
}
// lazyDetach detaches target with MNT_DETACH, ignoring an EINVAL (not mounted).
func lazyDetach(printer func(string, ...any), target string) error {
printer("lazily detaching %s", target)
if err := unix.Unmount(target, unix.MNT_DETACH); err != nil && !errors.Is(err, unix.EINVAL) {
return err
}
return nil
}
func logSubmounts(printer func(string, ...any), target string) {
submounts, err := getSubmounts(target)
if err != nil {
printer("failed to get submounts for %s: %v", target, err)
return
}
if len(submounts) > 0 {
printer("submounts on %s: %v", target, submounts)
}
}
// logMountUsers scans /proc to find processes that have open file descriptors,
// working directories, or memory-mapped files under the given mount target.
// This helps diagnose "device or resource busy" errors during unmount.
//
//nolint:gocyclo,cyclop
func logMountUsers(printer func(string, ...any), target string) {
entries, err := os.ReadDir("/proc")
if err != nil {
printer("failed to read /proc: %v", err)
return
}
targetWithSlash := target + "/"
found := false
for _, entry := range entries {
if !entry.IsDir() {
continue
}
pid, err := strconv.Atoi(entry.Name())
if err != nil {
continue // not a PID directory
}
procPath := filepath.Join("/proc", entry.Name())
var offendingPaths []string
// Check cwd.
if cwd, err := os.Readlink(filepath.Join(procPath, "cwd")); err == nil {
if cwd == target || strings.HasPrefix(cwd, targetWithSlash) {
offendingPaths = append(offendingPaths, "cwd="+cwd)
}
}
// Check root.
if root, err := os.Readlink(filepath.Join(procPath, "root")); err == nil {
if root == target || strings.HasPrefix(root, targetWithSlash) {
offendingPaths = append(offendingPaths, "root="+root)
}
}
// Check open file descriptors.
if fds, err := os.ReadDir(filepath.Join(procPath, "fd")); err == nil {
for _, fd := range fds {
if link, err := os.Readlink(filepath.Join(procPath, "fd", fd.Name())); err == nil {
if link == target || strings.HasPrefix(link, targetWithSlash) {
offendingPaths = append(offendingPaths, "fd/"+fd.Name()+"="+link)
}
}
}
}
// Check memory-mapped files.
if f, err := os.Open(filepath.Join(procPath, "maps")); err == nil {
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
// maps format: address perms offset dev inode pathname
// pathname starts after the 5th field
fields := strings.Fields(line)
if len(fields) >= 6 {
mappedPath := fields[len(fields)-1]
if mappedPath == target || strings.HasPrefix(mappedPath, targetWithSlash) {
offendingPaths = append(offendingPaths, "mmap="+mappedPath)
}
}
}
f.Close() //nolint:errcheck
}
if len(offendingPaths) == 0 {
continue
}
found = true
// Read process identity.
comm := "<unknown>"
if data, err := os.ReadFile(filepath.Join(procPath, "comm")); err == nil {
comm = strings.TrimSpace(string(data))
}
cmdline := ""
if data, err := os.ReadFile(filepath.Join(procPath, "cmdline")); err == nil {
// cmdline uses null bytes as separators
cmdline = strings.ReplaceAll(strings.TrimRight(string(data), "\x00"), "\x00", " ")
}
printer("mount %s held by pid %d (%s) cmdline=[%s]: %s",
target, pid, comm, cmdline, strings.Join(offendingPaths, ", "))
}
if !found {
printer("mount %s is busy but no processes found holding it (may be held by kernel references)", target)
} else {
printer("if you see this message, report a bug with the above information to help us identify and fix the issue")
}
}