forked from xplorfin/docker-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
volume.go
66 lines (58 loc) · 1.82 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
package docker
import (
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/volume"
)
// RemoveContainer removes a stopped a container (and it's volumes) by id if it exists
// see Client.ContainerRemove or https://docs.docker.com/engine/reference/commandline/container_rm/
// for details
func (c *Client) RemoveContainer(id string) error {
err := c.ContainerRemove(c.Ctx, id, types.ContainerRemoveOptions{
RemoveVolumes: true,
})
return err
}
// StopContainer stops a container (but does not remove it) by id if it exists
// see Client.ContainerStop or https://docs.docker.com/engine/reference/commandline/container_stop/
// for details
func (c *Client) StopContainer(id string) error {
timeout := time.Second * 5
err := c.ContainerStop(c.Ctx, id, &timeout)
return err
}
// RemoveVolume removes a volume by name if it exists
// see Client.VolumeRemove or https://docs.docker.com/engine/reference/commandline/volume_rm/
// for details
func (c *Client) RemoveVolume(name string) error {
err := c.VolumeRemove(c.Ctx, name, true)
return err
}
// VolumeExists checks if a volume exists by name
// see Client.VolumeInspect or https://docs.docker.com/engine/reference/commandline/volume_inspect/
// for details
func (c *Client) VolumeExists(name string) bool {
_, err := c.VolumeInspect(c.Ctx, name)
return err == nil
}
// CreateVolume creates a new docker volume with a unique name
// see Client.VolumeCreate or https://docs.docker.com/engine/extend/plugins_volume/
// for details
func (c *Client) CreateVolume(name string) (err error) {
if c.VolumeExists(name) {
err := c.RemoveVolume(name)
if err != nil {
return err
}
}
vol, err := c.VolumeCreate(c.Ctx, volume.VolumeCreateBody{
Driver: Driver,
Name: name,
Labels: c.GetSessionLabels(),
})
if err != nil {
return err
}
_ = vol
return nil
}