miaopanel
1package docker
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "strings"
8 "time"
9)
10
11// Volumes lists Docker volumes with their mountpoints when available.
12func (s *Service) Volumes(ctx context.Context) ([]Volume, error) {
13 out, err := s.run(ctx, 10*time.Second, "volume", "ls", "--format", "{{json .}}")
14 if err != nil {
15 return nil, err
16 }
17 rows := jsonLines(out.Stdout)
18 volumes := make([]Volume, 0, len(rows))
19 names := make([]string, 0, len(rows))
20 for _, row := range rows {
21 name := textField(row, "Name")
22 if name == "" {
23 continue
24 }
25 names = append(names, name)
26 volumes = append(volumes, Volume{
27 Name: name,
28 Driver: textField(row, "Driver"),
29 Scope: textField(row, "Scope"),
30 })
31 }
32 if len(names) > 0 {
33 if raw, err := s.run(ctx, 15*time.Second, append([]string{"volume", "inspect"}, names...)...); err == nil {
34 var inspected []struct {
35 Name string `json:"Name"`
36 Driver string `json:"Driver"`
37 Mountpoint string `json:"Mountpoint"`
38 Scope string `json:"Scope"`
39 }
40 if json.Unmarshal([]byte(raw.Stdout), &inspected) == nil {
41 index := map[string]int{}
42 for i, v := range volumes {
43 index[v.Name] = i
44 }
45 for _, item := range inspected {
46 if i, ok := index[item.Name]; ok {
47 volumes[i].Driver = item.Driver
48 volumes[i].Mountpoint = item.Mountpoint
49 volumes[i].Scope = item.Scope
50 }
51 }
52 }
53 }
54 }
55 return volumes, nil
56}
57
58// CreateVolume creates a local volume.
59func (s *Service) CreateVolume(ctx context.Context, name string) (string, error) {
60 name = strings.TrimSpace(name)
61 if !validResourceName(name) {
62 return "", fmt.Errorf("%w: 卷名称只能包含字母、数字、点、下划线和短横线", ErrInvalid)
63 }
64 res, err := s.run(ctx, 60*time.Second, "volume", "create", name)
65 if err != nil {
66 return "", err
67 }
68 return strings.TrimSpace(res.Stdout), nil
69}
70
71// RemoveVolume removes a volume. Docker refuses when it is still in use.
72func (s *Service) RemoveVolume(ctx context.Context, name string) error {
73 name = strings.TrimSpace(name)
74 if !validResourceName(name) {
75 return fmt.Errorf("%w: 卷名称不合法", ErrInvalid)
76 }
77 _, err := s.run(ctx, 60*time.Second, "volume", "rm", name)
78 return err
79}