2017-03-29 20:55:42 -04:00
|
|
|
// +build linux,cgo
|
2015-12-14 17:16:34 -05:00
|
|
|
|
2018-02-05 16:05:59 -05:00
|
|
|
package loopback // import "github.com/docker/docker/pkg/loopback"
|
2015-12-14 17:16:34 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
|
2017-07-26 17:42:13 -04:00
|
|
|
"github.com/sirupsen/logrus"
|
2017-07-27 03:51:23 -04:00
|
|
|
"golang.org/x/sys/unix"
|
2015-12-14 17:16:34 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
func getLoopbackBackingFile(file *os.File) (uint64, uint64, error) {
|
|
|
|
loopInfo, err := ioctlLoopGetStatus64(file.Fd())
|
|
|
|
if err != nil {
|
|
|
|
logrus.Errorf("Error get loopback backing file: %s", err)
|
|
|
|
return 0, 0, ErrGetLoopbackBackingFile
|
|
|
|
}
|
|
|
|
return loopInfo.loDevice, loopInfo.loInode, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetCapacity reloads the size for the loopback device.
|
|
|
|
func SetCapacity(file *os.File) error {
|
|
|
|
if err := ioctlLoopSetCapacity(file.Fd(), 0); err != nil {
|
|
|
|
logrus.Errorf("Error loopbackSetCapacity: %s", err)
|
|
|
|
return ErrSetCapacity
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// FindLoopDeviceFor returns a loopback device file for the specified file which
|
|
|
|
// is backing file of a loop back device.
|
|
|
|
func FindLoopDeviceFor(file *os.File) *os.File {
|
2017-07-27 03:51:23 -04:00
|
|
|
var stat unix.Stat_t
|
|
|
|
err := unix.Stat(file.Name(), &stat)
|
2015-12-14 17:16:34 -05:00
|
|
|
if err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
2017-07-27 03:51:23 -04:00
|
|
|
targetInode := stat.Ino
|
|
|
|
targetDevice := stat.Dev
|
2015-12-14 17:16:34 -05:00
|
|
|
|
|
|
|
for i := 0; true; i++ {
|
|
|
|
path := fmt.Sprintf("/dev/loop%d", i)
|
|
|
|
|
|
|
|
file, err := os.OpenFile(path, os.O_RDWR, 0)
|
|
|
|
if err != nil {
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ignore all errors until the first not-exist
|
|
|
|
// we want to continue looking for the file
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
dev, inode, err := getLoopbackBackingFile(file)
|
|
|
|
if err == nil && dev == targetDevice && inode == targetInode {
|
|
|
|
return file
|
|
|
|
}
|
|
|
|
file.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|