Files
Kelx/docker_engine.go
2026-11-30 16:32:37 +00:00

1491 lines
46 KiB
Go

package main
import (
"bufio"
"bytes"
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"sort"
"strconv"
"strings"
"sync"
"time"
)
const (
dockerEngineSocketPath = "/var/run/docker.sock"
dockerEngineAPIVersion = "v1.41"
// dockerServerOwnershipLabel marks containers created by this panel and
// records which server they belong to.
dockerServerOwnershipLabel = "adpanel.server"
)
var (
dockerEngineHTTPClient *http.Client
dockerEngineHTTPClientOnce sync.Once
)
type Docker struct {
debug bool
}
func runDockerCLI(ctx context.Context, stdout, stderr io.Writer, args ...string) (int, error) {
cmd := exec.CommandContext(ctx, "docker", rewriteDockerCLIArgs(args)...)
cmd.Stdout, cmd.Stderr = stdout, stderr
err := cmd.Run()
return exitCodeFromErr(err), err
}
func (d Docker) runCollect(ctx context.Context, args ...string) (string, string, int, error) {
var stdout, stderr bytes.Buffer
exitCode, err := runDockerCLI(ctx, &stdout, &stderr, args...)
return stdout.String(), stderr.String(), exitCode, err
}
func collectDockerLogTail(ctx context.Context, name string, tail int, timestamps bool) (string, string) {
args := []string{"logs", "--tail", strconv.Itoa(tail), name}
if timestamps {
args = append([]string{"logs", "--timestamps"}, args[1:]...)
}
stdout := newBoundedLogWriter(consolePersistMaxBytes / 2)
stderr := newBoundedLogWriter(consolePersistMaxBytes / 2)
_, _ = runDockerCLI(ctx, stdout, stderr, args...)
completeLines := func(output *boundedLogWriter) string {
text := output.String()
if output.truncated {
_, text, _ = strings.Cut(text, "\n")
}
return text
}
return completeLines(stdout), completeLines(stderr)
}
// adpanel:installer-resource-limits - staging must not bypass the server's CPU or memory budget.
func appendInstallerResourceArgs(args []string, resources *resourceLimits, boundedScratch bool) []string {
config := buildStructuredHostConfig(nil, nil, resources, "", false)
if boundedScratch {
if config.Memory <= 0 {
config.Memory = 1 << 30
}
config.MemorySwap = config.Memory
}
args = append(args, "--pids-limit="+strconv.FormatInt(min(config.PidsLimit, defaultPidsLimit), 10))
if config.Memory > 0 {
args = append(args, "--memory="+strconv.FormatInt(config.Memory, 10), "--memory-swap="+strconv.FormatInt(config.MemorySwap, 10))
}
if config.CpuQuota > 0 && config.CpuPeriod > 0 {
args = append(args, "--cpu-period="+strconv.FormatInt(config.CpuPeriod, 10), "--cpu-quota="+strconv.FormatInt(config.CpuQuota, 10))
}
return args
}
type dockerEngineError struct {
Message string `json:"message"`
}
type dockerPortBinding struct {
HostIP string `json:"HostIp,omitempty"`
HostPort string `json:"HostPort,omitempty"`
}
type dockerRestartPolicy struct {
Name string `json:"Name,omitempty"`
MaximumRetryCount int `json:"MaximumRetryCount,omitempty"`
}
type dockerUlimit struct {
Name string `json:"Name"`
Soft int64 `json:"Soft"`
Hard int64 `json:"Hard"`
}
type dockerLogConfig struct {
Type string `json:"Type,omitempty"`
Config map[string]string `json:"Config,omitempty"`
}
type dockerHostConfig struct {
Binds []string `json:"Binds,omitempty"`
PortBindings map[string][]dockerPortBinding `json:"PortBindings,omitempty"`
RestartPolicy dockerRestartPolicy `json:"RestartPolicy,omitempty"`
CapAdd []string `json:"CapAdd,omitempty"`
CapDrop []string `json:"CapDrop,omitempty"`
SecurityOpt []string `json:"SecurityOpt,omitempty"`
PidsLimit int64 `json:"PidsLimit,omitempty"`
ReadonlyRootfs bool `json:"ReadonlyRootfs,omitempty"`
Tmpfs map[string]string `json:"Tmpfs,omitempty"`
Memory int64 `json:"Memory,omitempty"`
MemoryReservation int64 `json:"MemoryReservation,omitempty"`
MemorySwap int64 `json:"MemorySwap,omitempty"`
CpuShares int64 `json:"CpuShares,omitempty"`
CpuPeriod int64 `json:"CpuPeriod,omitempty"`
CpuQuota int64 `json:"CpuQuota,omitempty"`
BlkioWeight int64 `json:"BlkioWeight,omitempty"`
Ulimits []dockerUlimit `json:"Ulimits,omitempty"`
LogConfig *dockerLogConfig `json:"LogConfig,omitempty"`
NetworkMode string `json:"NetworkMode,omitempty"`
}
type dockerContainerCreateRequest struct {
Image string `json:"Image"`
Env []string `json:"Env,omitempty"`
Cmd []string `json:"Cmd,omitempty"`
Entrypoint []string `json:"Entrypoint,omitempty"`
WorkingDir string `json:"WorkingDir,omitempty"`
User string `json:"User,omitempty"`
Tty bool `json:"Tty,omitempty"`
OpenStdin bool `json:"OpenStdin,omitempty"`
AttachStdin bool `json:"AttachStdin,omitempty"`
AttachStdout bool `json:"AttachStdout,omitempty"`
AttachStderr bool `json:"AttachStderr,omitempty"`
StdinOnce bool `json:"StdinOnce,omitempty"`
ExposedPorts map[string]struct{} `json:"ExposedPorts,omitempty"`
HostConfig dockerHostConfig `json:"HostConfig,omitempty"`
Labels map[string]string `json:"Labels,omitempty"`
}
type dockerContainerCreateResponse struct {
ID string `json:"Id"`
}
func validDockerContainerID(value string) bool {
_, err := hex.DecodeString(value)
return len(value) == 64 && err == nil
}
type dockerContainerInspectResponse struct {
HostConfig dockerHostConfig `json:"HostConfig"`
Config dockerContainerConfigLabels `json:"Config"`
Labels map[string]string `json:"Labels"`
State dockerContainerStateForStats `json:"State"`
}
type dockerContainerMount struct {
Type string `json:"Type"`
Source string `json:"Source"`
}
// dockerContainerConfigLabels mirrors the part of a container inspect
// "Config" object the ownership check needs. The Docker Engine API reports
// container labels under Config.Labels.
type dockerContainerConfigLabels struct {
Labels map[string]string `json:"Labels"`
}
// dockerServerLabel returns the value of the panel ownership label from a
// container inspect payload. The top-level Labels field is accepted in
// addition to Config.Labels.
func dockerServerLabel(topLevel map[string]string, config dockerContainerConfigLabels) (string, bool) {
if v, ok := topLevel[dockerServerOwnershipLabel]; ok && v != "" {
return v, true
}
v, ok := config.Labels[dockerServerOwnershipLabel]
return v, ok && v != ""
}
type dockerPullProgress struct {
Status string `json:"status"`
Error string `json:"error"`
}
type dockerAttachOptions struct {
Stdin bool
Stdout bool
Stderr bool
Logs bool
}
type dockerHijackedConn struct {
net.Conn
reader *bufio.Reader
}
func (c *dockerHijackedConn) Read(p []byte) (int, error) {
return c.reader.Read(p)
}
type dockerImageInspectConfig struct {
Entrypoint []string `json:"Entrypoint"`
Cmd []string `json:"Cmd"`
WorkingDir string `json:"WorkingDir"`
Env []string `json:"Env"`
User string `json:"User"`
Volumes map[string]any `json:"Volumes"`
Labels map[string]string `json:"Labels"`
}
type dockerImageInspectResponse struct {
ID string `json:"Id"`
Config dockerImageInspectConfig `json:"Config"`
}
func sanitizeStringList(values []string) []string {
out := make([]string, 0, len(values))
for _, value := range values {
clean := strings.TrimSpace(value)
if clean != "" {
out = append(out, clean)
}
}
return out
}
func (d Docker) inspectImageConfigAPI(ctx context.Context, ref string) (imageConfig, error) {
imageRef := strings.TrimSpace(ref)
if imageRef == "" {
return imageConfig{}, fmt.Errorf("missing image reference")
}
body, status, err := d.engineRequest(ctx, http.MethodGet, "/images/"+url.PathEscape(imageRef)+"/json", nil, nil)
if err != nil {
return imageConfig{}, err
}
if status < 200 || status >= 300 {
return imageConfig{}, fmt.Errorf("failed to inspect image %s: %s", imageRef, decodeDockerAPIError(body))
}
var payload dockerImageInspectResponse
if err := json.Unmarshal(body, &payload); err != nil {
return imageConfig{}, err
}
cfg := imageConfig{ID: payload.ID, Env: map[string]string{}}
cfg.Entrypoint = sanitizeStringList(payload.Config.Entrypoint)
cfg.Cmd = sanitizeStringList(payload.Config.Cmd)
cfg.Workdir = strings.TrimSpace(payload.Config.WorkingDir)
cfg.User = strings.TrimSpace(payload.Config.User)
if len(payload.Config.Volumes) > 0 {
cfg.Volumes = make([]string, 0, len(payload.Config.Volumes))
for volumePath := range payload.Config.Volumes {
clean := strings.TrimSpace(volumePath)
if clean == "/" {
cfg.DeclaresRootVolume = true
} else if clean != "" {
cfg.Volumes = append(cfg.Volumes, clean)
}
}
sort.Strings(cfg.Volumes)
}
for _, kv := range sanitizeStringList(payload.Config.Env) {
if k, v, ok := strings.Cut(kv, "="); ok {
cfg.Env[strings.TrimSpace(k)] = v
}
}
if len(payload.Config.Labels) > 0 {
cfg.Labels = make(map[string]string, len(payload.Config.Labels))
for k, v := range payload.Config.Labels {
k = strings.TrimSpace(k)
if k != "" {
cfg.Labels[k] = v
}
}
}
return cfg, nil
}
func dockerEngineClient() *http.Client {
dockerEngineHTTPClientOnce.Do(func() {
transport := &http.Transport{
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
var dialer net.Dialer
return dialer.DialContext(ctx, "unix", dockerEngineSocketPath)
},
DisableCompression: true,
}
dockerEngineHTTPClient = &http.Client{
Transport: transport,
Timeout: 0,
}
})
return dockerEngineHTTPClient
}
func dockerAPIPath(rawPath string, query url.Values) string {
path := "/" + dockerEngineAPIVersion + rawPath
if query == nil || len(query) == 0 {
return path
}
return path + "?" + query.Encode()
}
func decodeDockerAPIError(body []byte) string {
trimmed := strings.TrimSpace(string(body))
if trimmed == "" {
return "docker engine request failed"
}
var payload dockerEngineError
if err := json.Unmarshal(body, &payload); err == nil && strings.TrimSpace(payload.Message) != "" {
return strings.TrimSpace(payload.Message)
}
return trimmed
}
func (d Docker) engineRequest(ctx context.Context, method, rawPath string, query url.Values, body any) ([]byte, int, error) {
var reader io.Reader
if body != nil {
payload, err := json.Marshal(body)
if err != nil {
return nil, 0, err
}
reader = bytes.NewReader(payload)
}
req, err := http.NewRequestWithContext(ctx, method, "http://docker"+dockerAPIPath(rawPath, query), reader)
if err != nil {
return nil, 0, err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := dockerEngineClient().Do(req)
if err != nil {
return nil, 0, err
}
defer resp.Body.Close()
respBody, readErr := io.ReadAll(resp.Body)
if readErr != nil {
return nil, resp.StatusCode, readErr
}
return respBody, resp.StatusCode, nil
}
func (d Docker) attachContainerAPI(ctx context.Context, name string, opts dockerAttachOptions) (io.ReadWriteCloser, error) {
dockerName := dockerContainerName(name)
if dockerName == "" {
return nil, fmt.Errorf("missing container name")
}
if !opts.Stdin && !opts.Stdout && !opts.Stderr {
return nil, fmt.Errorf("no attach streams requested")
}
var dialer net.Dialer
conn, err := dialer.DialContext(ctx, "unix", dockerEngineSocketPath)
if err != nil {
return nil, err
}
_ = conn.SetDeadline(time.Now().Add(10 * time.Second))
query := url.Values{}
query.Set("stream", "1")
if opts.Stdin {
query.Set("stdin", "1")
}
if opts.Stdout {
query.Set("stdout", "1")
}
if opts.Stderr {
query.Set("stderr", "1")
}
if opts.Logs {
query.Set("logs", "1")
}
req, err := http.NewRequestWithContext(
ctx,
http.MethodPost,
"http://docker"+dockerAPIPath("/containers/"+url.PathEscape(dockerName)+"/attach", query),
nil,
)
if err != nil {
_ = conn.Close()
return nil, err
}
req.Header.Set("Connection", "Upgrade")
req.Header.Set("Upgrade", "tcp")
if err := req.Write(conn); err != nil {
_ = conn.Close()
return nil, err
}
reader := bufio.NewReader(conn)
resp, err := http.ReadResponse(reader, req)
if err != nil {
_ = conn.Close()
return nil, err
}
if resp.StatusCode != http.StatusSwitchingProtocols && resp.StatusCode != http.StatusOK {
detail := ""
if resp.Body != nil {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
_ = resp.Body.Close()
detail = decodeDockerAPIError(body)
}
_ = conn.Close()
if detail == "" {
detail = resp.Status
}
return nil, fmt.Errorf("failed to attach container %s: %s", dockerName, detail)
}
_ = conn.SetDeadline(time.Time{})
return &dockerHijackedConn{Conn: conn, reader: reader}, nil
}
func splitDockerImageRef(ref string) (string, string) {
clean := strings.TrimSpace(ref)
if clean == "" {
return "", ""
}
if at := strings.Index(clean, "@"); at > 0 {
return clean, ""
}
lastSlash := strings.LastIndex(clean, "/")
lastColon := strings.LastIndex(clean, ":")
if lastColon > lastSlash {
return clean[:lastColon], clean[lastColon+1:]
}
return clean, "latest"
}
func (d Docker) pullImageAPI(ctx context.Context, ref string) error {
var lastErr error
for attempt := 1; attempt <= 3; attempt++ {
err := d.pullImageAPIOnce(ctx, ref)
if err == nil {
return nil
}
lastErr = err
if ctx.Err() != nil || !isTransientDockerPullError(err) || attempt == 3 {
break
}
delay := time.Duration(attempt*attempt) * time.Second
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
}
return lastErr
}
func (d Docker) ensureImageAvailableAPI(ctx context.Context, ref string, onStatus ...func(string)) error {
imageRef := strings.TrimSpace(ref)
if imageRef == "" {
return fmt.Errorf("missing image reference")
}
report := func(msg string) {
for _, fn := range onStatus {
if fn != nil {
fn(msg)
}
}
}
if d.imageExistsLocally(ctx, imageRef) {
report(fmt.Sprintf("Verified runtime container image: %s", imageRef))
return nil
}
report(fmt.Sprintf("Fetching container image %s, please wait...", imageRef))
if err := d.pullImageAPI(ctx, imageRef); err != nil {
if isTransientDockerPullError(err) && d.imageExistsLocally(ctx, imageRef) {
report(fmt.Sprintf("Successfully prepared container image %s (cached)", imageRef))
return nil
}
return err
}
report(fmt.Sprintf("Successfully prepared container image %s", imageRef))
return nil
}
func (d Docker) pullImageAPIOnce(ctx context.Context, ref string) error {
image, tag := splitDockerImageRef(ref)
if image == "" {
return fmt.Errorf("missing image reference")
}
query := url.Values{}
query.Set("fromImage", image)
if tag != "" {
query.Set("tag", tag)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://docker"+dockerAPIPath("/images/create", query), nil)
if err != nil {
return err
}
resp, err := dockerEngineClient().Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed to pull image %s: %s", ref, decodeDockerAPIError(body))
}
dec := json.NewDecoder(resp.Body)
for {
var item dockerPullProgress
if err := dec.Decode(&item); err != nil {
if err == io.EOF {
break
}
return err
}
if strings.TrimSpace(item.Error) != "" {
return fmt.Errorf("failed to pull image %s: %s", ref, strings.TrimSpace(item.Error))
}
}
return nil
}
func isTransientDockerPullError(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
nonTransient := []string{
"manifest unknown",
"not found",
"pull access denied",
"repository does not exist",
"requested access to the resource is denied",
"unauthorized",
"authentication required",
"invalid reference format",
}
for _, marker := range nonTransient {
if strings.Contains(msg, marker) {
return false
}
}
transient := []string{
"tls: bad record mac",
"unexpected eof",
"connection reset",
"connection refused",
"connection timed out",
"i/o timeout",
"net/http",
"httpreadseeker",
"failed to copy",
"failed to do request",
"tls handshake timeout",
"temporary failure",
"503",
"502",
"504",
"too many requests",
}
for _, marker := range transient {
if strings.Contains(msg, marker) {
return true
}
}
return false
}
func (d Docker) extractImageFiles(ctx context.Context, imageRef, destDir, extractPath string, stagingBudget ...int64) error {
extractPath = strings.TrimSuffix(extractPath, "/")
if extractPath == "" {
extractPath = "/"
}
tempName := "adpanel-extract-" + fmt.Sprintf("%d", time.Now().UnixNano())
_, errStr, code, err := d.runCollect(ctx, "create", "--name", tempName, imageRef, "true")
if err != nil || code != 0 {
return fmt.Errorf("failed to create temp container: %s", strings.TrimSpace(errStr))
}
defer func() {
cleanupCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
d.rmForce(cleanupCtx, tempName)
}()
srcPath := tempName + ":" + extractPath
if extractPath != "/" {
srcPath += "/."
}
if len(stagingBudget) != 0 {
return extractStagedImageFiles(ctx, srcPath, destDir, stagingBudget[0])
}
_, errStr, code, err = d.runCollect(ctx, "cp", srcPath, destDir+"/")
if err != nil || code != 0 {
_, errStr, code, err = d.runCollect(ctx, "cp", tempName+":"+extractPath, destDir+"/")
if err != nil || code != 0 {
return fmt.Errorf("failed to copy files from container: %s", strings.TrimSpace(errStr))
}
}
if d.debug {
fmt.Printf("[docker] extracted files from %s:%s to %s\n", imageRef, extractPath, destDir)
}
return nil
}
func (d Docker) removeContainerAPI(ctx context.Context, name string, force bool) error {
dockerName := dockerContainerName(name)
if dockerName == "" {
return fmt.Errorf("missing container name")
}
query := url.Values{}
query.Set("v", "1")
if force {
query.Set("force", "1")
}
body, status, err := d.engineRequest(ctx, http.MethodDelete, "/containers/"+url.PathEscape(dockerName), query, nil)
if err != nil {
return err
}
if status == http.StatusNotFound {
return nil
}
if status < 200 || status >= 300 {
return fmt.Errorf("failed to remove container %s: %s", dockerName, decodeDockerAPIError(body))
}
return nil
}
func (d Docker) killContainerAPI(ctx context.Context, name string) error {
dockerName := dockerContainerName(name)
if dockerName == "" {
return fmt.Errorf("missing container name")
}
query := url.Values{}
query.Set("signal", "SIGKILL")
body, status, err := d.engineRequest(ctx, http.MethodPost, "/containers/"+url.PathEscape(dockerName)+"/kill", query, nil)
if err != nil {
return err
}
if status == http.StatusNotFound {
return nil
}
if status == http.StatusConflict {
msg := strings.ToLower(decodeDockerAPIError(body))
if strings.Contains(msg, "not running") || strings.Contains(msg, "is not running") {
return nil
}
}
if status < 200 || status >= 300 {
return fmt.Errorf("failed to kill container %s: %s", dockerName, decodeDockerAPIError(body))
}
return nil
}
func (d Docker) updateRestartNoAPI(ctx context.Context, name string) error {
dockerName := dockerContainerName(name)
if dockerName == "" {
return fmt.Errorf("missing container name")
}
req := dockerHostConfig{RestartPolicy: dockerRestartPolicy{Name: "no"}}
body, status, err := d.engineRequest(ctx, http.MethodPost, "/containers/"+url.PathEscape(dockerName)+"/update", nil, req)
if err != nil {
return err
}
if status == http.StatusNotFound {
return nil
}
if status < 200 || status >= 300 {
return fmt.Errorf("failed to disable restart policy for %s: %s", dockerName, decodeDockerAPIError(body))
}
return nil
}
func (d Docker) containerExistsAPI(ctx context.Context, name string) (bool, error) {
dockerName := dockerContainerName(name)
if dockerName == "" {
return false, fmt.Errorf("missing container name")
}
body, status, err := d.engineRequest(ctx, http.MethodGet, "/containers/"+url.PathEscape(dockerName)+"/json", nil, nil)
if err != nil {
return false, err
}
if status == http.StatusNotFound {
return false, nil
}
if status < 200 || status >= 300 {
return false, fmt.Errorf("failed to inspect container %s: %s", dockerName, decodeDockerAPIError(body))
}
return true, nil
}
func (d Docker) createContainerAPI(ctx context.Context, name string, req dockerContainerCreateRequest) (string, error) {
query := url.Values{}
query.Set("name", name)
body, status, err := d.engineRequest(ctx, http.MethodPost, "/containers/create", query, req)
if err != nil {
return "", err
}
if status < 200 || status >= 300 {
return "", fmt.Errorf("failed to create container %s: %s", name, decodeDockerAPIError(body))
}
var created dockerContainerCreateResponse
if err := json.Unmarshal(body, &created); err != nil {
return "", err
}
if !validDockerContainerID(created.ID) {
return "", fmt.Errorf("docker engine did not return a valid container id")
}
return created.ID, nil
}
func (d Docker) inspectContainerAPI(ctx context.Context, name string) (dockerContainerInspectResponse, error) {
body, status, err := d.engineRequest(ctx, http.MethodGet, "/containers/"+url.PathEscape(name)+"/json", nil, nil)
if err != nil {
return dockerContainerInspectResponse{}, err
}
if status < 200 || status >= 300 {
return dockerContainerInspectResponse{}, fmt.Errorf("failed to inspect container %s: %s", name, decodeDockerAPIError(body))
}
var payload dockerContainerInspectResponse
if err := json.Unmarshal(body, &payload); err != nil {
return dockerContainerInspectResponse{}, err
}
return payload, nil
}
// containerHasServerLabel reports whether the given container carries the
// panel ownership label for the requested server name. Probe errors count as
// "no label" so an inconclusive check never enables a name fallback.
func (d Docker) containerHasServerLabel(ctx context.Context, dockerName, serverName string) bool {
payload, err := d.inspectContainerAPI(ctx, dockerName)
if err != nil {
return false
}
label, ok := dockerServerLabel(payload.Labels, payload.Config)
return ok && label == serverName
}
func (d Docker) startContainerAPI(ctx context.Context, name string) error {
body, status, err := d.engineRequest(ctx, http.MethodPost, "/containers/"+url.PathEscape(name)+"/start", nil, nil)
if err != nil {
return err
}
if status < 200 || status >= 300 {
return fmt.Errorf("failed to start container %s: %s", name, decodeDockerAPIError(body))
}
return nil
}
type dockerNetworkCreateRequest struct {
Name string `json:"Name"`
CheckDuplicate bool `json:"CheckDuplicate"`
Driver string `json:"Driver"`
Attachable bool `json:"Attachable"`
Options map[string]string `json:"Options,omitempty"`
}
func (d Docker) ensureNetworkExistsAPI(ctx context.Context, name string) error {
networkName := strings.TrimSpace(name)
if networkName == "" || networkName == "bridge" || networkName == "host" || networkName == "none" {
return nil
}
_, status, err := d.engineRequest(ctx, http.MethodGet, "/networks/"+url.PathEscape(networkName), nil, nil)
if err == nil && status == http.StatusOK {
return nil
}
req := dockerNetworkCreateRequest{
Name: networkName,
CheckDuplicate: true,
Driver: "bridge",
Attachable: true,
Options: map[string]string{
"com.docker.network.bridge.enable_icc": "true",
},
}
createBody, createStatus, createErr := d.engineRequest(ctx, http.MethodPost, "/networks/create", nil, req)
if createErr != nil {
return createErr
}
if createStatus >= 200 && createStatus < 300 {
return nil
}
errMsg := decodeDockerAPIError(createBody)
if strings.Contains(strings.ToLower(errMsg), "already exists") {
return nil
}
return fmt.Errorf("failed to create network %s: %s", networkName, errMsg)
}
func (d Docker) runContainerAPI(ctx context.Context, name string, req dockerContainerCreateRequest, replaceExisting bool, onStatus ...func(string)) (string, error) {
if replaceExisting {
removeCtx, removeCancel := context.WithTimeout(ctx, 15*time.Second)
_ = d.removeContainerAPI(removeCtx, name, true)
removeCancel()
}
if req.HostConfig.NetworkMode != "" && req.HostConfig.NetworkMode != "bridge" && req.HostConfig.NetworkMode != "host" && req.HostConfig.NetworkMode != "none" {
netCtx, netCancel := context.WithTimeout(ctx, 10*time.Second)
if netErr := d.ensureNetworkExistsAPI(netCtx, req.HostConfig.NetworkMode); netErr != nil {
fmt.Printf("[docker] warning: failed to ensure network %s (%v); falling back to bridge\n", req.HostConfig.NetworkMode, netErr)
req.HostConfig.NetworkMode = "bridge"
}
netCancel()
}
if reinstall, ok := ctx.Value(reinstallContainerContextKey{}).(*reinstallFileHandoff); ok && reinstall.image.config.ID != "" {
req.Image = reinstall.image.config.ID
} else {
pullCtx, pullCancel := context.WithTimeout(ctx, 10*time.Minute)
err := d.ensureImageAvailableAPI(pullCtx, req.Image, onStatus...)
pullCancel()
if err != nil {
return "", err
}
}
containerID, err := d.createContainerAPI(ctx, name, req)
if err != nil {
return "", err
}
return containerID, d.startContainerAPI(ctx, containerID)
}
const (
powerOpAcquirePollStep = 25 * time.Millisecond
powerOpRequestEnded = "power_request_ended"
serverStopInProgress = "server_stop_in_progress"
)
var powerOpAcquireWaitBudget = 15 * time.Second
var errServerStopInProgress = errors.New("server is stopping")
// adpanel:power-admission-cancel - wait briefly behind short holders, refuse
// long operations as soon as they register, and never admit an expired request.
func (a *Agent) acquireServerOpLockFailFast(ctx context.Context, name string) (*sync.RWMutex, string) {
deadline := time.Now().Add(powerOpAcquireWaitBudget)
poll := time.NewTicker(powerOpAcquirePollStep)
defer poll.Stop()
for {
if ctx.Err() != nil {
return nil, powerOpRequestEnded
}
if code, _, _, long := a.longOpConflict(name); long {
return nil, code
}
if mu := a.tryLockServerOp(name); mu != nil {
if ctx.Err() != nil {
mu.Unlock()
return nil, powerOpRequestEnded
}
return mu, ""
}
if !time.Now().Before(deadline) {
return nil, "server_op_in_progress"
}
select {
case <-ctx.Done():
return nil, powerOpRequestEnded
case <-poll.C:
}
}
}
func writePowerOpRefusal(w http.ResponseWriter, code string) {
status := http.StatusConflict
if code == powerOpRequestEnded {
status = http.StatusRequestTimeout
}
jsonWrite(w, status, serverOpConflictBody(code))
}
func (a *Agent) handleStart(w http.ResponseWriter, r *http.Request, name string) {
if !isValidContainerName(name) {
jsonWrite(w, 400, map[string]any{"error": "invalid container name"})
return
}
var body struct {
HostPort int `json:"hostPort"`
Env map[string]string `json:"env"`
}
if err := readJSON(w, r, a.uploadLimit, &body); err != nil && !errors.Is(err, io.EOF) {
jsonWrite(w, 400, map[string]any{"error": "invalid request body"})
return
}
if body.HostPort != 0 {
if _, ok := parseStrictPortValue(body.HostPort); !ok {
jsonWrite(w, 400, map[string]any{"error": "invalid hostPort"})
return
}
}
typ, err := a.performServerStart(r.Context(), name, body.HostPort, body.Env)
if err != nil {
if errors.Is(err, errPowerOpRequestEnded) {
writePowerOpRefusal(w, powerOpRequestEnded)
return
}
if errors.Is(err, errServerStartNotFound) {
jsonWrite(w, http.StatusNotFound, map[string]any{"error": "not found"})
return
}
if errors.Is(err, errServerAlreadyRunning) {
jsonWrite(w, http.StatusConflict, map[string]any{"ok": false, "error": "server_already_running", "code": "server_already_running", "detail": "The server is already running."})
return
}
if errors.Is(err, errServerStartStateUnknown) {
jsonWrite(w, http.StatusServiceUnavailable, map[string]any{"ok": false, "error": "server_state_unconfirmed", "detail": err.Error()})
return
}
if errors.Is(err, errNetworkQuotaExceeded) {
writeServerNetworkQuotaExceeded(w)
return
}
if errors.Is(err, errTransferExportInProgress) {
status, body := fileMutationAdmissionFailure(err)
jsonWrite(w, status, body)
return
}
if errors.Is(err, errMinecraftEulaRequired) {
jsonWrite(w, 409, map[string]any{
"ok": false,
"error": "minecraft_eula_required",
"code": "minecraft_eula_required",
"detail": "The Minecraft EULA (eula.txt) must be accepted before this server can start.",
})
return
}
if errors.Is(err, errBackupOpInProgress) {
writePowerOpRefusal(w, "backup_in_progress")
return
}
if errors.Is(err, errReinstallOpInProgress) {
writePowerOpRefusal(w, "reinstall_in_progress")
return
}
if errors.Is(err, errReinstallStartupPending) {
writeReinstallStartupPending(w)
return
}
if errors.Is(err, errServerStopInProgress) {
writePowerOpRefusal(w, serverStopInProgress)
return
}
if errors.Is(err, errRuntimeSeedOpInProgress) {
writePowerOpRefusal(w, "runtime_seed_in_progress")
return
}
if errors.Is(err, errServerOpInProgress) {
writePowerOpRefusal(w, "server_op_in_progress")
return
}
jsonWrite(w, 500, map[string]any{"error": "failed to start container", "detail": err.Error()})
return
}
auditLog.Log("server_start", getClientIP(r), "", name, "start", "success", map[string]any{"type": typ})
jsonWrite(w, 200, map[string]any{"ok": true})
}
func (a *Agent) prepareServerConsoleStart(name string) {
a.resetConsoleLogs(name)
a.broadcastDaemonLog(name, "Preparing server environment and configuration files...")
a.broadcastDaemonLog(name, "Verifying file permissions and filesystem integrity...")
if a.stdinMgr != nil {
a.stdinMgr.remove(name)
}
}
func (a *Agent) broadcastConsoleChunk(name, prefix, chunk string) bool {
cleaned := cleanLogLine(chunk)
if cleaned == "" {
return false
}
cleaned = strings.ReplaceAll(cleaned, "\r\n", "\n")
cleaned = strings.ReplaceAll(cleaned, "\r", "\n")
t := a.logs.getOrCreate(name)
sent := false
for _, line := range strings.Split(cleaned, "\n") {
line = strings.TrimRight(line, " \t")
plain := strings.TrimSpace(ansiSGRRE.ReplaceAllString(line, ""))
if plain == "" {
continue
}
a.logs.sendToClients(t, prefix+line)
sent = true
}
return sent
}
func isMissingExecShell(stderr string, execPath string, exitCode int) bool {
if exitCode != 126 && exitCode != 127 {
return false
}
diagnostic := strings.ToLower(strings.TrimSpace(stderr))
diagnostic = strings.TrimPrefix(diagnostic, "docker: ")
diagnostic = strings.TrimPrefix(diagnostic, "error response from daemon: ")
if !strings.HasPrefix(diagnostic, "oci runtime exec failed:") || strings.ContainsAny(diagnostic, "\r\n") {
return false
}
_, reason, found := strings.Cut(diagnostic, "exec: "+strconv.Quote(strings.ToLower(execPath))+": ")
return found && (strings.Contains(reason, "executable file not found") || strings.Contains(reason, "no such file or directory"))
}
// adpanel:console-exec-output - the shell deadline is not a memory budget;
// container-controlled output must not grow a daemon-side buffer unbounded.
const consoleExecOutputLimit = 128 * 1024
func (a *Agent) executeShellConsoleCommand(ctx context.Context, name, command string) (int, error) {
for _, shellPath := range []string{"sh", "/bin/sh", "bash", "/bin/bash"} {
stdout := newBoundedLogWriter(consoleExecOutputLimit)
stderr := newBoundedLogWriter(consoleExecOutputLimit)
exitCode, err := runDockerCLI(ctx, stdout, stderr, "exec", name, shellPath, "-lc", command)
stderrText := stderr.String()
if stdout.truncated || stderr.truncated {
a.broadcastConsoleChunk(name, "stderr:", "[command output truncated; showing the end of each stream]\n")
}
sawOutput := a.broadcastConsoleChunk(name, "stdout:", stdout.String())
sawOutput = a.broadcastConsoleChunk(name, "stderr:", stderrText) || sawOutput
if ctx.Err() != nil {
a.broadcastConsoleChunk(name, "stderr:", fmt.Sprintf("[command timed out] %s\n", command))
return exitCode, ctx.Err()
}
if err != nil && isMissingExecShell(stderrText, shellPath, exitCode) {
continue
}
if exitCode < 0 && err != nil {
return exitCode, err
}
if !sawOutput {
prefix := "stdout:"
if err != nil {
prefix = "stderr:"
}
a.broadcastConsoleChunk(name, prefix, fmt.Sprintf("[command exited with code %d]\n", exitCode))
}
return exitCode, nil
}
a.broadcastConsoleChunk(name, "stderr:", "[command failed] no supported shell found in container\n")
return -1, fmt.Errorf("no supported shell found in container")
}
func (a *Agent) handleCommand(w http.ResponseWriter, r *http.Request, name string) {
if !isValidContainerName(name) {
jsonWrite(w, 400, map[string]any{"error": "invalid container name"})
return
}
var body struct {
Command string `json:"command"`
RequestID string `json:"requestId"`
}
if err := readJSON(w, r, 16*1024, &body); err != nil {
jsonWrite(w, 400, map[string]any{"error": "bad json"})
return
}
cmd := strings.TrimSpace(body.Command)
if cmd == "" {
jsonWrite(w, 400, map[string]any{"error": "missing command"})
return
}
if len(cmd) > stdinCommandMaxLen {
jsonWrite(w, 400, map[string]any{"error": "command too long", "max": stdinCommandMaxLen})
return
}
requestID := sanitizeCommandRequestID(body.RequestID)
// adpanel:reinstall-console-admission - a name-addressed command must not
// resolve the container on one side of a rebuild and dispatch on the other.
opMu := a.getServerOpLock(name)
if !opMu.TryRLock() {
a.writeServerOpConflictResponse(w, name)
return
}
defer opMu.RUnlock()
serverDir := a.serverDir(name)
if st, err := os.Stat(serverDir); err != nil || !st.IsDir() {
jsonWrite(w, 404, map[string]any{"error": "not found"})
return
}
meta := a.loadMeta(serverDir)
if meta[reinstallPendingStartupKey] == true {
writeReinstallStartupPending(w)
return
}
if ok, reason := a.claimConsoleCommand(name, cmd, requestID); !ok {
jsonWrite(w, 200, map[string]any{"ok": true, "deduplicated": true, "reason": reason})
return
}
serverType := strings.ToLower(fmt.Sprint(meta["type"]))
consoleMode := inferredConsoleModeForServer(meta)
useExecShell := consoleMode == "exec" || consoleMode == "exec-shell" || consoleMode == "shell"
if a.logs != nil {
a.logs.suppressCommandEcho(name, cmd)
// Record the command as an in-order marker line in the same log stream
// as its output. This is the single source of truth for ordering so the
// panel never has to re-interleave commands and output from two clocks.
a.logs.recordCommandLine(name, cmd)
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if useExecShell {
exitCode, err := a.executeShellConsoleCommand(ctx, name, cmd)
if err != nil {
jsonWrite(w, 200, map[string]any{
"ok": false,
"error": "failed-to-send",
"detail": err.Error(),
"type": serverType,
"mode": "exec",
"exitCode": exitCode,
})
return
}
jsonWrite(w, 200, map[string]any{"ok": true, "type": serverType, "mode": "exec", "exitCode": exitCode})
return
}
targetProcesses := consoleProcessTargetsForServer(meta)
if err := a.docker.sendCommand(ctx, a.stdinMgr, name, cmd, targetProcesses); err != nil {
detail := err.Error()
jsonWrite(w, 200, map[string]any{
"ok": false,
"error": "failed-to-send",
"detail": detail,
"type": serverType,
"mode": "stdin",
})
return
}
jsonWrite(w, 200, map[string]any{"ok": true, "type": serverType, "mode": "stdin", "transport": "attached-stdin", "targeted": len(targetProcesses) > 0})
}
func (a *Agent) stopContainerBeforeStart(ctx context.Context, name string) {
if a.longOpKind(name) != longOpReinstall {
a.docker.rmForce(ctx, name)
}
}
// adpanel:stop-admission - use while holding the server operation lock so
// a new lifecycle operation cannot interrupt an accepted graceful shutdown.
func (a *Agent) serverStopPending(name string) bool {
a.stopMu.Lock()
defer a.stopMu.Unlock()
_, pending := a.stoppingNow[name]
return pending
}
func (a *Agent) clearPendingServerStop(name string) {
a.stopMu.Lock()
delete(a.stoppingNow, name)
a.stopMu.Unlock()
}
func (a *Agent) removeServerContainerWithRetry(ctx context.Context, name string) error {
container, _, exists, err := a.inspectContainerForStats(ctx, name)
if err != nil {
return err
}
if exists {
if !validDockerContainerID(container.ID) {
return fmt.Errorf("could not verify container identity")
}
if err := a.docker.brutalRemoveContainer(ctx, container.ID); err != nil {
go a.retryRemoveServerContainer(name, container.ID)
return err
}
}
a.clearPendingServerStop(name)
return nil
}
// adpanel:container-cleanup-identity - retry only against the original Docker
// ID; a name can be reused as soon as the owning operation releases its lock.
func (a *Agent) retryRemoveServerContainer(name, containerID string) {
for attempt := 1; attempt <= 30; attempt++ {
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
err := a.docker.brutalRemoveContainer(ctx, containerID)
cancel()
if err == nil {
return
}
fmt.Printf("[docker] container cleanup retry %d failed for %s: %v\n", attempt, name, err)
delay := time.Duration(attempt) * time.Second
if attempt <= 5 {
delay = time.Duration(attempt) * 250 * time.Millisecond
}
time.Sleep(delay)
}
fmt.Printf("[docker] container cleanup gave up for %s after repeated failures\n", name)
}
type dockerContainerStateForStats struct {
Status string `json:"Status"`
Running bool `json:"Running"`
StartedAt string `json:"StartedAt"`
Health struct {
Status string `json:"Status"`
} `json:"Health"`
}
type dockerContainerInspectForStats struct {
ID string `json:"Id"`
Name string `json:"Name"`
State dockerContainerStateForStats `json:"State"`
HostConfig dockerHostConfig `json:"HostConfig"`
Config dockerContainerConfigLabels `json:"Config"`
Labels map[string]string `json:"Labels"`
Mounts []dockerContainerMount `json:"Mounts"`
}
// adpanel:deferred-stop-identity - neither a replacement nor a later run of
// the same container inherits a previously requested or measured stop.
func sameDockerContainerRun(original, current dockerContainerInspectForStats) bool {
return validDockerContainerID(original.ID) && current.ID == original.ID && current.State.StartedAt == original.State.StartedAt
}
func volumeNeedsFileRecovery(serverDir string) bool {
entries, err := os.ReadDir(serverDir)
if err != nil {
return false
}
foundDirectory := false
for _, entry := range entries {
if entry.Name() == ".adpanel" || entry.Name() == ".adpanel_meta" {
continue
}
if !entry.IsDir() || foundDirectory {
return false
}
foundDirectory = true
}
return true
}
func (a *Agent) scheduleMisplacedFileRecovery(ctx context.Context, name, serverDir string) {
inspectCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
original, _, exists, err := a.inspectContainerForStats(inspectCtx, name)
if err != nil || !exists || !original.State.Running || !validDockerContainerID(original.ID) {
return
}
go func() {
for _, delay := range []time.Duration{15 * time.Second, 45 * time.Second} {
time.Sleep(delay)
if !volumeNeedsFileRecovery(serverDir) {
return
}
}
a.recoverMisplacedFiles(name, serverDir, original)
}()
}
// adpanel:reinstall-file-recovery - delayed Docker copies must not cross a
// container replacement or write into the new server tree during its handoff.
func (a *Agent) lockMisplacedFileRecovery(name, serverDir string, original dockerContainerInspectForStats) func() {
operation := a.tryLockServerOp(name)
if operation == nil {
return nil
}
if a.serverStopPending(name) || a.serverDir(name) != serverDir {
operation.Unlock()
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
releaseStorage, err := a.acquireFileMutationScope(ctx, a.fsScopeRootFor(name, serverDir))
if err != nil {
operation.Unlock()
return nil
}
release := func() {
releaseStorage()
operation.Unlock()
}
current, _, exists, err := a.inspectContainerForStats(ctx, name)
if err != nil || !exists || !current.State.Running || !sameDockerContainerRun(original, current) || !volumeNeedsFileRecovery(serverDir) {
release()
return nil
}
return release
}
func (a *Agent) finishServerStop(name, containerID string) error {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := a.docker.stop(ctx, containerID); err != nil {
fmt.Printf("[docker] Shutdown could not be confirmed for %s: %v\n", name, err)
a.broadcastDaemonLog(name, "Server process shutdown could not be confirmed. Check the server state before retrying.")
return err
}
if a.stdinMgr != nil {
a.stdinMgr.remove(name)
}
a.broadcastDaemonLog(name, "Server process shutdown completed successfully.")
a.broadcastContainerEvent(name, "stopped")
return nil
}
func (a *Agent) completeDeferredServerStop(name string, original dockerContainerInspectForStats, requestedAt time.Time) {
time.Sleep(a.stopGrace)
opMu := a.getServerOpLock(name)
opMu.Lock()
defer opMu.Unlock()
a.stopMu.Lock()
stillPending := a.stoppingNow[name].Equal(requestedAt)
a.stopMu.Unlock()
if !stillPending {
return
}
defer a.clearPendingServerStop(name)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
current, _, exists, err := a.inspectContainerForStats(ctx, name)
cancel()
if err != nil || !exists || !sameDockerContainerRun(original, current) {
return
}
_ = a.finishServerStop(name, original.ID)
}
type confirmDockerStartKey struct{}
func (a *Agent) verifyContainerHealthyAfterStart(ctx context.Context, name string) error {
requireConfirmation, _ := ctx.Value(confirmDockerStartKey{}).(bool)
probeCtx, cancel := context.WithTimeout(ctx, 4*time.Second)
defer cancel()
poll := time.NewTicker(500 * time.Millisecond)
defer poll.Stop()
var lastStatus string
for {
select {
case <-probeCtx.Done():
if err := ctx.Err(); err != nil {
return err
}
if !requireConfirmation {
return nil
}
if lastStatus == "" {
return errors.New("container startup status could not be confirmed")
}
return fmt.Errorf("container did not reach a running state after startup (status: %s)", lastStatus)
case <-poll.C:
}
statusOut, _, _, err := a.docker.runCollect(probeCtx, "inspect", "--format", "{{.State.Status}} {{.State.ExitCode}}", name)
statusParts := strings.Fields(statusOut)
if err != nil || len(statusParts) == 0 {
continue
}
lastStatus = statusParts[0]
switch lastStatus {
case "running":
return nil
case "restarting":
if requireConfirmation {
continue
}
logsOut := a.recentContainerLogs(ctx, name, 50)
fmt.Printf("[docker] container %s is restarting after startup; leaving restart policy active and not blocking start. Last logs:\n%s\n", name, logsOut)
return nil
case "exited", "dead":
exitStr := "0"
if len(statusParts) >= 2 {
exitStr = statusParts[1]
}
logsOut := a.recentContainerLogs(ctx, name, 50)
fmt.Printf("[docker] container exited after startup. Last logs:\n%s\n", logsOut)
logSummary := strings.TrimSpace(logsOut)
if len(logSummary) > 1800 {
logSummary = logSummary[len(logSummary)-1800:]
}
if logSummary != "" {
logSummary = "; last logs: " + logSummary
}
return fmt.Errorf("container exited immediately with code %s%s", exitStr, logSummary)
}
}
}
func (a *Agent) runStructuredContainerWithCompatUser(ctx context.Context, name string, req dockerContainerCreateRequest) error {
dockerName := dockerContainerName(name)
// adpanel:reinstall-startup-ownership - teardown already verified ownership;
// a newly occupied name belongs to Docker's create conflict handling.
replaceExisting := a.longOpKind(name) != longOpReinstall
req.Labels = map[string]string{dockerServerOwnershipLabel: name, "adpanel.managed": "true"}
if reinstall, ok := ctx.Value(reinstallContainerContextKey{}).(*reinstallFileHandoff); ok {
req.Labels[reinstallContainerLabel] = reinstall.containerLabel()
if err := validateReinstallImageVolumes(reinstall.image.config, req.HostConfig); err != nil {
return err
}
}
removeForRetry := func(containerID string) error {
if containerID == "" {
return nil
}
removeCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
return a.docker.removeContainerAPI(removeCtx, containerID, true)
}
launchRetry := func(containerID string, retryReq dockerContainerCreateRequest) error {
if err := removeForRetry(containerID); err != nil {
return err
}
if _, err := a.docker.runContainerAPI(ctx, dockerName, retryReq, false); err != nil {
return err
}
if err := a.verifyContainerHealthyAfterStart(ctx, name); err != nil {
return err
}
return a.verifyContainerResourceLimitsApplied(ctx, name, retryReq.HostConfig)
}
containerID, err := a.docker.runContainerAPI(ctx, dockerName, req, replaceExisting, func(message string) {
a.broadcastDaemonLog(name, message)
})
if err != nil {
// adpanel:reinstall-startup-command - a different process cannot confirm a destructive replacement.
if ctx.Value(confirmDockerStartKey{}) != true && replaceExisting && containerID != "" && len(req.Cmd) > 0 && isMissingRuntimeExecutableStartError(err) {
imgCfg := a.inspectRuntimeLaunchImage(ctx, req.Image)
if imageConfigHasRuntimeDefault(imgCfg) {
fmt.Printf("[docker] startup command failed for %s (%v); retrying with image default entrypoint/cmd\n", name, err)
req.Cmd = nil
req.Entrypoint = nil
if workdir := normalizeContainerWorkdir(imgCfg.Workdir); workdir != "" {
req.WorkingDir = workdir
}
return launchRetry(containerID, req)
}
}
return err
}
if err := a.verifyContainerHealthyAfterStart(ctx, name); err != nil {
forcedUser := strings.TrimSpace(req.User)
if !replaceExisting || forcedUser == "" {
return err
}
logCtx, logCancel := context.WithTimeout(context.Background(), 5*time.Second)
logsOut := a.recentContainerLogs(logCtx, name, 80)
logCancel()
if !isImmediateStartupPermissionIssue(logsOut) {
return err
}
fmt.Printf("[docker] startup failed under forced user %s for %s; retrying with image default user\n", forcedUser, name)
req.User = ""
return launchRetry(containerID, req)
}
return a.verifyContainerResourceLimitsApplied(ctx, name, req.HostConfig)
}