package docker import ( "context" "encoding/json" "fmt" "strings" "time" ) // Volumes lists Docker volumes with their mountpoints when available. func (s *Service) Volumes(ctx context.Context) ([]Volume, error) { out, err := s.run(ctx, 10*time.Second, "volume", "ls", "--format", "{{json .}}") if err != nil { return nil, err } rows := jsonLines(out.Stdout) volumes := make([]Volume, 0, len(rows)) names := make([]string, 0, len(rows)) for _, row := range rows { name := textField(row, "Name") if name == "" { continue } names = append(names, name) volumes = append(volumes, Volume{ Name: name, Driver: textField(row, "Driver"), Scope: textField(row, "Scope"), }) } if len(names) > 0 { if raw, err := s.run(ctx, 15*time.Second, append([]string{"volume", "inspect"}, names...)...); err == nil { var inspected []struct { Name string `json:"Name"` Driver string `json:"Driver"` Mountpoint string `json:"Mountpoint"` Scope string `json:"Scope"` } if json.Unmarshal([]byte(raw.Stdout), &inspected) == nil { index := map[string]int{} for i, v := range volumes { index[v.Name] = i } for _, item := range inspected { if i, ok := index[item.Name]; ok { volumes[i].Driver = item.Driver volumes[i].Mountpoint = item.Mountpoint volumes[i].Scope = item.Scope } } } } } return volumes, nil } // CreateVolume creates a local volume. func (s *Service) CreateVolume(ctx context.Context, name string) (string, error) { name = strings.TrimSpace(name) if !validResourceName(name) { return "", fmt.Errorf("%w: 卷名称只能包含字母、数字、点、下划线和短横线", ErrInvalid) } res, err := s.run(ctx, 60*time.Second, "volume", "create", name) if err != nil { return "", err } return strings.TrimSpace(res.Stdout), nil } // RemoveVolume removes a volume. Docker refuses when it is still in use. func (s *Service) RemoveVolume(ctx context.Context, name string) error { name = strings.TrimSpace(name) if !validResourceName(name) { return fmt.Errorf("%w: 卷名称不合法", ErrInvalid) } _, err := s.run(ctx, 60*time.Second, "volume", "rm", name) return err }