-
Notifications
You must be signed in to change notification settings - Fork 457
/
mount.go
504 lines (402 loc) · 11.5 KB
/
mount.go
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
// 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"
"strings"
"time"
"github.com/siderolabs/go-blockdevice/blockdevice"
"github.com/siderolabs/go-blockdevice/blockdevice/filesystem"
"github.com/siderolabs/go-blockdevice/blockdevice/util"
"github.com/siderolabs/go-retry/retry"
"golang.org/x/sys/unix"
"github.com/siderolabs/talos/pkg/machinery/constants"
"github.com/siderolabs/talos/pkg/makefs"
)
// RetryFunc defines the requirements for retrying a mount point operation.
type RetryFunc func(*Point) error
// Mount mounts the device(s).
func Mount(mountpoints *Points) (err error) {
iter := mountpoints.Iter()
// Mount the device(s).
for iter.Next() {
if _, err = mountMountpoint(iter.Value()); err != nil {
return fmt.Errorf("error mounting %q: %w", iter.Value().Source(), err)
}
}
if iter.Err() != nil {
return iter.Err()
}
return nil
}
//nolint:gocyclo
func mountMountpoint(mountpoint *Point) (skipMount bool, err error) {
// Repair the disk's partition table.
if mountpoint.MountFlags.Check(Resize) {
if _, err = mountpoint.ResizePartition(); err != nil {
return false, fmt.Errorf("error resizing %w", err)
}
}
if mountpoint.MountFlags.Check(SkipIfMounted) {
skipMount, err = mountpoint.IsMounted()
if err != nil {
return false, fmt.Errorf("mountpoint is set to skip if mounted, but the mount check failed: %w", err)
}
}
if mountpoint.MountFlags.Check(SkipIfNoFilesystem) && mountpoint.Fstype() == filesystem.Unknown {
skipMount = true
}
if !skipMount {
if err = mountpoint.Mount(); err != nil {
if mountpoint.MountFlags.Check(SkipIfNoDevice) && errors.Is(err, unix.ENODEV) {
if mountpoint.Logger != nil {
mountpoint.Logger.Printf("error mounting: %q: %s", mountpoint.Source(), err)
}
return true, nil
}
return false, fmt.Errorf("error mounting: %w", err)
}
}
// Grow the filesystem to the maximum allowed size.
//
// Growfs is called always, even if ResizePartition returns false to workaround failure scenario
// when partition was resized, but growfs never got called.
if mountpoint.MountFlags.Check(Resize) {
if err = mountpoint.GrowFilesystem(); err != nil {
return false, fmt.Errorf("error resizing filesystem: %w", err)
}
}
return skipMount, nil
}
// Unmount unmounts the device(s).
func Unmount(mountpoints *Points) (err error) {
iter := mountpoints.IterRev()
for iter.Next() {
mountpoint := iter.Value()
if err = mountpoint.Unmount(); err != nil {
return fmt.Errorf("unmount: %w", err)
}
}
if iter.Err() != nil {
return iter.Err()
}
return nil
}
// Move moves the device(s).
// TODO(andrewrynhard): We need to skip calling the move method on mountpoints
// that are a child of another mountpoint. The kernel will handle moving the
// child mountpoints for us.
func Move(mountpoints *Points, prefix string) (err error) {
iter := mountpoints.Iter()
for iter.Next() {
mountpoint := iter.Value()
if err = mountpoint.Move(prefix); err != nil {
return fmt.Errorf("move: %w", err)
}
}
if iter.Err() != nil {
return iter.Err()
}
return nil
}
// PrefixMountTargets prefixes all mountpoints targets with fixed path.
func PrefixMountTargets(mountpoints *Points, targetPrefix string) error {
iter := mountpoints.Iter()
for iter.Next() {
mountpoint := iter.Value()
mountpoint.target = filepath.Join(targetPrefix, mountpoint.target)
}
return iter.Err()
}
//nolint:gocyclo
func mountRetry(f RetryFunc, p *Point, isUnmount bool) (err error) {
err = retry.Constant(5*time.Second, retry.WithUnits(50*time.Millisecond)).Retry(func() error {
if err = f(p); err != nil {
switch err {
case unix.EBUSY:
return retry.ExpectedError(err)
case unix.ENOENT, unix.ENODEV:
// if udevd triggers BLKRRPART ioctl, partition device entry might disappear temporarily
return retry.ExpectedError(err)
case unix.EUCLEAN:
if errRepair := p.Repair(); errRepair != nil {
return fmt.Errorf("error repairing: %w", errRepair)
}
return retry.ExpectedError(err)
case unix.EINVAL:
isMounted, checkErr := p.IsMounted()
if checkErr != nil {
return retry.ExpectedError(checkErr)
}
if !isMounted && !isUnmount {
if errRepair := p.Repair(); errRepair != nil {
return fmt.Errorf("error repairing: %w", errRepair)
}
return retry.ExpectedError(err)
}
if !isMounted && isUnmount { // if partition is already unmounted, ignore EINVAL
return nil
}
return err
default:
return err
}
}
return nil
})
return err
}
// Point represents a Linux mount point.
type Point struct {
source string
target string
fstype string
flags uintptr
data string
*Options
}
// PointMap represents a unique set of mount points.
type PointMap = map[string]*Point
// Points represents an ordered set of mount points.
type Points struct {
points PointMap
order []string
}
// NewMountPoint initializes and returns a Point struct.
func NewMountPoint(source, target, fstype string, flags uintptr, data string, setters ...Option) *Point {
opts := NewDefaultOptions(setters...)
p := &Point{
source: source,
target: target,
fstype: fstype,
flags: flags,
data: data,
Options: opts,
}
if p.Prefix != "" {
p.target = filepath.Join(p.Prefix, p.target)
}
if p.Options.ProjectQuota {
if len(p.data) > 0 {
p.data += ","
}
p.data += "prjquota"
}
return p
}
// NewMountPoints initializes and returns a Points struct.
func NewMountPoints() *Points {
return &Points{
points: make(PointMap),
}
}
// Source returns the mount points source field.
func (p *Point) Source() string {
return p.source
}
// Target returns the mount points target field.
func (p *Point) Target() string {
return p.target
}
// Fstype returns the mount points fstype field.
func (p *Point) Fstype() string {
return p.fstype
}
// Flags returns the mount points flags field.
func (p *Point) Flags() uintptr {
return p.flags
}
// Data returns the mount points data field.
func (p *Point) Data() string {
return p.data
}
// Mount attempts to retry a mount on EBUSY. It will attempt a retry
// every 100 milliseconds over the course of 5 seconds.
func (p *Point) Mount() (err error) {
for _, hook := range p.Options.PreMountHooks {
if err = hook(p); err != nil {
return err
}
}
if err = ensureDirectory(p.target); err != nil {
return err
}
if p.MountFlags.Check(ReadOnly) {
p.flags |= unix.MS_RDONLY
}
switch {
case p.MountFlags.Check(Overlay):
err = mountRetry(overlay, p, false)
case p.MountFlags.Check(ReadonlyOverlay):
err = mountRetry(readonlyOverlay, p, false)
default:
err = mountRetry(mount, p, false)
}
if err != nil {
return err
}
if p.MountFlags.Check(Shared) {
if err = mountRetry(share, p, false); err != nil {
return fmt.Errorf("error sharing mount point %s: %+v", p.target, err)
}
}
return nil
}
// Unmount attempts to retry an unmount on EBUSY. It will attempt a
// retry every 100 milliseconds over the course of 5 seconds.
func (p *Point) Unmount() (err error) {
var mounted bool
if mounted, err = p.IsMounted(); err != nil {
return err
}
if mounted {
if err = mountRetry(unmount, p, true); err != nil {
return err
}
}
for _, hook := range p.Options.PostUnmountHooks {
if err = hook(p); err != nil {
return err
}
}
return nil
}
// IsMounted checks whether mount point is active under /proc/mounts.
func (p *Point) IsMounted() (bool, error) {
f, err := os.Open("/proc/mounts")
if err != nil {
return false, err
}
defer f.Close() //nolint:errcheck
scanner := bufio.NewScanner(f)
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) < 2 {
continue
}
mountpoint := fields[1]
if mountpoint == p.target {
return true, nil
}
}
return false, scanner.Err()
}
// Move moves a mountpoint to a new location with a prefix.
func (p *Point) Move(prefix string) (err error) {
target := p.Target()
mountpoint := NewMountPoint(target, target, "", unix.MS_MOVE, "", WithPrefix(prefix))
if err = mountpoint.Mount(); err != nil {
return fmt.Errorf("error moving mount point %s: %w", target, err)
}
return nil
}
// ResizePartition resizes a partition to the maximum size allowed.
func (p *Point) ResizePartition() (resized bool, err error) {
var devname string
if devname, err = util.DevnameFromPartname(p.Source()); err != nil {
return false, err
}
bd, err := blockdevice.Open("/dev/"+devname, blockdevice.WithExclusiveLock(true))
if err != nil {
return false, fmt.Errorf("error opening block device %q: %w", devname, err)
}
//nolint:errcheck
defer bd.Close()
pt, err := bd.PartitionTable()
if err != nil {
return false, err
}
if err := pt.Repair(); err != nil {
return false, err
}
for _, partition := range pt.Partitions().Items() {
if partition.Name == constants.EphemeralPartitionLabel {
resized, err := pt.Resize(partition)
if err != nil {
return false, err
}
if !resized {
return false, nil
}
}
}
if err := pt.Write(); err != nil {
return false, err
}
return true, nil
}
// GrowFilesystem grows a partition's filesystem to the maximum size allowed.
// NB: An XFS partition MUST be mounted, or this will fail.
func (p *Point) GrowFilesystem() (err error) {
if err = makefs.XFSGrow(p.Target()); err != nil {
return fmt.Errorf("xfs_growfs: %w", err)
}
return nil
}
// Repair repairs a partition's filesystem.
func (p *Point) Repair() error {
if p.Logger != nil {
p.Logger.Printf("filesystem on %s needs cleaning, running repair", p.Source())
}
if err := makefs.XFSRepair(p.Source(), p.Fstype()); err != nil {
return fmt.Errorf("xfs_repair: %w", err)
}
if p.Logger != nil {
p.Logger.Printf("filesystem successfully repaired on %s", p.Source())
}
return nil
}
func mount(p *Point) (err error) {
return unix.Mount(p.source, p.target, p.fstype, p.flags, p.data)
}
func unmount(p *Point) error {
return SafeUnmount(context.Background(), p.Logger, p.target)
}
func share(p *Point) error {
return unix.Mount("", p.target, "", unix.MS_SHARED|unix.MS_REC, "")
}
func overlay(p *Point) error {
parts := strings.Split(p.target, "/")
prefix := strings.Join(parts[1:], "-")
basePath := constants.VarSystemOverlaysPath
if p.MountFlags.Check(SystemOverlay) {
basePath = constants.SystemOverlaysPath
}
diff := fmt.Sprintf(filepath.Join(basePath, "%s-diff"), prefix)
workdir := fmt.Sprintf(filepath.Join(basePath, "%s-workdir"), prefix)
for _, target := range []string{diff, workdir} {
if err := ensureDirectory(target); err != nil {
return err
}
}
lowerDir := p.target
if p.source != "" {
lowerDir = p.source
}
opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lowerDir, diff, workdir)
if err := unix.Mount("overlay", p.target, "overlay", 0, opts); err != nil {
return fmt.Errorf("error creating overlay mount to %s: %w", p.target, err)
}
return nil
}
func readonlyOverlay(p *Point) error {
opts := fmt.Sprintf("lowerdir=%s", p.source)
if err := unix.Mount("overlay", p.target, "overlay", p.flags, opts); err != nil {
return fmt.Errorf("error creating overlay mount to %s: %w", p.target, err)
}
return nil
}
func ensureDirectory(target string) (err error) {
if _, err := os.Stat(target); os.IsNotExist(err) {
if err = os.MkdirAll(target, 0o755); err != nil {
return fmt.Errorf("error creating mount point directory %s: %w", target, err)
}
}
return nil
}