package docker import ( "context" "crypto/rand" "encoding/hex" "encoding/json" "fmt" "os" "path/filepath" "sort" "strconv" "strings" "time" "github.com/miaopanel/miaopanel/internal/fsutil" ) type inspectContainer struct { ID string `json:"Id"` Name string `json:"Name"` Created string `json:"Created"` State struct { Status string `json:"Status"` } `json:"State"` Config struct { Image string `json:"Image"` } `json:"Config"` NetworkSettings struct { Ports map[string][]struct { HostIP string `json:"HostIp"` HostPort string `json:"HostPort"` } `json:"Ports"` } `json:"NetworkSettings"` } // ListContainers returns every container with port mappings and panel bindings. func (s *Service) ListContainers(ctx context.Context) ([]Container, error) { out, err := s.run(ctx, 10*time.Second, "ps", "-a", "--no-trunc", "--format", "{{json .}}") if err != nil { return nil, err } rows := jsonLines(out.Stdout) if len(rows) == 0 { return []Container{}, nil } ids := make([]string, 0, len(rows)) for _, row := range rows { if id := textField(row, "ID"); id != "" { ids = append(ids, id) } } inspected := map[string]inspectContainer{} if len(ids) > 0 { args := append([]string{"inspect"}, ids...) if raw, err := s.run(ctx, 15*time.Second, args...); err == nil { var list []inspectContainer if err := json.Unmarshal([]byte(raw.Stdout), &list); err == nil { for _, item := range list { inspected[item.ID] = item } } } } siteBindings := map[string][]Binding{} if sites, err := s.db.ListSites(ctx); err == nil { for _, st := range sites { cid := st.Options.DockerContainerID if st.Kind != "proxy" || cid == "" { continue } // Compare prefixes in both directions: IDs stored at bind time are // full IDs, but a short ID is accepted here for resilience. matched := "" for _, id := range ids { if id == cid || strings.HasPrefix(id, cid) || strings.HasPrefix(cid, id) { matched = id break } } if matched == "" { continue } siteBindings[matched] = append(siteBindings[matched], Binding{ SiteID: st.ID, Slug: st.Slug, Domains: st.Domains, HostPort: st.Options.DockerHostPort, ContainerPort: st.Options.DockerContainerPort, }) } } containers := make([]Container, 0, len(rows)) for _, row := range rows { id := textField(row, "ID") c := Container{ ID: id, ShortID: shortID(id), Name: strings.TrimPrefix(textField(row, "Names"), "/"), Image: textField(row, "Image"), State: textField(row, "State"), Status: textField(row, "Status"), CreatedAt: textField(row, "CreatedAt"), } if item, ok := inspected[id]; ok { if item.Name != "" { c.Name = strings.TrimPrefix(item.Name, "/") } if item.State.Status != "" { c.State = item.State.Status } if item.Config.Image != "" { c.Image = item.Config.Image } if item.Created != "" { c.CreatedAt = item.Created } c.Ports = inspectPorts(item.NetworkSettings.Ports) } if len(c.Ports) == 0 { c.Ports = parsePorts(textField(row, "Ports")) } c.Bindings = siteBindings[id] for _, b := range c.Bindings { c.DomainNames = append(c.DomainNames, b.Domains...) } containers = append(containers, c) } sort.SliceStable(containers, func(i, j int) bool { return containers[i].Name < containers[j].Name }) return containers, nil } func inspectPorts(raw map[string][]struct { HostIP string `json:"HostIp"` HostPort string `json:"HostPort"` }) []Port { seen := map[string]bool{} out := make([]Port, 0, 8) keys := make([]string, 0, len(raw)) for key := range raw { keys = append(keys, key) } sort.Strings(keys) for _, key := range keys { containerPort := 0 protocol := "tcp" if i := strings.LastIndex(key, "/"); i >= 0 { protocol = key[i+1:] containerPort, _ = strconv.Atoi(key[:i]) } mappings := raw[key] if len(mappings) == 0 { out = append(out, Port{ContainerPort: containerPort, Protocol: protocol}) continue } for _, m := range mappings { host, _ := strconv.Atoi(m.HostPort) dedupe := fmt.Sprintf("%d|%d|%s", host, containerPort, protocol) if seen[dedupe] { continue } seen[dedupe] = true out = append(out, Port{ HostIP: m.HostIP, HostPort: host, ContainerPort: containerPort, Protocol: protocol, Published: host > 0, }) } } return out } func shortID(id string) string { if len(id) > 12 { return id[:12] } return id } func (s *Service) resolveContainer(ctx context.Context, ref string) (*Container, error) { ref = strings.TrimSpace(ref) if !validContainerRef(ref) { return nil, fmt.Errorf("%w: 容器引用不合法", ErrInvalid) } list, err := s.ListContainers(ctx) if err != nil { return nil, err } for i := range list { c := &list[i] if c.ID == ref || c.Name == ref || (len(ref) >= 12 && strings.HasPrefix(c.ID, ref)) { return c, nil } } return nil, fmt.Errorf("%w: 容器不存在", ErrInvalid) } // ContainerAction starts, stops or restarts a container. func (s *Service) ContainerAction(ctx context.Context, ref, action string) error { switch action { case "start", "stop", "restart": default: return fmt.Errorf("%w: 不支持的操作 %q", ErrInvalid, action) } c, err := s.resolveContainer(ctx, ref) if err != nil { return err } _, err = s.run(ctx, 90*time.Second, action, c.ID) return err } // ContainerLogs returns the tail of a container log. func (s *Service) ContainerLogs(ctx context.Context, ref string, tail int) (string, error) { if tail <= 0 || tail > 2000 { tail = 200 } c, err := s.resolveContainer(ctx, ref) if err != nil { return "", err } res, err := s.run(ctx, 30*time.Second, "logs", "--tail", strconv.Itoa(tail), c.ID) if err != nil { return "", err } return clip(strings.TrimSpace(res.Stdout+"\n"+res.Stderr), 64<<10), nil } // Bindings returns the nginx sites bound to one container. func (s *Service) Bindings(ctx context.Context, ref string) ([]Binding, error) { c, err := s.resolveContainer(ctx, ref) if err != nil { return nil, err } return c.Bindings, nil } // RemoveContainer deletes a container. bindingMode is "remove" (delete the // proxy sites), "keep" (explicitly keep them) or "" (refuse when bindings exist). func (s *Service) RemoveContainer(ctx context.Context, ref string, force bool, bindingMode string) error { c, err := s.resolveContainer(ctx, ref) if err != nil { return err } switch bindingMode { case "remove": for _, b := range c.Bindings { if err := s.sites.Delete(ctx, b.SiteID, true); err != nil { return fmt.Errorf("删除绑定站点 %s 失败: %w", b.Slug, err) } } case "keep": // Explicitly keep the sites; the operator accepted that they will 502. default: if len(c.Bindings) > 0 { return &BindingError{Bindings: c.Bindings} } } args := []string{"rm"} if force { args = append(args, "-f") } args = append(args, c.ID) _, err = s.run(ctx, 90*time.Second, args...) return err } // Overview collects counts and storage usage for the dashboard. func (s *Service) Overview(ctx context.Context) (Overview, error) { var ov Overview out, err := s.run(ctx, 15*time.Second, "system", "df", "--format", "{{json .}}") if err != nil { return ov, err } for _, row := range jsonLines(out.Stdout) { typ := strings.ToLower(textField(row, "Type")) total, _ := strconv.Atoi(textField(row, "TotalCount")) size := textField(row, "Size") switch typ { case "images": ov.Images = ResourceStat{Total: total, Size: size} case "containers": ov.Containers = ResourceStat{Total: total, Size: size} case "local volumes": ov.Volumes = ResourceStat{Total: total, Size: size} } } if out, err := s.run(ctx, 10*time.Second, "ps", "-q"); err == nil { ov.Containers.Running = countLines(out.Stdout) } if ov.Containers.Total == 0 { if out, err := s.run(ctx, 10*time.Second, "ps", "-aq"); err == nil { ov.Containers.Total = countLines(out.Stdout) } } if out, err := s.run(ctx, 10*time.Second, "network", "ls", "-q"); err == nil { ov.Networks.Total = countLines(out.Stdout) } if out, err := s.run(ctx, 10*time.Second, "volume", "ls", "-q"); err == nil { ov.Volumes.Total = countLines(out.Stdout) } if sites, err := s.db.ListSites(ctx); err == nil { for _, st := range sites { if st.Kind == "proxy" && st.Options.DockerContainerID != "" { ov.Bindings++ } } } return ov, nil } func countLines(text string) int { n := 0 for _, line := range strings.Split(text, "\n") { if strings.TrimSpace(line) != "" { n++ } } return n } // CreateFromRun executes a validated pasted docker run command. func (s *Service) CreateFromRun(ctx context.Context, raw string) (*CreateResult, error) { tokens, err := TokenizeDockerRun(raw) if err != nil { return nil, err } res, err := s.run(ctx, 10*time.Minute, tokens[1:]...) if err != nil { return nil, err } return &CreateResult{Mode: "run", Output: strings.TrimSpace(res.Stdout + "\n" + res.Stderr)}, nil } // CreateFromCompose writes the YAML under the panel data dir and runs compose up. func (s *Service) CreateFromCompose(ctx context.Context, project, yaml string) (*CreateResult, error) { if err := ValidateCompose(yaml); err != nil { return nil, err } project = strings.TrimSpace(project) if project == "" { project = "stack-" + randomHex(6) } if !resourceNameRe.MatchString(project) { return nil, fmt.Errorf("%w: 项目名称只能包含字母、数字、点、下划线和短横线", ErrInvalid) } root := filepath.Join(s.cfg.DataDir, "docker", "compose", project) if err := os.MkdirAll(root, 0o755); err != nil { return nil, err } path := filepath.Join(root, "compose.yaml") if err := fsutil.WriteFileAtomic(path, []byte(yaml), 0o600); err != nil { return nil, fmt.Errorf("写入 compose 文件失败: %w", err) } if _, err := s.run(ctx, 15*time.Minute, "compose", "-f", path, "-p", project, "up", "-d"); err != nil { return nil, err } return &CreateResult{Mode: "compose", Stack: project, Path: path, Output: "compose up 完成"}, nil } func randomHex(n int) string { b := make([]byte, n) _, _ = rand.Read(b) return hex.EncodeToString(b) }