docker

package
v0.6.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: Apache-2.0 Imports: 37 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package docker 实现 Docker 管理模块:查看容器、启停、日志,以及检查镜像更新并按原配置重建容器。

直接调用 Docker Engine API(默认 /var/run/docker.sock),不依赖官方 SDK。

Index

Constants

View Source
const ID = "docker"

ID 是模块标识。

View Source
const SelfUpgradeCommand = "docker-self-upgrade"

SelfUpgradeCommand 是辅助容器执行的子命令。

Variables

This section is empty.

Functions

func RunSelfUpgrade added in v0.6.3

func RunSelfUpgrade(args []string, stdout io.Writer) int

RunSelfUpgrade 是辅助容器的入口:按原配置重建 -container 指定的容器,失败时恢复旧容器。 镜像已由发起升级的 Gately 拉取,这里只负责重建。

Types

type APIError

type APIError struct {
	Status  int
	Message string
}

APIError 是 Docker 返回的错误。

func (*APIError) Error

func (e *APIError) Error() string

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client 是精简的 Docker Engine API 客户端。

func NewClient

func NewClient(host string) (*Client, error)

NewClient 按地址创建客户端:unix:///var/run/docker.sock 或 tcp://host:2375。

func (*Client) Action

func (c *Client) Action(ctx context.Context, id, action string) error

Action 执行 start/stop/restart/pause/unpause/kill。

func (*Client) ConnectNetwork

func (c *Client) ConnectNetwork(ctx context.Context, network, id string, endpoint map[string]any) error

ConnectNetwork 把容器连接到网络。

func (*Client) Containers

func (c *Client) Containers(ctx context.Context) ([]Container, error)

Containers 列出全部容器。

func (*Client) Create

func (c *Client) Create(ctx context.Context, name string, body any) (string, error)

Create 创建容器,返回新容器 ID。

func (*Client) FollowLogs added in v0.5.6

func (c *Client) FollowLogs(ctx context.Context, id string, onData func([]byte)) error

FollowLogs 持续读取容器从现在开始产生的日志,把标准输出与标准错误按块交给 onData,直到 ctx 取消或日志流结束。 非 TTY 容器的输出带 8 字节的多路复用头,这里按第一个块的格式判断并去掉。

func (*Client) ImageID

func (c *Client) ImageID(ctx context.Context, ref string) (string, error)

ImageID 返回本地镜像 ID;镜像不存在时返回空字符串。

func (*Client) Inspect

func (c *Client) Inspect(ctx context.Context, id string) (map[string]json.RawMessage, error)

Inspect 返回容器详情的原始 JSON,重建容器时需要完整保留未知字段。

func (*Client) Logs

func (c *Client) Logs(ctx context.Context, id string, tail int) (string, error)

Logs 返回容器最近的日志。非 TTY 容器的输出是带 8 字节头的多路复用流,这里解析为纯文本。

func (*Client) LogsWith added in v0.3.0

func (c *Client) LogsWith(ctx context.Context, id string, tail int, timestamps bool) (string, error)

LogsWith 与 Logs 相同,timestamps 控制是否带时间戳。

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping 检查 Docker 是否可用。

func (*Client) Pull

func (c *Client) Pull(ctx context.Context, ref string) error

Pull 拉取镜像。返回的进度流逐行解析,遇到错误消息时返回错误。

func (*Client) Remove

func (c *Client) Remove(ctx context.Context, id string) error

Remove 删除容器(保留数据卷)。

func (*Client) RemoveVolumes added in v0.3.0

func (c *Client) RemoveVolumes(ctx context.Context, id string, volumes bool) error

RemoveVolumes 强制删除容器,volumes 为 true 时同时删除匿名卷。

func (*Client) Rename

func (c *Client) Rename(ctx context.Context, id, name string) error

Rename 重命名容器。

type ComposeProjectView added in v0.3.0

type ComposeProjectView struct {
	Name        string           `json:"name"`
	WorkingDir  string           `json:"workingDir"`
	ConfigFiles []string         `json:"configFiles"`
	Status      string           `json:"status"`
	Total       int              `json:"total"`
	Running     int              `json:"running"`
	Services    []ComposeService `json:"services"`
	Managed     bool             `json:"managed"`
	Self        bool             `json:"self,omitempty"`
}

ComposeProjectView 是 Compose 项目列表项。

type ComposeService added in v0.3.0

type ComposeService struct {
	Name        string   `json:"name"`
	State       string   `json:"state"`
	ContainerID string   `json:"containerId"`
	Image       string   `json:"image"`
	Ports       []string `json:"ports"`
}

ComposeService 是项目中的一个服务容器。

type Container

type Container struct {
	ID      string            `json:"Id"`
	Names   []string          `json:"Names"`
	Image   string            `json:"Image"`
	ImageID string            `json:"ImageID"`
	State   string            `json:"State"`
	Status  string            `json:"Status"`
	Created int64             `json:"Created"`
	Labels  map[string]string `json:"Labels"`
	Ports   []struct {
		IP          string `json:"IP"`
		PrivatePort int    `json:"PrivatePort"`
		PublicPort  int    `json:"PublicPort"`
		Type        string `json:"Type"`
	} `json:"Ports"`
	Mounts []struct {
		Type string `json:"Type"`
	} `json:"Mounts"`
	NetworkSettings struct {
		Networks map[string]json.RawMessage `json:"Networks"`
	} `json:"NetworkSettings"`
}

Container 是容器列表项。

func (Container) Name

func (c Container) Name() string

Name 返回不带斜杠的容器名。

type ContainerDetail added in v0.3.0

type ContainerDetail struct {
	ContainerSpec
	ID             string          `json:"id"`
	State          string          `json:"state"`
	Status         string          `json:"status"`
	Created        string          `json:"created"`
	Started        string          `json:"started"`
	ImageID        string          `json:"imageId"`
	Path           string          `json:"path"`
	Args           []string        `json:"args"`
	Mounts         []DetailMount   `json:"mounts"`
	NetworkDetails []DetailNetwork `json:"networkDetails"`
	ExitCode       int             `json:"exitCode"`
	RestartCount   int             `json:"restartCount"`
	HealthStatus   string          `json:"healthStatus"`
	ComposeProject string          `json:"composeProject"`
	ComposeService string          `json:"composeService"`
}

ContainerDetail 是容器详情:ContainerSpec 的全部字段加运行时信息。

type ContainerSecrets added in v0.6.1

type ContainerSecrets struct {
	Env        []string `json:"env"`
	Command    string   `json:"command"`
	Entrypoint string   `json:"entrypoint"`
	Args       []string `json:"args"`
}

ContainerSecrets 是容器敏感字段的明文,字段与详情中的同名字段一一对应。

type ContainerSpec added in v0.3.0

type ContainerSpec struct {
	Name              string            `json:"name"`
	Image             string            `json:"image"`
	Pull              bool              `json:"pull"`
	AutoStart         bool              `json:"autoStart"`
	Command           string            `json:"command"`
	Entrypoint        string            `json:"entrypoint"`
	Env               []string          `json:"env"`
	Ports             []SpecPort        `json:"ports"`
	Volumes           []SpecVolume      `json:"volumes"`
	Network           string            `json:"network"`
	Networks          []string          `json:"networks"`
	IP                string            `json:"ip"`
	Aliases           []string          `json:"aliases"`
	Restart           string            `json:"restart"`
	RestartMaxRetries int               `json:"restartMaxRetries"`
	Privileged        bool              `json:"privileged"`
	CapAdd            []string          `json:"capAdd"`
	CapDrop           []string          `json:"capDrop"`
	Devices           []SpecDevice      `json:"devices"`
	User              string            `json:"user"`
	Workdir           string            `json:"workdir"`
	Hostname          string            `json:"hostname"`
	DNS               []string          `json:"dns"`
	Labels            map[string]string `json:"labels"`
	MemoryMB          int64             `json:"memoryMB"`
	CPUs              float64           `json:"cpus"`
	TTY               bool              `json:"tty"`
	StdinOpen         bool              `json:"stdinOpen"`
}

ContainerSpec 是创建与编辑容器使用的配置。

type ContainerView

type ContainerView struct {
	ID       string            `json:"id"`
	Name     string            `json:"name"`
	Image    string            `json:"image"`
	ImageID  string            `json:"imageId"`
	State    string            `json:"state"`
	Status   string            `json:"status"`
	Created  int64             `json:"created"`
	Started  string            `json:"started,omitempty"`
	Ports    []string          `json:"ports"`
	Networks []string          `json:"networks"`
	Mounts   int               `json:"mounts"`
	Project  string            `json:"project,omitempty"`
	Update   *UpdateInfo       `json:"update,omitempty"`
	Busy     bool              `json:"busy"`
	Self     bool              `json:"self,omitempty"`
	Labels   map[string]string `json:"-"`
}

ContainerView 是界面展示的容器信息。

type DetailMount added in v0.3.0

type DetailMount struct {
	Type        string `json:"type"`
	Name        string `json:"name"`
	Source      string `json:"source"`
	Destination string `json:"destination"`
	RW          bool   `json:"rw"`
}

DetailMount 是详情里的一条挂载。

type DetailNetwork added in v0.3.0

type DetailNetwork struct {
	Name    string   `json:"name"`
	IP      string   `json:"ip"`
	Gateway string   `json:"gateway"`
	MAC     string   `json:"mac"`
	Aliases []string `json:"aliases"`
}

DetailNetwork 是详情里的一个网络连接。

type DiskUsage added in v0.3.0

type DiskUsage struct {
	Images     UsageItem `json:"images"`
	Containers UsageItem `json:"containers"`
	Volumes    UsageItem `json:"volumes"`
	BuildCache UsageItem `json:"buildCache"`
}

DiskUsage 是 /disk-usage 的响应。

type FileEntry added in v0.3.0

type FileEntry struct {
	Name     string `json:"name"`
	Path     string `json:"path"`
	Dir      bool   `json:"dir"`
	Size     int64  `json:"size"`
	Mode     string `json:"mode"`     // 形如 drwxr-xr-x
	Modified string `json:"modified"` // RFC3339
	Link     string `json:"link,omitempty"`
}

FileEntry 是目录列表中的一项。

type ImageDetail added in v0.3.0

type ImageDetail struct {
	ID           string            `json:"id"`
	Tags         []string          `json:"tags"`
	Size         int64             `json:"size"`
	Created      int64             `json:"created"`
	OS           string            `json:"os"`
	Arch         string            `json:"arch"`
	Author       string            `json:"author"`
	Cmd          []string          `json:"cmd"`
	Entrypoint   []string          `json:"entrypoint"`
	Env          []string          `json:"env"`
	ExposedPorts []string          `json:"exposedPorts"`
	Workdir      string            `json:"workdir"`
	User         string            `json:"user"`
	Labels       map[string]string `json:"labels"`
	Layers       []ImageLayer      `json:"layers"`
}

ImageDetail 是镜像详情。

type ImageLayer added in v0.3.0

type ImageLayer struct {
	CreatedBy string `json:"createdBy"`
	Size      int64  `json:"size"`
	Created   int64  `json:"created"`
}

ImageLayer 是镜像的一层历史。

type ImageView added in v0.3.0

type ImageView struct {
	ID         string   `json:"id"`
	Tags       []string `json:"tags"`
	Digests    []string `json:"digests"`
	Size       int64    `json:"size"`
	Created    int64    `json:"created"`
	Containers int      `json:"containers"`
	Dangling   bool     `json:"dangling"`
}

ImageView 是镜像列表项。

type InfoView added in v0.3.0

type InfoView struct {
	Version       string `json:"version"`
	APIVersion    string `json:"apiVersion"`
	OS            string `json:"os"`
	Arch          string `json:"arch"`
	Kernel        string `json:"kernel"`
	Name          string `json:"name"`
	CPUs          int    `json:"cpus"`
	MemTotal      int64  `json:"memTotal"`
	StorageDriver string `json:"storageDriver"`
	RootDir       string `json:"rootDir"`
	Containers    struct {
		Total   int `json:"total"`
		Running int `json:"running"`
		Paused  int `json:"paused"`
		Stopped int `json:"stopped"`
	} `json:"containers"`
	Images            int    `json:"images"`
	ComposeCli        bool   `json:"composeCli"`
	ComposeCliVersion string `json:"composeCliVersion"`
	// DaemonMirrors 是 Docker 守护进程自身的镜像加速地址(daemon.json 的 registry-mirrors),
	// 由 dockerd 拉取 Docker Hub 镜像时自动使用,与 Gately 设置中的回退加速地址相互独立
	DaemonMirrors []string `json:"daemonMirrors"`
}

InfoView 是 /info 的响应。

type Module

type Module struct {
	// contains filtered or unexported fields
}

Module 是 Docker 管理模块。

func New

func New() *Module

New 创建模块。

func (*Module) ContainerNames added in v0.5.5

func (m *Module) ContainerNames(ctx context.Context) ([]string, error)

ContainerNames 返回全部容器的名称,供证书部署等功能选择要重启的容器。

func (*Module) FollowLogs added in v0.5.6

func (m *Module) FollowLogs(ctx context.Context, name string, onLine func(string)) error

FollowLogs 持续读取容器新产生的日志行,直到 ctx 取消或容器日志流结束,供入侵防护的日志规则使用。

func (*Module) ID

func (m *Module) ID() string

ID 实现 module.Module。

func (*Module) Init

func (m *Module) Init(env module.Env) error

Init 实现 module.Module。

func (*Module) RestartContainers added in v0.5.5

func (m *Module) RestartContainers(ctx context.Context, names []string) error

RestartContainers 依次重启指定容器(名称或 ID),例如证书更新后让服务加载新证书。

func (*Module) Routes

func (m *Module) Routes(r module.Router)

Routes 实现 module.Module。

func (*Module) Start

func (m *Module) Start(ctx context.Context) error

Start 实现 module.Module:按设置启动定时检查更新。

func (*Module) Stop

func (m *Module) Stop() error

Stop 实现 module.Module:停止定时检查并等待其退出。

func (*Module) Summary added in v0.4.2

func (m *Module) Summary() []module.SummaryItem

Summary 实现 module.Summarizer:容器运行 / 停止 / 异常数量与待更新数量;连不上 Docker 时提示未连接。

func (*Module) Title

func (m *Module) Title() string

Title 实现 module.Module。

type NetworkContainer added in v0.3.0

type NetworkContainer struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	IP   string `json:"ip"`
}

NetworkContainer 是接入网络的容器。

type NetworkView added in v0.3.0

type NetworkView struct {
	ID         string             `json:"id"`
	Name       string             `json:"name"`
	Driver     string             `json:"driver"`
	Scope      string             `json:"scope"`
	Subnet     string             `json:"subnet"`
	Gateway    string             `json:"gateway"`
	Internal   bool               `json:"internal"`
	IPv6       bool               `json:"ipv6"`
	Builtin    bool               `json:"builtin"`
	Containers []NetworkContainer `json:"containers"`
}

NetworkView 是网络列表项。

type Registry added in v0.3.0

type Registry struct {
	Server   string `json:"server"`
	Username string `json:"username"`
	Password string `json:"password"`
}

Registry 是一个镜像仓库的登录信息。

type Settings

type Settings struct {
	// Host 为 Docker 地址,默认 unix:///var/run/docker.sock
	Host string `json:"host"`
	// Mirrors 是镜像加速地址(如 docker.m.daocloud.io),直接拉取失败时依次尝试
	Mirrors []string `json:"mirrors"`
	// Registries 是私有仓库认证信息,拉取与推送时通过 X-Registry-Auth 传给 Docker
	Registries []Registry `json:"registries"`
	// AutoCheckHours 大于 0 时按该间隔自动检查容器镜像更新
	AutoCheckHours int `json:"autoCheckHours"`
}

Settings 是模块配置。

type SpecDevice added in v0.3.0

type SpecDevice struct {
	Host      string `json:"host"`
	Container string `json:"container"`
	Perm      string `json:"perm"`
}

SpecDevice 是设备映射。

type SpecPort added in v0.3.0

type SpecPort struct {
	HostIP    string `json:"hostIp"`
	Host      int    `json:"host"`
	Container int    `json:"container"`
	Proto     string `json:"proto"`
}

SpecPort 是端口映射。

type SpecVolume added in v0.3.0

type SpecVolume struct {
	Type     string `json:"type"` // bind / volume
	Source   string `json:"source"`
	Target   string `json:"target"`
	ReadOnly bool   `json:"readOnly"`
}

SpecVolume 是数据卷或目录挂载。

type StatsView added in v0.3.0

type StatsView struct {
	CPUPercent float64 `json:"cpuPercent"`
	MemUsage   uint64  `json:"memUsage"`
	MemLimit   uint64  `json:"memLimit"`
	MemPercent float64 `json:"memPercent"`
	NetRx      uint64  `json:"netRx"`
	NetTx      uint64  `json:"netTx"`
	BlockRead  uint64  `json:"blockRead"`
	BlockWrite uint64  `json:"blockWrite"`
	Pids       uint64  `json:"pids"`
}

StatsView 是单次采样的资源占用。

type Task added in v0.3.0

type Task struct {
	ID       string    `json:"id"`
	Kind     string    `json:"kind"`   // pull / push / build / compose / upgrade / volume 等
	Title    string    `json:"title"`  // 展示用标题
	Status   string    `json:"status"` // running / done / error / cancelled
	Error    string    `json:"error,omitempty"`
	Lines    []string  `json:"lines"` // 最近的进度行(最多 maxTaskLines 行)
	Started  time.Time `json:"started"`
	Finished time.Time `json:"finished,omitempty"`
	// Cancelling 表示已请求取消、任务正在收尾(例如等待 compose 进程退出)
	Cancelling bool `json:"cancelling,omitempty"`
	// contains filtered or unexported fields
}

Task 是后台长任务(拉取镜像、构建、compose up 等)。接口立即返回任务 ID,界面轮询进度, 这样移动端切到后台或网络抖动后重新打开页面仍能看到结果。

type UpdateInfo

type UpdateInfo struct {
	Checked   time.Time `json:"checked"`
	HasUpdate bool      `json:"hasUpdate"`
	Error     string    `json:"error,omitempty"`
}

UpdateInfo 是镜像更新检查结果。

type UsageItem added in v0.3.0

type UsageItem struct {
	Count       int   `json:"count"`
	Size        int64 `json:"size"`
	Reclaimable int64 `json:"reclaimable"`
}

UsageItem 是一类资源的占用。

type VolumeRef added in v0.3.0

type VolumeRef struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

VolumeRef 是使用卷的容器。

type VolumeView added in v0.3.0

type VolumeView struct {
	Name       string            `json:"name"`
	Driver     string            `json:"driver"`
	Mountpoint string            `json:"mountpoint"`
	Created    string            `json:"created"`
	Size       int64             `json:"size"`
	RefCount   int               `json:"refCount"`
	UsedBy     []VolumeRef       `json:"usedBy"`
	Labels     map[string]string `json:"labels"`
}

VolumeView 是卷列表项。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL