github.com/ssdev-go/moby@v17.12.1-ce-rc2+incompatible/hack/integration-cli-on-swarm/host/volume.go (about) 1 package main 2 3 import ( 4 "archive/tar" 5 "bytes" 6 "context" 7 "io" 8 9 "github.com/docker/docker/api/types" 10 "github.com/docker/docker/api/types/container" 11 "github.com/docker/docker/api/types/mount" 12 "github.com/docker/docker/api/types/volume" 13 "github.com/docker/docker/client" 14 ) 15 16 func createTar(data map[string][]byte) (io.Reader, error) { 17 var b bytes.Buffer 18 tw := tar.NewWriter(&b) 19 for path, datum := range data { 20 hdr := tar.Header{ 21 Name: path, 22 Mode: 0644, 23 Size: int64(len(datum)), 24 } 25 if err := tw.WriteHeader(&hdr); err != nil { 26 return nil, err 27 } 28 _, err := tw.Write(datum) 29 if err != nil { 30 return nil, err 31 } 32 } 33 if err := tw.Close(); err != nil { 34 return nil, err 35 } 36 return &b, nil 37 } 38 39 // createVolumeWithData creates a volume with the given data (e.g. data["/foo"] = []byte("bar")) 40 // Internally, a container is created from the image so as to provision the data to the volume, 41 // which is attached to the container. 42 func createVolumeWithData(cli *client.Client, volumeName string, data map[string][]byte, image string) error { 43 _, err := cli.VolumeCreate(context.Background(), 44 volume.VolumesCreateBody{ 45 Driver: "local", 46 Name: volumeName, 47 }) 48 if err != nil { 49 return err 50 } 51 mnt := "/mnt" 52 miniContainer, err := cli.ContainerCreate(context.Background(), 53 &container.Config{ 54 Image: image, 55 }, 56 &container.HostConfig{ 57 Mounts: []mount.Mount{ 58 { 59 Type: mount.TypeVolume, 60 Source: volumeName, 61 Target: mnt, 62 }, 63 }, 64 }, nil, "") 65 if err != nil { 66 return err 67 } 68 tr, err := createTar(data) 69 if err != nil { 70 return err 71 } 72 if cli.CopyToContainer(context.Background(), 73 miniContainer.ID, mnt, tr, types.CopyToContainerOptions{}); err != nil { 74 return err 75 } 76 return cli.ContainerRemove(context.Background(), 77 miniContainer.ID, 78 types.ContainerRemoveOptions{}) 79 } 80 81 func hasVolume(cli *client.Client, volumeName string) bool { 82 _, err := cli.VolumeInspect(context.Background(), volumeName) 83 return err == nil 84 } 85 86 func removeVolume(cli *client.Client, volumeName string) error { 87 return cli.VolumeRemove(context.Background(), volumeName, true) 88 }