Ensure getting the correct mountinfo corresponds to path

Signed-off-by: Yanqiang Miao <miao.yanqiang@zte.com.cn>
This commit is contained in:
Yanqiang Miao
2017-10-03 12:44:46 +08:00
parent a8426ed9e7
commit d7c4611848
2 changed files with 39 additions and 3 deletions

View File

@@ -4,6 +4,9 @@ package mount
import (
"fmt"
"path/filepath"
"sort"
"strings"
"syscall"
"github.com/pkg/errors"
@@ -12,6 +15,7 @@ import (
// Lookup returns the mount info corresponds to the path.
func Lookup(dir string) (Info, error) {
var dirStat syscall.Stat_t
dir = filepath.Clean(dir)
if err := syscall.Stat(dir, &dirStat); err != nil {
return Info{}, errors.Wrapf(err, "failed to access %q", dir)
}
@@ -20,6 +24,11 @@ func Lookup(dir string) (Info, error) {
if err != nil {
return Info{}, err
}
// Sort descending order by Info.Mountpoint
sort.Slice(mounts, func(i, j int) bool {
return mounts[j].Mountpoint < mounts[i].Mountpoint
})
for _, m := range mounts {
// Note that m.{Major, Minor} are generally unreliable for our purpose here
// https://www.spinics.net/lists/linux-btrfs/msg58908.html
@@ -28,7 +37,7 @@ func Lookup(dir string) (Info, error) {
// may fail; ignore err
continue
}
if st.Dev == dirStat.Dev {
if st.Dev == dirStat.Dev && strings.HasPrefix(dir, m.Mountpoint) {
return m, nil
}
}