File: du_unix_test.go

package info (click to toggle)
continuity 0.0~git20201208.1805252-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 612 kB
  • sloc: makefile: 53; sh: 28
file content (97 lines) | stat: -rw-r--r-- 2,304 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// +build !windows

/*
   Copyright The containerd Authors.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package fs

import (
	"io/ioutil"
	"os"
	"strconv"
	"strings"
	"syscall"

	"github.com/pkg/errors"
)

func getBsize(root string) (int64, error) {
	var s syscall.Statfs_t
	if err := syscall.Statfs(root, &s); err != nil {
		return 0, err
	}

	return int64(s.Bsize), nil // nolint: unconvert
}

// getTmpAlign returns filesystem specific size alignment functions
// first:  aligns filesize to file usage based on blocks
// second: determines directory usage based on directory count (assumes small directories)
func getTmpAlign() (func(int64) int64, func(int64) int64, error) {
	t1, err := ioutil.TempDir("", "compute-align-")
	if err != nil {
		return nil, nil, errors.Wrap(err, "failed to create temp dir")
	}
	defer os.RemoveAll(t1)

	bsize, err := getBsize(t1)
	if err != nil {
		return nil, nil, errors.Wrap(err, "failed to get bsize")
	}

	align := func(size int64) int64 {
		// Align to blocks
		aligned := (size / bsize) * bsize

		// Add next block if has remainder
		if size%bsize > 0 {
			aligned += bsize
		}

		return aligned
	}

	fi, err := os.Stat(t1)
	if err != nil {
		return nil, nil, errors.Wrap(err, "failed to stat directory")
	}

	dirSize := fi.Sys().(*syscall.Stat_t).Blocks * blocksUnitSize
	dirs := func(count int64) int64 {
		return count * dirSize
	}

	return align, dirs, nil
}

func duCheck(root string) (usage int64, err error) {
	cmd := duCmd(root)
	cmd.Stderr = os.Stderr
	out, err := cmd.Output()
	if err != nil {
		return 0, err
	}
	if len(out) == 0 {
		return 0, errors.New("no du output")
	}
	size := strings.Fields(string(out))[0]
	blocks, err := strconv.ParseInt(size, 10, 64)
	if err != nil {
		return 0, err
	}
	return blocks * blocksUnitSize, nil

}