docker.go

161 lines
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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
package internal

import (
	"encoding/json"
	"fmt"
	"os/exec"
	"strings"
)

// ContainerInfo holds Docker container details.
type ContainerInfo struct {
	ID      string `json:"ID"`
	Name    string `json:"Names"`
	Image   string `json:"Image"`
	Status  string `json:"Status"`
	State   string `json:"State"`
	Ports   string `json:"Ports"`
	Created string `json:"CreatedAt"`
}

// RunOptions configures docker run.
type RunOptions struct {
	Network string
	Ports   map[int]int       // host:container
	Volumes map[string]string // host:container
	Env     map[string]string
	Restart string // "always", "unless-stopped"
	Detach  bool
	Command []string
}

// ListContainers returns all Docker containers.
func ListContainers() ([]*ContainerInfo, error) {
	out, err := exec.Command("docker", "ps", "-a", "--format", "{{json .}}").Output()
	if err != nil {
		return nil, fmt.Errorf("docker ps: %w", err)
	}

	var containers []*ContainerInfo
	for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
		if line == "" {
			continue
		}
		var c ContainerInfo
		if err := json.Unmarshal([]byte(line), &c); err != nil {
			continue
		}
		containers = append(containers, &c)
	}
	return containers, nil
}

// RunContainer starts a new Docker container.
func RunContainer(name, image string, opts RunOptions) error {
	args := []string{"run"}
	if opts.Detach {
		args = append(args, "-d")
	}
	args = append(args, "--name", name)

	if opts.Network != "" {
		args = append(args, "--network", opts.Network)
	}
	if opts.Restart != "" {
		args = append(args, "--restart", opts.Restart)
	}
	for host, container := range opts.Ports {
		args = append(args, "-p", fmt.Sprintf("%d:%d", host, container))
	}
	for host, container := range opts.Volumes {
		args = append(args, "-v", host+":"+container)
	}
	for k, v := range opts.Env {
		args = append(args, "-e", k+"="+v)
	}

	args = append(args, image)
	args = append(args, opts.Command...)

	cmd := exec.Command("docker", args...)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("docker run: %s: %w", strings.TrimSpace(string(out)), err)
	}
	return nil
}

// StopContainer stops a running container.
func StopContainer(name string) error {
	cmd := exec.Command("docker", "stop", name)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("docker stop: %s: %w", strings.TrimSpace(string(out)), err)
	}
	return nil
}

// StartContainer starts a stopped container.
func StartContainer(name string) error {
	cmd := exec.Command("docker", "start", name)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("docker start: %s: %w", strings.TrimSpace(string(out)), err)
	}
	return nil
}

// RemoveContainer removes a container.
func RemoveContainer(name string) error {
	cmd := exec.Command("docker", "rm", "-f", name)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("docker rm: %s: %w", strings.TrimSpace(string(out)), err)
	}
	return nil
}

// BuildImage builds a Docker image from a context path.
func BuildImage(contextPath, tag string) error {
	cmd := exec.Command("docker", "build", "-t", tag, contextPath)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("docker build: %s: %w", strings.TrimSpace(string(out)), err)
	}
	return nil
}

// ContainerLogs returns recent log output.
func ContainerLogs(name string, lines int) (string, error) {
	if lines <= 0 {
		lines = 50
	}
	cmd := exec.Command("docker", "logs", "--tail", fmt.Sprintf("%d", lines), name)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return "", fmt.Errorf("docker logs: %w", err)
	}
	return string(out), nil
}

// InspectContainer returns container details.
func InspectContainer(name string) (*ContainerInfo, error) {
	out, err := exec.Command("docker", "inspect", "--format", "{{json .}}", name).Output()
	if err != nil {
		return nil, fmt.Errorf("docker inspect: %w", err)
	}
	// Just return basic info
	return &ContainerInfo{
		Name:  name,
		State: strings.TrimSpace(string(out)),
	}, nil
}

// IsContainerRunning checks if a container is in running state.
func IsContainerRunning(name string) bool {
	out, err := exec.Command("docker", "inspect", "-f", "{{.State.Running}}", name).Output()
	if err != nil {
		return false
	}
	return strings.TrimSpace(string(out)) == "true"
}