Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add scan command #199

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions database/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,91 @@ func execCopy(mdb *Server, conn redis.Connection, args [][]byte) redis.Reply {
return protocol.MakeIntReply(1)
}

// execScan iteratively output all keys in the current db
func execScan(db *DB, args [][]byte) redis.Reply {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

scan 的参数有 MATCH,COUNT, TYPE 3个,实际执行 scan 的函数签名应该是 scan0(cursor, pattern, count, typ)。
现在的解析命令行逻辑过于晦涩, 可以参考一下 execSet 的实现

argsNum := len(args)
if argsNum < 3 && argsNum > 5 {
return protocol.MakeArgNumErrReply("scan")
}

if argsNum == 1 {
return scanWithArg(db, args, false)
} else if argsNum == 3 {
firstArg := strings.ToLower(string(args[1]))
if firstArg == "match" {
return scanWithArg(db, args, true)
} else if firstArg == "count" {
return scanWithArg(db, args, false)
} else {
return protocol.MakeSyntaxErrReply()
}
} else if argsNum == 5 {
return scanWithArg(db, args, true)
}
return protocol.MakeNullBulkReply()
}

func scanWithArg(db *DB, args [][]byte, match bool) redis.Reply {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

函数签名改成: execScan0(cursor, pattern, count, typ)

result := make([]redis.Reply, 2)
var m [][]byte
var scanReturnKeys []string
var nextCursor int
cursor, err := strconv.Atoi(string(args[0]))
if err != nil {
return &protocol.SyntaxErrReply{}
}

if len(args) == 1 {
scanReturnKeys, nextCursor = db.data.ScanKeys(cursor, 10, "*")
} else if !match {
count, err := strconv.Atoi(string(args[2]))
if err != nil || count < 0 {
return &protocol.SyntaxErrReply{}
}
scanReturnKeys, nextCursor = db.data.ScanKeys(cursor, count, "*")
} else {
commandAndArgs := parseScanCommandArgs(args)
numOfcommandAndArgs := len(commandAndArgs)
if numOfcommandAndArgs == 1 {
//if there is only the match parameter, then count defaults to 10
scanReturnKeys, nextCursor = db.data.ScanKeys(cursor, 10, commandAndArgs["match"])
} else if numOfcommandAndArgs == 2 {
count, err := strconv.Atoi(commandAndArgs["count"])
if err != nil || count <= 0 {
return &protocol.SyntaxErrReply{}
}
scanReturnKeys, nextCursor = db.data.ScanKeys(cursor, count, commandAndArgs["match"])
} else {
return &protocol.SyntaxErrReply{}
}
}
nextCursorTobyte := strconv.FormatInt(int64(nextCursor), 10)
result[0] = protocol.MakeBulkReply([]byte(nextCursorTobyte))
for _, s := range scanReturnKeys {
if s != "" {
m = append(m, []byte(s))
}
}
result[1] = protocol.MakeMultiBulkReply(m)
return protocol.MakeMultiRawReply(result)
}

// parseScanCommandArgs parse the parameters of the scan args
func parseScanCommandArgs(args [][]byte) map[string]string {
arg := make(map[string]string)
argNum := len(args)
if argNum == 3 {
firstCommand := strings.ToLower(string(args[1]))
arg[firstCommand] = string(args[2])
} else if argNum == 5 {
firstCommand := strings.ToLower(string(args[1]))
arg[firstCommand] = string(args[2])
secondCommand := strings.ToLower(string(args[3]))
arg[secondCommand] = string(args[4])
}
return arg
}

func init() {
registerCommand("Del", execDel, writeAllKeys, undoDel, -2, flagWrite).
attachCommandExtra([]string{redisFlagWrite}, 1, -1, 1)
Expand Down Expand Up @@ -443,4 +528,6 @@ func init() {
attachCommandExtra([]string{redisFlagWrite, redisFlagFast}, 1, 1, 1)
registerCommand("Keys", execKeys, noPrepare, nil, 2, flagReadOnly).
attachCommandExtra([]string{redisFlagReadonly, redisFlagSortForScript}, 1, 1, 1)
registerCommand("Scan", execScan, readAllKeys, nil, -2, flagReadOnly).
attachCommandExtra([]string{redisFlagReadonly, redisFlagSortForScript}, 1, 1, 1)
}
54 changes: 54 additions & 0 deletions datastruct/dict/concurrent.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package dict

import (
"github.com/hdt3213/godis/lib/wildcard"
"math"
"math/rand"
"sort"
Expand Down Expand Up @@ -435,3 +436,56 @@ func (dict *ConcurrentDict) RWUnLocks(writeKeys []string, readKeys []string) {
}
}
}

// ScanKeys iteratively output all keys in the current db
func (dict *ConcurrentDict) ScanKeys(cursor, count int, matchKey string) ([]string, int) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

matchKey -> pattern

nextCursor := 0
size := dict.Len()
result := make([]string, count)
r := make(map[string]struct{})
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

不要使用过于简单的变量名

if count >= size {
return dict.Keys(), nextCursor
}
remainingKeys := dict.table[cursor:]
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

table 中取出来的是 shard, 为啥起名叫 remainingKeys?

i := 0
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

直接用 len(r) 不就行了

for tableK, s := range remainingKeys {
s.mutex.RLock()
f := func(m map[string]struct{}) bool {
defer s.mutex.RUnlock()
for key, _ := range s.m {
if key != "" {
if matchKey != "*" {
pattern, err := wildcard.CompilePattern(matchKey)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CompilePattern 执行一次就可以了。。

if err != nil {
return false
}
if pattern.IsMatch(key) {
m[key] = struct{}{}
i++
}
} else {
m[key] = struct{}{}
i++
}
}
if count <= i {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

scan 命令不保证返回的元素数一定等于 count 参数,但是保证从遍历开始直到完整遍历结束期间, 一直存在于数据集内的所有元素都会被返回。如果到了 count 就中止的话,当前shard 中可能有一些 key 在遍历期间一直存在但因为遍历中止未被返回。

所以应完整遍历shard, 当 len(result) >= count 后返回即可。

for _, shard := range shards {
    for k, _ := range shard.m {
          result.add(key)
    } 
    if len(result) >= count {
          break
    }
} 

return false
}
}
return true
}
nextCursor = tableK + cursor + 1
if !f(r) {
break
}
}
j := 0
for k := range r {
result[j] = k
j++
}
if nextCursor >= dict.shardCount {
nextCursor = 0
}
return result, nextCursor
}
30 changes: 29 additions & 1 deletion datastruct/dict/concurrent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,7 @@ func TestConcurrentRemoveWithLock(t *testing.T) {
}
}

//change t.Error remove->forEach
// change t.Error remove->forEach
func TestConcurrentForEach(t *testing.T) {
d := MakeConcurrent(0)
size := 100
Expand Down Expand Up @@ -524,3 +524,31 @@ func TestConcurrentDict_Keys(t *testing.T) {
t.Errorf("expect %d keys, actual: %d", size, len(d.Keys()))
}
}

func TestScanKeys(t *testing.T) {
d := MakeConcurrent(0)
count := 100
for i := 0; i < count; i++ {
key := "k" + strconv.Itoa(i)
d.Put(key, i)
}
cursor := 0
matchKey := "*"
c := 20
returnKeys, _ := d.ScanKeys(cursor, c, matchKey)
if len(returnKeys) != c {
t.Errorf("scan command count error: %d, should be %d ", len(returnKeys), c)
}
matchKey = "k*"
returnKeys, _ = d.ScanKeys(cursor, c, matchKey)
if len(returnKeys) != c {
t.Errorf("scan command count error: %d, should be %d ", len(returnKeys), c)
}
matchKey = "s*"
returnKeys, _ = d.ScanKeys(cursor, c, matchKey)
for _, key := range returnKeys {
if key != "" {
t.Errorf("returnKeys should be empty")
}
}
}
1 change: 1 addition & 0 deletions datastruct/dict/dict.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ type Dict interface {
RandomKeys(limit int) []string
RandomDistinctKeys(limit int) []string
Clear()
ScanKeys(cursor, count int, matchKey string) ([]string, int)
}
22 changes: 22 additions & 0 deletions datastruct/dict/simple.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,25 @@ func (dict *SimpleDict) RandomDistinctKeys(limit int) []string {
func (dict *SimpleDict) Clear() {
*dict = *MakeSimple()
}

// ScanKeys randomly returns keys of the given number, may contain duplicated key
func (dict *SimpleDict) ScanKeys(cursor, count int, matchKey string) ([]string, int) {
nextCursor := 0
size := dict.Len()
if count >= size {
return dict.Keys(), nextCursor
}

if count == 0 {
count = 10
}

result := make([]string, count)
for i := cursor; i < count; i++ {
for k := range dict.m {
result[i] = k
}
}

return result, nextCursor
}
29 changes: 29 additions & 0 deletions datastruct/dict/simple_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package dict

import (
"github.com/hdt3213/godis/lib/utils"
"github.com/hdt3213/godis/lib/wildcard"
"sort"
"testing"
)
Expand Down Expand Up @@ -53,3 +54,31 @@ func TestSimpleDict_PutIfExists(t *testing.T) {
return
}
}

func TestSimpleDict_ScanKeys(t *testing.T) {
count := 1
d := MakeSimple()
for i := 0; i < 5; i++ {
value := utils.RandString(5)
key := "k" + value
ret := d.PutIfExists(key, value)
if ret != 0 {
t.Error("expect 0")
return
}
}
result, _ := d.ScanKeys(0, count, "k*")

pattern, err := wildcard.CompilePattern("k*")
if err != nil {
t.Error(err)
return
}

for _, s := range result {
if !pattern.IsMatch(s) {
t.Error("Scan command execution error")
}
}

}