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

     1  // Copyright 2020 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  package fsutil
    15  
    16  import (
    17  	"fmt"
    18  	"os"
    19  	"path/filepath"
    20  
    21  	"github.com/pingcap/errors"
    22  	cerror "github.com/pingcap/tiflow/pkg/errors"
    23  )
    24  
    25  const (
    26  	gb = 1024 * 1024 * 1024
    27  )
    28  
    29  // IsDirAndWritable checks a given path is directory and writable
    30  func IsDirAndWritable(path string) error {
    31  	st, err := os.Stat(path)
    32  	if err != nil {
    33  		return cerror.WrapError(cerror.ErrCheckDirWritable, err)
    34  	}
    35  	if !st.IsDir() {
    36  		return cerror.WrapError(cerror.ErrCheckDirWritable, errors.Errorf("%s is not a directory", path))
    37  	}
    38  	return IsDirWritable(path)
    39  }
    40  
    41  // IsDirWritable checks if a dir is writable, return error nil means it is writable
    42  func IsDirWritable(dir string) error {
    43  	f := filepath.Join(dir, ".writable.test")
    44  	if err := os.WriteFile(f, []byte(""), 0o600); err != nil {
    45  		return cerror.WrapError(cerror.ErrCheckDirWritable, err)
    46  	}
    47  	return cerror.WrapError(cerror.ErrCheckDirWritable, os.Remove(f))
    48  }
    49  
    50  // IsDirReadWritable check if the dir is writable and readable by cdc server
    51  func IsDirReadWritable(dir string) error {
    52  	f := filepath.Join(dir, "file.test")
    53  	if err := os.WriteFile(f, []byte(""), 0o600); err != nil {
    54  		return cerror.WrapError(cerror.ErrCheckDirValid, err)
    55  	}
    56  
    57  	if _, err := os.ReadFile(f); err != nil {
    58  		return cerror.WrapError(cerror.ErrCheckDirValid, err)
    59  	}
    60  
    61  	return cerror.WrapError(cerror.ErrCheckDirValid, os.Remove(f))
    62  }
    63  
    64  // DiskInfo present the disk amount information, in gb
    65  type DiskInfo struct {
    66  	All             uint64
    67  	Used            uint64
    68  	Free            uint64
    69  	Avail           uint64
    70  	AvailPercentage float32
    71  }
    72  
    73  func (d *DiskInfo) String() string {
    74  	return fmt.Sprintf("{All: %+vGB; Used: %+vGB; Free: %+vGB; Available: %+vGB; Available Percentage: %+v%%}",
    75  		d.All, d.Used, d.Free, d.Avail, d.AvailPercentage)
    76  }