readysite / hosting / internal / websites / docker.go
1.3 KB
docker.go
package websites

import (
	"fmt"
	"os/exec"
	"strconv"
	"strings"
)

const (
	SiteImage     = "localhost:5001/website"
	SiteNetwork   = "readysite"
	SiteConfigDir = "/caddy/sites"
	SiteDataDir   = "/data/sites"
	DomainSuffix  = ".readysite.app"
)

// containerName returns the Docker container name for a site.
func containerName(siteID string) string {
	return "site-" + siteID
}

// Docker runs a Docker CLI command and returns its combined output.
func Docker(args ...string) (string, error) {
	cmd := exec.Command("docker", args...)
	out, err := cmd.CombinedOutput()
	output := strings.TrimSpace(string(out))
	if err != nil {
		return output, fmt.Errorf("docker %s: %s (%w)", args[0], output, err)
	}
	return output, nil
}

// containerExists returns true if a container with the given name exists (running or stopped).
func containerExists(name string) bool {
	_, err := Docker("inspect", name)
	return err == nil
}

// DataSize returns the total bytes used by a site's /data directory
// by running du inside the site's container. Returns 0 on any error.
func DataSize(siteID string) int64 {
	out, err := Docker("exec", containerName(siteID), "du", "-sb", "/data")
	if err != nil {
		return 0
	}
	// du -sb outputs: "12345\t/data"
	parts := strings.Fields(out)
	if len(parts) == 0 {
		return 0
	}
	n, _ := strconv.ParseInt(parts[0], 10, 64)
	return n
}
← Back