github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/dm/pkg/utils/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  //go:build !windows && !freebsd
    15  
    16  package utils
    17  
    18  import (
    19  	"reflect"
    20  
    21  	"github.com/pingcap/tiflow/dm/pkg/terror"
    22  	"golang.org/x/sys/unix"
    23  )
    24  
    25  // GetStorageSize gets storage's capacity and available size.
    26  func GetStorageSize(dir string) (size StorageSize, err error) {
    27  	var stat unix.Statfs_t
    28  
    29  	err = unix.Statfs(dir, &stat)
    30  	if err != nil {
    31  		return size, terror.ErrStatFileSize.Delegate(err)
    32  	}
    33  
    34  	// When container is run in MacOS, `bsize` obtained by `statfs` syscall is not the fundamental block size,
    35  	// but the `iosize` (optimal transfer block size) instead, it's usually 1024 times larger than the `bsize`.
    36  	// for example `4096 * 1024`. To get the correct block size, we should use `frsize`. But `frsize` isn't
    37  	// guaranteed to be supported everywhere, so we need to check whether it's supported before use it.
    38  	// For more details, please refer to: https://github.com/docker/for-mac/issues/2136
    39  	bSize := uint64(stat.Bsize)
    40  	field := reflect.ValueOf(&stat).Elem().FieldByName("Frsize")
    41  	if field.IsValid() {
    42  		if field.Kind() == reflect.Uint64 {
    43  			bSize = field.Uint()
    44  		} else {
    45  			bSize = uint64(field.Int())
    46  		}
    47  	}
    48  
    49  	// Available blocks * size per block = available space in bytes
    50  	size.Available = stat.Bavail * bSize
    51  	size.Capacity = stat.Blocks * bSize
    52  
    53  	return
    54  }