github.com/anonymouse64/snapd@v0.0.0-20210824153203-04c4c42d842d/osutil/disk.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2020 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package osutil
    21  
    22  import (
    23  	"fmt"
    24  	"syscall"
    25  
    26  	"github.com/snapcore/snapd/strutil"
    27  )
    28  
    29  var syscallStatfs = syscall.Statfs
    30  
    31  type NotEnoughDiskSpaceError struct {
    32  	Path  string
    33  	Delta int64
    34  }
    35  
    36  func (e *NotEnoughDiskSpaceError) Error() string {
    37  	return fmt.Sprintf("insufficient space in %q, at least %s more is required", e.Path, strutil.SizeToStr(e.Delta))
    38  }
    39  
    40  // diskFree returns free disk space for the given path
    41  func diskFree(path string) (uint64, error) {
    42  	var st syscall.Statfs_t
    43  	if err := syscallStatfs(path, &st); err != nil {
    44  		return 0, err
    45  	}
    46  	// available blocks * block size
    47  	return st.Bavail * uint64(st.Bsize), nil
    48  }
    49  
    50  // CheckFreeSpace checks if there is enough disk space for the given path
    51  func CheckFreeSpace(path string, minSize uint64) error {
    52  	free, err := diskFree(path)
    53  	if err != nil {
    54  		return err
    55  	}
    56  	if free < minSize {
    57  		delta := int64(minSize - free)
    58  		return &NotEnoughDiskSpaceError{Path: path, Delta: delta}
    59  	}
    60  	return nil
    61  }