node-api/docker/tools.go

73 lines
1.3 KiB
Go
Raw Normal View History

2020-07-09 22:27:23 +00:00
package docker
import (
"bytes"
2020-07-11 11:04:37 +00:00
"os"
2020-07-09 22:27:23 +00:00
"os/exec"
2020-07-11 11:04:37 +00:00
"path/filepath"
2020-07-09 22:27:23 +00:00
"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
command := exec.Command("/usr/bin/du -m -s " + path)
command.Stdout = &out
err := command.Run()
if err != nil {
return space, inodes, err
}
fields := strings.Fields(strings.TrimSpace(out.String()))
out.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
err = command.Run()
if err != nil {
return space, inodes, err
}
fields = strings.Fields(strings.TrimSpace(out.String()))
out.Reset()
if len(fields) == 2 {
space, err = strconv.Atoi(fields[0])
if err != nil {
return inodes, inodes, err
}
}
return space, inodes, nil
}
2020-07-11 11:04:37 +00:00
// 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
}