仰望星辰工作室

miaopanel

miaopanel/ internal/docker/images.go 1.8 KB · 71 行 原始文件
1package docker
2
3import (
4 "context"
5 "fmt"
6 "strings"
7 "time"
8)
9
10// Images lists local images.
11func (s *Service) Images(ctx context.Context) ([]Image, error) {
12 out, err := s.run(ctx, 10*time.Second, "image", "ls", "--no-trunc", "--format", "{{json .}}")
13 if err != nil {
14 return nil, err
15 }
16 rows := jsonLines(out.Stdout)
17 images := make([]Image, 0, len(rows))
18 for _, row := range rows {
19 images = append(images, Image{
20 ID: textField(row, "ID"),
21 Repository: textField(row, "Repository"),
22 Tag: textField(row, "Tag"),
23 Size: textField(row, "Size"),
24 CreatedAt: textField(row, "CreatedAt"),
25 })
26 }
27 return images, nil
28}
29
30// PullImage pulls one image reference.
31func (s *Service) PullImage(ctx context.Context, ref string) (string, error) {
32 ref = strings.TrimSpace(ref)
33 if !imageRefRe.MatchString(ref) {
34 return "", fmt.Errorf("%w: 镜像名称不合法", ErrInvalid)
35 }
36 res, err := s.run(ctx, 20*time.Minute, "pull", ref)
37 if err != nil {
38 return "", err
39 }
40 return clip(strings.TrimSpace(res.Stdout+"\n"+res.Stderr), 16<<10), nil
41}
42
43// RemoveImage removes one image by tag or ID.
44func (s *Service) RemoveImage(ctx context.Context, ref string) error {
45 ref = strings.TrimSpace(ref)
46 if !validImageRef(ref) {
47 return fmt.Errorf("%w: 镜像引用不合法", ErrInvalid)
48 }
49 _, err := s.run(ctx, 60*time.Second, "rmi", ref)
50 return err
51}
52
53func validImageRef(ref string) bool {
54 if imageRefRe.MatchString(ref) {
55 return true
56 }
57 if strings.HasPrefix(ref, "sha256:") {
58 hexPart := strings.TrimPrefix(ref, "sha256:")
59 return len(hexPart) >= 12 && len(hexPart) <= 64 && isHex(hexPart)
60 }
61 return false
62}
63
64func isHex(s string) bool {
65 for _, r := range s {
66 if (r < '0' || r > '9') && (r < 'a' || r > 'f') && (r < 'A' || r > 'F') {
67 return false
68 }
69 }
70 return len(s) > 0
71}