File: loopback.go

package info (click to toggle)
golang-github-coreos-bbolt 1.4.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,300 kB
  • sloc: makefile: 87; sh: 57
file content (91 lines) | stat: -rw-r--r-- 2,337 bytes parent folder | download
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
//go:build linux

package dmflakey

import (
	"errors"
	"fmt"
	"os"
	"time"

	"golang.org/x/sys/unix"
)

const (
	loopControlDevice = "/dev/loop-control"
	loopDevicePattern = "/dev/loop%d"

	maxRetryToAttach = 50
)

// attachToLoopDevice associates free loop device with backing file.
//
// There might have race condition. It needs to retry when it runs into EBUSY.
//
// REF: https://man7.org/linux/man-pages/man4/loop.4.html
func attachToLoopDevice(backingFile string) (string, error) {
	backingFd, err := os.OpenFile(backingFile, os.O_RDWR, 0)
	if err != nil {
		return "", fmt.Errorf("failed to open loop device's backing file %s: %w",
			backingFile, err)
	}
	defer backingFd.Close()

	for i := 0; i < maxRetryToAttach; i++ {
		loop, err := getFreeLoopDevice()
		if err != nil {
			return "", fmt.Errorf("failed to get free loop device: %w", err)
		}

		err = func() error {
			loopFd, err := os.OpenFile(loop, os.O_RDWR, 0)
			if err != nil {
				return err
			}
			defer loopFd.Close()

			return unix.IoctlSetInt(int(loopFd.Fd()),
				unix.LOOP_SET_FD, int(backingFd.Fd()))
		}()
		if err != nil {
			if errors.Is(err, unix.EBUSY) {
				time.Sleep(500 * time.Millisecond)
				continue
			}
			return "", err
		}
		return loop, nil
	}
	return "", fmt.Errorf("failed to associate free loop device with backing file %s after retry %v",
		backingFile, maxRetryToAttach)
}

// detachLoopDevice disassociates the loop device from any backing file.
//
// REF: https://man7.org/linux/man-pages/man4/loop.4.html
func detachLoopDevice(loopDevice string) error {
	loopFd, err := os.Open(loopDevice)
	if err != nil {
		return fmt.Errorf("failed to open loop %s: %w", loopDevice, err)
	}
	defer loopFd.Close()

	return unix.IoctlSetInt(int(loopFd.Fd()), unix.LOOP_CLR_FD, 0)
}

// getFreeLoopDevice allocates or finds a free loop device for use.
//
// REF: https://man7.org/linux/man-pages/man4/loop.4.html
func getFreeLoopDevice() (string, error) {
	control, err := os.OpenFile(loopControlDevice, os.O_RDWR, 0)
	if err != nil {
		return "", fmt.Errorf("failed to open %s: %w", loopControlDevice, err)
	}

	idx, err := unix.IoctlRetInt(int(control.Fd()), unix.LOOP_CTL_GET_FREE)
	control.Close()
	if err != nil {
		return "", fmt.Errorf("failed to get free loop device number: %w", err)
	}
	return fmt.Sprintf(loopDevicePattern, idx), nil
}