miaopanel
1package docker
2
3import (
4 "context"
5 "crypto/rand"
6 "encoding/hex"
7 "encoding/json"
8 "fmt"
9 "os"
10 "path/filepath"
11 "sort"
12 "strconv"
13 "strings"
14 "time"
15
16 "github.com/miaopanel/miaopanel/internal/fsutil"
17)
18
19type inspectContainer struct {
20 ID string `json:"Id"`
21 Name string `json:"Name"`
22 Created string `json:"Created"`
23 State struct {
24 Status string `json:"Status"`
25 } `json:"State"`
26 Config struct {
27 Image string `json:"Image"`
28 } `json:"Config"`
29 NetworkSettings struct {
30 Ports map[string][]struct {
31 HostIP string `json:"HostIp"`
32 HostPort string `json:"HostPort"`
33 } `json:"Ports"`
34 } `json:"NetworkSettings"`
35}
36
37// ListContainers returns every container with port mappings and panel bindings.
38func (s *Service) ListContainers(ctx context.Context) ([]Container, error) {
39 out, err := s.run(ctx, 10*time.Second, "ps", "-a", "--no-trunc", "--format", "{{json .}}")
40 if err != nil {
41 return nil, err
42 }
43 rows := jsonLines(out.Stdout)
44 if len(rows) == 0 {
45 return []Container{}, nil
46 }
47
48 ids := make([]string, 0, len(rows))
49 for _, row := range rows {
50 if id := textField(row, "ID"); id != "" {
51 ids = append(ids, id)
52 }
53 }
54 inspected := map[string]inspectContainer{}
55 if len(ids) > 0 {
56 args := append([]string{"inspect"}, ids...)
57 if raw, err := s.run(ctx, 15*time.Second, args...); err == nil {
58 var list []inspectContainer
59 if err := json.Unmarshal([]byte(raw.Stdout), &list); err == nil {
60 for _, item := range list {
61 inspected[item.ID] = item
62 }
63 }
64 }
65 }
66
67 siteBindings := map[string][]Binding{}
68 if sites, err := s.db.ListSites(ctx); err == nil {
69 for _, st := range sites {
70 cid := st.Options.DockerContainerID
71 if st.Kind != "proxy" || cid == "" {
72 continue
73 }
74 // Compare prefixes in both directions: IDs stored at bind time are
75 // full IDs, but a short ID is accepted here for resilience.
76 matched := ""
77 for _, id := range ids {
78 if id == cid || strings.HasPrefix(id, cid) || strings.HasPrefix(cid, id) {
79 matched = id
80 break
81 }
82 }
83 if matched == "" {
84 continue
85 }
86 siteBindings[matched] = append(siteBindings[matched], Binding{
87 SiteID: st.ID, Slug: st.Slug, Domains: st.Domains,
88 HostPort: st.Options.DockerHostPort, ContainerPort: st.Options.DockerContainerPort,
89 })
90 }
91 }
92
93 containers := make([]Container, 0, len(rows))
94 for _, row := range rows {
95 id := textField(row, "ID")
96 c := Container{
97 ID: id, ShortID: shortID(id),
98 Name: strings.TrimPrefix(textField(row, "Names"), "/"),
99 Image: textField(row, "Image"),
100 State: textField(row, "State"),
101 Status: textField(row, "Status"),
102 CreatedAt: textField(row, "CreatedAt"),
103 }
104 if item, ok := inspected[id]; ok {
105 if item.Name != "" {
106 c.Name = strings.TrimPrefix(item.Name, "/")
107 }
108 if item.State.Status != "" {
109 c.State = item.State.Status
110 }
111 if item.Config.Image != "" {
112 c.Image = item.Config.Image
113 }
114 if item.Created != "" {
115 c.CreatedAt = item.Created
116 }
117 c.Ports = inspectPorts(item.NetworkSettings.Ports)
118 }
119 if len(c.Ports) == 0 {
120 c.Ports = parsePorts(textField(row, "Ports"))
121 }
122 c.Bindings = siteBindings[id]
123 for _, b := range c.Bindings {
124 c.DomainNames = append(c.DomainNames, b.Domains...)
125 }
126 containers = append(containers, c)
127 }
128 sort.SliceStable(containers, func(i, j int) bool {
129 return containers[i].Name < containers[j].Name
130 })
131 return containers, nil
132}
133
134func inspectPorts(raw map[string][]struct {
135 HostIP string `json:"HostIp"`
136 HostPort string `json:"HostPort"`
137}) []Port {
138 seen := map[string]bool{}
139 out := make([]Port, 0, 8)
140 keys := make([]string, 0, len(raw))
141 for key := range raw {
142 keys = append(keys, key)
143 }
144 sort.Strings(keys)
145 for _, key := range keys {
146 containerPort := 0
147 protocol := "tcp"
148 if i := strings.LastIndex(key, "/"); i >= 0 {
149 protocol = key[i+1:]
150 containerPort, _ = strconv.Atoi(key[:i])
151 }
152 mappings := raw[key]
153 if len(mappings) == 0 {
154 out = append(out, Port{ContainerPort: containerPort, Protocol: protocol})
155 continue
156 }
157 for _, m := range mappings {
158 host, _ := strconv.Atoi(m.HostPort)
159 dedupe := fmt.Sprintf("%d|%d|%s", host, containerPort, protocol)
160 if seen[dedupe] {
161 continue
162 }
163 seen[dedupe] = true
164 out = append(out, Port{
165 HostIP: m.HostIP, HostPort: host, ContainerPort: containerPort,
166 Protocol: protocol, Published: host > 0,
167 })
168 }
169 }
170 return out
171}
172
173func shortID(id string) string {
174 if len(id) > 12 {
175 return id[:12]
176 }
177 return id
178}
179
180func (s *Service) resolveContainer(ctx context.Context, ref string) (*Container, error) {
181 ref = strings.TrimSpace(ref)
182 if !validContainerRef(ref) {
183 return nil, fmt.Errorf("%w: 容器引用不合法", ErrInvalid)
184 }
185 list, err := s.ListContainers(ctx)
186 if err != nil {
187 return nil, err
188 }
189 for i := range list {
190 c := &list[i]
191 if c.ID == ref || c.Name == ref || (len(ref) >= 12 && strings.HasPrefix(c.ID, ref)) {
192 return c, nil
193 }
194 }
195 return nil, fmt.Errorf("%w: 容器不存在", ErrInvalid)
196}
197
198// ContainerAction starts, stops or restarts a container.
199func (s *Service) ContainerAction(ctx context.Context, ref, action string) error {
200 switch action {
201 case "start", "stop", "restart":
202 default:
203 return fmt.Errorf("%w: 不支持的操作 %q", ErrInvalid, action)
204 }
205 c, err := s.resolveContainer(ctx, ref)
206 if err != nil {
207 return err
208 }
209 _, err = s.run(ctx, 90*time.Second, action, c.ID)
210 return err
211}
212
213// ContainerLogs returns the tail of a container log.
214func (s *Service) ContainerLogs(ctx context.Context, ref string, tail int) (string, error) {
215 if tail <= 0 || tail > 2000 {
216 tail = 200
217 }
218 c, err := s.resolveContainer(ctx, ref)
219 if err != nil {
220 return "", err
221 }
222 res, err := s.run(ctx, 30*time.Second, "logs", "--tail", strconv.Itoa(tail), c.ID)
223 if err != nil {
224 return "", err
225 }
226 return clip(strings.TrimSpace(res.Stdout+"\n"+res.Stderr), 64<<10), nil
227}
228
229// Bindings returns the nginx sites bound to one container.
230func (s *Service) Bindings(ctx context.Context, ref string) ([]Binding, error) {
231 c, err := s.resolveContainer(ctx, ref)
232 if err != nil {
233 return nil, err
234 }
235 return c.Bindings, nil
236}
237
238// RemoveContainer deletes a container. bindingMode is "remove" (delete the
239// proxy sites), "keep" (explicitly keep them) or "" (refuse when bindings exist).
240func (s *Service) RemoveContainer(ctx context.Context, ref string, force bool, bindingMode string) error {
241 c, err := s.resolveContainer(ctx, ref)
242 if err != nil {
243 return err
244 }
245 switch bindingMode {
246 case "remove":
247 for _, b := range c.Bindings {
248 if err := s.sites.Delete(ctx, b.SiteID, true); err != nil {
249 return fmt.Errorf("删除绑定站点 %s 失败: %w", b.Slug, err)
250 }
251 }
252 case "keep":
253 // Explicitly keep the sites; the operator accepted that they will 502.
254 default:
255 if len(c.Bindings) > 0 {
256 return &BindingError{Bindings: c.Bindings}
257 }
258 }
259 args := []string{"rm"}
260 if force {
261 args = append(args, "-f")
262 }
263 args = append(args, c.ID)
264 _, err = s.run(ctx, 90*time.Second, args...)
265 return err
266}
267
268// Overview collects counts and storage usage for the dashboard.
269func (s *Service) Overview(ctx context.Context) (Overview, error) {
270 var ov Overview
271 out, err := s.run(ctx, 15*time.Second, "system", "df", "--format", "{{json .}}")
272 if err != nil {
273 return ov, err
274 }
275 for _, row := range jsonLines(out.Stdout) {
276 typ := strings.ToLower(textField(row, "Type"))
277 total, _ := strconv.Atoi(textField(row, "TotalCount"))
278 size := textField(row, "Size")
279 switch typ {
280 case "images":
281 ov.Images = ResourceStat{Total: total, Size: size}
282 case "containers":
283 ov.Containers = ResourceStat{Total: total, Size: size}
284 case "local volumes":
285 ov.Volumes = ResourceStat{Total: total, Size: size}
286 }
287 }
288 if out, err := s.run(ctx, 10*time.Second, "ps", "-q"); err == nil {
289 ov.Containers.Running = countLines(out.Stdout)
290 }
291 if ov.Containers.Total == 0 {
292 if out, err := s.run(ctx, 10*time.Second, "ps", "-aq"); err == nil {
293 ov.Containers.Total = countLines(out.Stdout)
294 }
295 }
296 if out, err := s.run(ctx, 10*time.Second, "network", "ls", "-q"); err == nil {
297 ov.Networks.Total = countLines(out.Stdout)
298 }
299 if out, err := s.run(ctx, 10*time.Second, "volume", "ls", "-q"); err == nil {
300 ov.Volumes.Total = countLines(out.Stdout)
301 }
302 if sites, err := s.db.ListSites(ctx); err == nil {
303 for _, st := range sites {
304 if st.Kind == "proxy" && st.Options.DockerContainerID != "" {
305 ov.Bindings++
306 }
307 }
308 }
309 return ov, nil
310}
311
312func countLines(text string) int {
313 n := 0
314 for _, line := range strings.Split(text, "\n") {
315 if strings.TrimSpace(line) != "" {
316 n++
317 }
318 }
319 return n
320}
321
322// CreateFromRun executes a validated pasted docker run command.
323func (s *Service) CreateFromRun(ctx context.Context, raw string) (*CreateResult, error) {
324 tokens, err := TokenizeDockerRun(raw)
325 if err != nil {
326 return nil, err
327 }
328 res, err := s.run(ctx, 10*time.Minute, tokens[1:]...)
329 if err != nil {
330 return nil, err
331 }
332 return &CreateResult{Mode: "run", Output: strings.TrimSpace(res.Stdout + "\n" + res.Stderr)}, nil
333}
334
335// CreateFromCompose writes the YAML under the panel data dir and runs compose up.
336func (s *Service) CreateFromCompose(ctx context.Context, project, yaml string) (*CreateResult, error) {
337 if err := ValidateCompose(yaml); err != nil {
338 return nil, err
339 }
340 project = strings.TrimSpace(project)
341 if project == "" {
342 project = "stack-" + randomHex(6)
343 }
344 if !resourceNameRe.MatchString(project) {
345 return nil, fmt.Errorf("%w: 项目名称只能包含字母、数字、点、下划线和短横线", ErrInvalid)
346 }
347 root := filepath.Join(s.cfg.DataDir, "docker", "compose", project)
348 if err := os.MkdirAll(root, 0o755); err != nil {
349 return nil, err
350 }
351 path := filepath.Join(root, "compose.yaml")
352 if err := fsutil.WriteFileAtomic(path, []byte(yaml), 0o600); err != nil {
353 return nil, fmt.Errorf("写入 compose 文件失败: %w", err)
354 }
355 if _, err := s.run(ctx, 15*time.Minute,
356 "compose", "-f", path, "-p", project, "up", "-d"); err != nil {
357 return nil, err
358 }
359 return &CreateResult{Mode: "compose", Stack: project, Path: path, Output: "compose up 完成"}, nil
360}
361
362func randomHex(n int) string {
363 b := make([]byte, n)
364 _, _ = rand.Read(b)
365 return hex.EncodeToString(b)
366}