Skip to content

Commit

Permalink
Merge pull request #2083 from xiaoxubeii/fix-filter-volumes
Browse files Browse the repository at this point in the history
WIP bugfix: fix that ListVolumes did not implement filter by labels
  • Loading branch information
rudyfly authored Aug 22, 2018
2 parents 48cdcfc + c706c78 commit d6a4571
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
13 changes: 13 additions & 0 deletions storage/volume/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,20 @@ func (c *Core) ListVolumes(labels map[string]string) ([]*types.Volume, error) {
c.store.Put(v)

retVolumes = append(retVolumes, v)
}

// filter volumes if specify labels
if len(labels) != 0 {
filteredVolumes := make([]*types.Volume, 0)
for k, v := range labels {
for _, vol := range retVolumes {
if val, ok := vol.Labels[k]; ok && val == v {
filteredVolumes = append(filteredVolumes, vol)
}
}
}

return filteredVolumes, nil
}

return retVolumes, nil
Expand Down
42 changes: 42 additions & 0 deletions storage/volume/core_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package volume

import (
"fmt"
"io/ioutil"
"os"
"path"
Expand Down Expand Up @@ -175,6 +176,47 @@ func TestListVolumes(t *testing.T) {
}
}

func TestListVolumesWithLabels(t *testing.T) {
driverName := "fake_driver5"
dir, err := ioutil.TempDir("", "TestListVolumesWithLabels")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)

core, err := createVolumeCore(dir)
if err != nil {
t.Fatal(err)
}

driver.Register(driver.NewFakeDriver(driverName))
defer driver.Unregister(driverName)

var i int64
for i = 0; i < 6; i++ {
volName := strconv.FormatInt(i, 10)
volid := types.VolumeID{Name: volName, Driver: driverName, Labels: map[string]string{fmt.Sprintf("label-%v", i): fmt.Sprintf("value-%v", i)}}
_, err := core.CreateVolume(volid)
if err != nil {
t.Fatalf("create volume error: %v", err)
}
}

testLabels := map[string]string{"test-label": "test-value"}

testVolume, err := core.CreateVolume(types.VolumeID{Name: "test-volume", Driver: driverName, Labels: testLabels})
if err != nil {
t.Fatalf("create volume error: %v", err)
}
realVolume, err := core.ListVolumes(testLabels)
if err != nil {
t.Fatalf("list volumes error: %v", err)
}
if len(realVolume) != 1 || testVolume.UID != realVolume[0].UID {
t.Fatalf("fail to list volumes with labels %v, expect value is %v, real value is %v.", testLabels, testVolume, realVolume[0])
}
}

func TestListVolumeName(t *testing.T) {
driverName := "my_fake"
dir, err := ioutil.TempDir("", "TestGetVolume")
Expand Down

0 comments on commit d6a4571

Please sign in to comment.