github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/fsutil/disk_info_freebsd.go (about)

     1  // Copyright 2021 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 freebsd
    15  
    16  package fsutil
    17  
    18  import (
    19  	"os"
    20  	"path/filepath"
    21  	"syscall"
    22  
    23  	cerror "github.com/pingcap/tiflow/pkg/errors"
    24  )
    25  
    26  // GetDiskInfo return the disk space information of the given directory
    27  // the caller should guarantee that dir exist
    28  func GetDiskInfo(dir string) (*DiskInfo, error) {
    29  	f := filepath.Join(dir, "file.test")
    30  	if err := os.WriteFile(f, []byte(""), 0o600); err != nil {
    31  		return nil, cerror.WrapError(cerror.ErrGetDiskInfo, err)
    32  	}
    33  
    34  	fs := syscall.Statfs_t{}
    35  	if err := syscall.Statfs(dir, &fs); err != nil {
    36  		return nil, cerror.WrapError(cerror.ErrGetDiskInfo, err)
    37  	}
    38  
    39  	info := &DiskInfo{
    40  		All:   fs.Blocks * uint64(fs.Bsize) / gb,
    41  		Avail: uint64(fs.Bavail) * uint64(fs.Bsize) / gb,
    42  		Free:  fs.Bfree * uint64(fs.Bsize) / gb,
    43  	}
    44  	info.Used = info.All - info.Free
    45  	info.AvailPercentage = float32(info.Avail) / float32(info.All) * 100
    46  
    47  	if err := os.Remove(f); err != nil {
    48  		if !os.IsNotExist(err) {
    49  			return info, cerror.WrapError(cerror.ErrGetDiskInfo, err)
    50  		}
    51  	}
    52  
    53  	return info, nil
    54  }