github.com/pingcap/br@v5.3.0-alpha.0.20220125034240-ec59c7b6ce30+incompatible/pkg/lightning/common/storage_unix.go (about)

     1  // Copyright 2019 PingCAP, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  // +build !windows
    15  
    16  // TODO: Deduplicate this implementation with DM!
    17  
    18  package common
    19  
    20  import (
    21  	"reflect"
    22  	"syscall"
    23  
    24  	"golang.org/x/sys/unix"
    25  
    26  	"github.com/pingcap/errors"
    27  )
    28  
    29  // GetStorageSize gets storage's capacity and available size
    30  func GetStorageSize(dir string) (size StorageSize, err error) {
    31  	var stat unix.Statfs_t
    32  
    33  	err = unix.Statfs(dir, &stat)
    34  	if err != nil {
    35  		return size, errors.Annotatef(err, "cannot get disk capacity at %s", dir)
    36  	}
    37  
    38  	// When container is run in MacOS, `bsize` obtained by `statfs` syscall is not the fundamental block size,
    39  	// but the `iosize` (optimal transfer block size) instead, it's usually 1024 times larger than the `bsize`.
    40  	// for example `4096 * 1024`. To get the correct block size, we should use `frsize`. But `frsize` isn't
    41  	// guaranteed to be supported everywhere, so we need to check whether it's supported before use it.
    42  	// For more details, please refer to: https://github.com/docker/for-mac/issues/2136
    43  	bSize := uint64(stat.Bsize)
    44  	field := reflect.ValueOf(&stat).Elem().FieldByName("Frsize")
    45  	if field.IsValid() {
    46  		if field.Kind() == reflect.Uint64 {
    47  			bSize = field.Uint()
    48  		} else {
    49  			bSize = uint64(field.Int())
    50  		}
    51  	}
    52  
    53  	// Available blocks * size per block = available space in bytes
    54  	size.Available = uint64(stat.Bavail) * bSize
    55  	size.Capacity = stat.Blocks * bSize
    56  
    57  	return
    58  }
    59  
    60  // SameDisk is used to check dir1 and dir2 in the same disk.
    61  func SameDisk(dir1 string, dir2 string) (bool, error) {
    62  	st1 := syscall.Stat_t{}
    63  	st2 := syscall.Stat_t{}
    64  
    65  	if err := syscall.Stat(dir1, &st1); err != nil {
    66  		return false, err
    67  	}
    68  
    69  	if err := syscall.Stat(dir2, &st2); err != nil {
    70  		return false, err
    71  	}
    72  
    73  	return st1.Dev == st2.Dev, nil
    74  }