/
volume.go
76 lines (67 loc) · 2.32 KB
/
volume.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package volume
import (
"regexp"
log "github.com/Sirupsen/logrus"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
volumetypes "github.com/docker/docker/api/types/volume"
runconfigopts "github.com/docker/docker/runconfig/opts"
"github.com/maliceio/malice/config"
"github.com/maliceio/malice/malice/docker/client"
"golang.org/x/net/context"
)
// Exists returns type.Volume and true
// if the volume name exists, otherwise false.
func Exists(docker *client.Docker, name string) (*types.Volume, bool, error) {
return parseVolumes(docker, name, true)
}
// Create creates a docker volume with the given name
// returns: error
func Create(docker *client.Docker, name, driver string, labels []string) error {
volReq := volumetypes.VolumesCreateBody{
Driver: driver,
// DriverOpts: opts.driverOpts.GetAll(),
Name: name,
Labels: runconfigopts.ConvertKVStringsToMap(labels),
}
vol, err := docker.Client.VolumeCreate(context.Background(), volReq)
if err != nil {
return err
}
log.WithFields(log.Fields{
"env": config.Conf.Environment.Run,
}).Info("Created Volume: ", vol.Name)
return nil
}
// ParseVolumes parses the volumes
func parseVolumes(docker *client.Docker, name string, all bool) (*types.Volume, bool, error) {
// list volumes
log.WithFields(log.Fields{"env": config.Conf.Environment.Run}).Debug("Searching for volume: ", name)
volumes, err := List(docker, all)
if err != nil {
return nil, false, err
}
// locate docker volume that matches name
r := regexp.MustCompile(name)
if len(volumes.Volumes) != 0 {
for _, volume := range volumes.Volumes {
if r.MatchString(volume.Name) {
log.WithFields(log.Fields{"env": config.Conf.Environment.Run}).Debug("Volume FOUND: ", name)
return volume, true, nil
}
}
}
log.WithFields(log.Fields{"env": config.Conf.Environment.Run}).Debug("Volume NOT Found: ", name)
return nil, false, nil
}
// List returns array of types.Containers and error
func List(docker *client.Docker, all bool) (volumetypes.VolumesListOKBody, error) {
// ctx, cancel := context.WithTimeout(context.Background(), config.Conf.Docker.Timeout*time.Second)
// defer cancel()
filter := filters.Args{}
volumes, err := docker.Client.VolumeList(context.Background(), filter)
if err != nil {
return volumetypes.VolumesListOKBody{}, err
}
return volumes, nil
}