node-api/docker/tools.go

83 lines
1.6 KiB
Go
Raw Normal View History

2020-07-09 22:27:23 +00:00
package docker
import (
"bytes"
2020-07-15 21:32:28 +00:00
"log"
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
2020-07-15 21:32:28 +00:00
var errOut bytes.Buffer
command := exec.Command("/usr/bin/du", "-m", "-s", path)
2020-07-09 22:27:23 +00:00
command.Stdout = &out
2020-07-15 21:32:28 +00:00
command.Stderr = &errOut
2020-07-09 22:27:23 +00:00
err := command.Run()
if err != nil {
2020-07-15 21:32:28 +00:00
log.Println(errOut.String())
log.Println("/usr/bin/du -m -s " + path)
2020-07-09 22:27:23 +00:00
return space, inodes, err
}
fields := strings.Fields(strings.TrimSpace(out.String()))
out.Reset()
2020-07-15 21:32:28 +00:00
errOut.Reset()
2020-07-09 22:27:23 +00:00
if len(fields) == 2 {
space, err = strconv.Atoi(fields[0])
if err != nil {
return space, inodes, err
}
}
// Occupied inodes
2020-07-15 21:32:28 +00:00
command = exec.Command("/usr/bin/du", "--inodes", "-s", path)
2020-07-09 22:27:23 +00:00
command.Stdout = &out
2020-07-15 21:32:28 +00:00
command.Stderr = &errOut
2020-07-09 22:27:23 +00:00
err = command.Run()
if err != nil {
2020-07-15 21:32:28 +00:00
log.Println(errOut.String())
log.Println("/usr/bin/du --inodes -s " + path)
2020-07-09 22:27:23 +00:00
return space, inodes, err
}
fields = strings.Fields(strings.TrimSpace(out.String()))
out.Reset()
2020-07-15 21:32:28 +00:00
errOut.Reset()
2020-07-09 22:27:23 +00:00
if len(fields) == 2 {
2020-07-15 21:32:28 +00:00
inodes, err = strconv.Atoi(fields[0])
2020-07-09 22:27:23 +00:00
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
}