/
volume.go
52 lines (46 loc) · 1.28 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
package docker
import (
"context"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/volume"
"github.com/docker/docker/client"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"github.com/runabol/tork"
"github.com/runabol/tork/internal/uuid"
)
type VolumeMounter struct {
client *client.Client
}
func NewVolumeMounter() (*VolumeMounter, error) {
dc, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
return nil, err
}
return &VolumeMounter{client: dc}, nil
}
func (m *VolumeMounter) Mount(ctx context.Context, mn *tork.Mount) error {
name := uuid.NewUUID()
mn.Source = name
v, err := m.client.VolumeCreate(ctx, volume.CreateOptions{Name: name})
if err != nil {
return err
}
log.Debug().
Str("mount-point", v.Mountpoint).Msgf("created volume %s", v.Name)
return nil
}
func (m *VolumeMounter) Unmount(ctx context.Context, mn *tork.Mount) error {
ls, err := m.client.VolumeList(ctx, volume.ListOptions{Filters: filters.NewArgs(filters.Arg("name", mn.Source))})
if err != nil {
return err
}
if len(ls.Volumes) == 0 {
return errors.Errorf("unknown volume: %s", mn.Source)
}
if err := m.client.VolumeRemove(ctx, mn.Source, true); err != nil {
return err
}
log.Debug().Msgf("removed volume %s", mn.Source)
return nil
}