github.com/pingcap/tidb-lightning@v5.0.0-rc.0.20210428090220-84b649866577+incompatible/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  
    23  	"golang.org/x/sys/unix"
    24  
    25  	"github.com/pingcap/errors"
    26  )
    27  
    28  // GetStorageSize gets storage's capacity and available size
    29  func GetStorageSize(dir string) (size StorageSize, err error) {
    30  	var stat unix.Statfs_t
    31  
    32  	err = unix.Statfs(dir, &stat)
    33  	if err != nil {
    34  		return size, errors.Annotatef(err, "cannot get disk capacity at %s", dir)
    35  	}
    36  
    37  	// When container is run in MacOS, `bsize` obtained by `statfs` syscall is not the fundamental block size,
    38  	// but the `iosize` (optimal transfer block size) instead, it's usually 1024 times larger than the `bsize`.
    39  	// for example `4096 * 1024`. To get the correct block size, we should use `frsize`. But `frsize` isn't
    40  	// guaranteed to be supported everywhere, so we need to check whether it's supported before use it.
    41  	// For more details, please refer to: https://github.com/docker/for-mac/issues/2136
    42  	bSize := uint64(stat.Bsize)
    43  	field := reflect.ValueOf(&stat).Elem().FieldByName("Frsize")
    44  	if field.IsValid() {
    45  		if field.Kind() == reflect.Uint64 {
    46  			bSize = field.Uint()
    47  		} else {
    48  			bSize = uint64(field.Int())
    49  		}
    50  	}
    51  
    52  	// Available blocks * size per block = available space in bytes
    53  	size.Available = stat.Bavail * bSize
    54  	size.Capacity = stat.Blocks * bSize
    55  
    56  	return
    57  }