2018-02-05 16:05:59 -05:00
|
|
|
package fsutils // import "github.com/docker/docker/pkg/fsutils"
|
2016-10-17 00:30:16 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"unsafe"
|
2017-05-23 10:22:32 -04:00
|
|
|
|
|
|
|
"golang.org/x/sys/unix"
|
2016-10-17 00:30:16 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
func locateDummyIfEmpty(path string) (string, error) {
|
2021-08-24 06:10:50 -04:00
|
|
|
children, err := os.ReadDir(path)
|
2016-10-17 00:30:16 -04:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
if len(children) != 0 {
|
|
|
|
return "", nil
|
|
|
|
}
|
2021-08-24 06:10:50 -04:00
|
|
|
dummyFile, err := os.CreateTemp(path, "fsutils-dummy")
|
2016-10-17 00:30:16 -04:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
name := dummyFile.Name()
|
2016-12-13 15:10:11 -05:00
|
|
|
err = dummyFile.Close()
|
|
|
|
return name, err
|
2016-10-17 00:30:16 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// SupportsDType returns whether the filesystem mounted on path supports d_type
|
|
|
|
func SupportsDType(path string) (bool, error) {
|
|
|
|
// locate dummy so that we have at least one dirent
|
|
|
|
dummy, err := locateDummyIfEmpty(path)
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
if dummy != "" {
|
|
|
|
defer os.Remove(dummy)
|
|
|
|
}
|
|
|
|
|
|
|
|
visited := 0
|
|
|
|
supportsDType := true
|
2017-05-23 10:22:32 -04:00
|
|
|
fn := func(ent *unix.Dirent) bool {
|
2016-10-17 00:30:16 -04:00
|
|
|
visited++
|
2017-05-23 10:22:32 -04:00
|
|
|
if ent.Type == unix.DT_UNKNOWN {
|
2016-10-17 00:30:16 -04:00
|
|
|
supportsDType = false
|
|
|
|
// stop iteration
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
// continue iteration
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if err = iterateReadDir(path, fn); err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
if visited == 0 {
|
|
|
|
return false, fmt.Errorf("did not hit any dirent during iteration %s", path)
|
|
|
|
}
|
|
|
|
return supportsDType, nil
|
|
|
|
}
|
|
|
|
|
2017-05-23 10:22:32 -04:00
|
|
|
func iterateReadDir(path string, fn func(*unix.Dirent) bool) error {
|
2016-10-17 00:30:16 -04:00
|
|
|
d, err := os.Open(path)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer d.Close()
|
|
|
|
fd := int(d.Fd())
|
|
|
|
buf := make([]byte, 4096)
|
|
|
|
for {
|
2017-05-23 10:22:32 -04:00
|
|
|
nbytes, err := unix.ReadDirent(fd, buf)
|
2016-10-17 00:30:16 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if nbytes == 0 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
for off := 0; off < nbytes; {
|
2017-05-23 10:22:32 -04:00
|
|
|
ent := (*unix.Dirent)(unsafe.Pointer(&buf[off]))
|
2016-10-17 00:30:16 -04:00
|
|
|
if stop := fn(ent); stop {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
off += int(ent.Reclen)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|