node-api/docker/tools.go
2020-07-16 23:24:09 +02:00

81 lines
1.5 KiB
Go

package docker
import (
"bytes"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
)
// Return bytes, inodes occupied by a directory and/or error if there is any
func du(path string) (int, int, error) {
space, inodes := 0, 0
// Occupied space
var out bytes.Buffer
var errOut bytes.Buffer
command := exec.Command("/usr/bin/du", "-b", "-s", path)
command.Stdout = &out
command.Stderr = &errOut
err := command.Run()
if err != nil {
log.Println(errOut.String())
return space, inodes, err
}
fields := strings.Fields(strings.TrimSpace(out.String()))
out.Reset()
errOut.Reset()
if len(fields) == 2 {
space, err = strconv.Atoi(fields[0])
if err != nil {
return space, inodes, err
}
}
// Occupied inodes
command = exec.Command("/usr/bin/du", "--inodes", "-s", path)
command.Stdout = &out
command.Stderr = &errOut
err = command.Run()
if err != nil {
log.Println(errOut.String())
return space, inodes, err
}
fields = strings.Fields(strings.TrimSpace(out.String()))
out.Reset()
errOut.Reset()
if len(fields) == 2 {
inodes, err = strconv.Atoi(fields[0])
if err != nil {
return inodes, inodes, err
}
}
return space, inodes, nil
}
// Removes content of given directory
func removeDirectory(dir string) error {
d, err := os.Open(dir)
if err != nil {
return err
}
defer d.Close()
names, err := d.Readdirnames(-1)
if err != nil {
return err
}
for _, name := range names {
err = os.RemoveAll(filepath.Join(dir, name))
if err != nil {
return err
}
}
return nil
}