Merge tag '6.2.1' into unstable

Former-commit-id: bfed57e3e0
This commit is contained in:
John Sully committed 2021-05-19 02:59:48 +00:00
commit fe8efa916b
298 files changed
+30298 -10182

No files matched your search

Binary file not shown.
+5
View File
@@ -0,0 +1,5 @@
# Minimal configuration for testing.
always-show-logo yes
daemonize no
pidfile /var/run/redis.pid
loglevel verbose
+1 -1
View File
@@ -21,7 +21,7 @@ proc get_cluster_nodes id {
pong_recv [lindex $args 5] \
config_epoch [lindex $args 6] \
linkstate [lindex $args 7] \
slots [lrange $args 8 -1] \
slots [lrange $args 8 end] \
]
lappend nodes $node
}
+7
View File
@@ -172,3 +172,10 @@ test "Verify slaves consistency" {
}
assert {$verified_masters >= 5}
}
test "Dump sanitization was skipped for migrations" {
set verified_masters 0
foreach_redis_id id {
assert {[RI $id dump_payload_sanitizations] == 0}
}
}
+45
View File
@@ -0,0 +1,45 @@
# Check cluster info stats
source "../tests/includes/init-tests.tcl"
test "Create a primary with a replica" {
create_cluster 2 0
}
test "Cluster should start ok" {
assert_cluster_state ok
}
set primary1 [Rn 0]
set primary2 [Rn 1]
proc cmdstat {instace cmd} {
return [cmdrstat $cmd $instace]
}
proc errorstat {instace cmd} {
return [errorrstat $cmd $instace]
}
test "errorstats: rejected call due to MOVED Redirection" {
$primary1 config resetstat
$primary2 config resetstat
assert_match {} [errorstat $primary1 MOVED]
assert_match {} [errorstat $primary2 MOVED]
# we know that one will have a MOVED reply and one will succeed
catch {$primary1 set key b} replyP1
catch {$primary2 set key b} replyP2
# sort servers so we know which one failed
if {$replyP1 eq {OK}} {
assert_match {MOVED*} $replyP2
set pok $primary1
set perr $primary2
} else {
assert_match {MOVED*} $replyP1
set pok $primary2
set perr $primary1
}
assert_match {} [errorstat $pok MOVED]
assert_match {*count=1*} [errorstat $perr MOVED]
assert_match {*calls=0,*,rejected_calls=1,failed_calls=0} [cmdstat $perr set]
}
@@ -0,0 +1,62 @@
# Optimize CLUSTER NODES command by generating all nodes slot topology firstly
source "../tests/includes/init-tests.tcl"
proc cluster_allocate_with_continuous_slots {n} {
set slot 16383
set avg [expr ($slot+1) / $n]
while {$slot >= 0} {
set node [expr $slot/$avg >= $n ? $n-1 : $slot/$avg]
lappend slots_$node $slot
incr slot -1
}
for {set j 0} {$j < $n} {incr j} {
R $j cluster addslots {*}[set slots_${j}]
}
}
proc cluster_create_with_continuous_slots {masters slaves} {
cluster_allocate_with_continuous_slots $masters
if {$slaves} {
cluster_allocate_slaves $masters $slaves
}
assert_cluster_state ok
}
test "Create a 2 nodes cluster" {
cluster_create_with_continuous_slots 2 2
}
test "Cluster should start ok" {
assert_cluster_state ok
}
set master1 [Rn 0]
set master2 [Rn 1]
test "Continuous slots distribution" {
assert_match "* 0-8191*" [$master1 CLUSTER NODES]
assert_match "* 8192-16383*" [$master2 CLUSTER NODES]
$master1 CLUSTER DELSLOTS 4096
assert_match "* 0-4095 4097-8191*" [$master1 CLUSTER NODES]
$master2 CLUSTER DELSLOTS 12288
assert_match "* 8192-12287 12289-16383*" [$master2 CLUSTER NODES]
}
test "Discontinuous slots distribution" {
# Remove middle slots
$master1 CLUSTER DELSLOTS 4092 4094
assert_match "* 0-4091 4093 4095 4097-8191*" [$master1 CLUSTER NODES]
$master2 CLUSTER DELSLOTS 12284 12286
assert_match "* 8192-12283 12285 12287 12289-16383*" [$master2 CLUSTER NODES]
# Remove head slots
$master1 CLUSTER DELSLOTS 0 2
assert_match "* 1 3-4091 4093 4095 4097-8191*" [$master1 CLUSTER NODES]
# Remove tail slots
$master2 CLUSTER DELSLOTS 16380 16382 16383
assert_match "* 8192-12283 12285 12287 12289-16379 16381*" [$master2 CLUSTER NODES]
}
+49 -12
View File
@@ -24,9 +24,12 @@ set ::simulate_error 0
set ::failed 0
set ::sentinel_instances {}
set ::redis_instances {}
set ::global_config {}
set ::sentinel_base_port 20000
set ::redis_base_port 30000
set ::redis_port_count 1024
set ::host "127.0.0.1"
set ::leaked_fds_file [file normalize "tmp/leaked_fds.txt"]
set ::pids {} ; # We kill everything at exit
set ::dirs {} ; # We remove all the temp dirs at exit
set ::run_matching {} ; # If non empty, only tests matching pattern are run.
@@ -58,10 +61,9 @@ proc exec_instance {type dirname cfgfile} {
}
# Spawn a redis or sentinel instance, depending on 'type'.
proc spawn_instance {type base_port count {conf {}}} {
proc spawn_instance {type base_port count {conf {}} {base_conf_file ""}} {
for {set j 0} {$j < $count} {incr j} {
set port [find_available_port $base_port $::redis_port_count]
# Create a directory for this instance.
set dirname "${type}_${j}"
lappend ::dirs $dirname
@@ -70,14 +72,22 @@ proc spawn_instance {type base_port count {conf {}}} {
# Write the instance config file.
set cfgfile [file join $dirname $type.conf]
set cfg [open $cfgfile w]
if {$base_conf_file ne ""} {
file copy -- $base_conf_file $cfgfile
set cfg [open $cfgfile a+]
} else {
set cfg [open $cfgfile w]
}
if {$::tls} {
puts $cfg "tls-port $port"
puts $cfg "tls-replication yes"
puts $cfg "tls-cluster yes"
puts $cfg "port 0"
puts $cfg [format "tls-cert-file %s/../../tls/redis.crt" [pwd]]
puts $cfg [format "tls-key-file %s/../../tls/redis.key" [pwd]]
puts $cfg [format "tls-cert-file %s/../../tls/server.crt" [pwd]]
puts $cfg [format "tls-key-file %s/../../tls/server.key" [pwd]]
puts $cfg [format "tls-client-cert-file %s/../../tls/client.crt" [pwd]]
puts $cfg [format "tls-client-key-file %s/../../tls/client.key" [pwd]]
puts $cfg [format "tls-dh-params-file %s/../../tls/redis.dh" [pwd]]
puts $cfg [format "tls-ca-cert-file %s/../../tls/ca.crt" [pwd]]
puts $cfg "loglevel debug"
@@ -90,6 +100,9 @@ proc spawn_instance {type base_port count {conf {}}} {
foreach directive $conf {
puts $cfg $directive
}
dict for {name val} $::global_config {
puts $cfg "$name $val"
}
close $cfg
# Finally exec it and remember the pid for later cleanup.
@@ -117,18 +130,18 @@ proc spawn_instance {type base_port count {conf {}}} {
}
# Check availability finally
if {[server_is_up 127.0.0.1 $port 100] == 0} {
if {[server_is_up $::host $port 100] == 0} {
set logfile [file join $dirname log.txt]
puts [exec tail $logfile]
abort_sentinel_test "Problems starting $type #$j: ping timeout, maybe server start failed, check $logfile"
}
# Push the instance into the right list
set link [redis 127.0.0.1 $port 0 $::tls]
set link [redis $::host $port 0 $::tls]
$link reconnect 1
lappend ::${type}_instances [list \
pid $pid \
host 127.0.0.1 \
host $::host \
port $port \
link $link \
]
@@ -155,7 +168,7 @@ proc log_crashes {} {
set logs [glob */err.txt]
foreach log $logs {
set res [find_valgrind_errors $log]
set res [find_valgrind_errors $log true]
if {$res != ""} {
puts $res
incr ::failed
@@ -173,6 +186,8 @@ proc is_alive pid {
proc stop_instance pid {
catch {exec kill $pid}
# Node might have been stopped in the test
catch {exec kill -SIGCONT $pid}
if {$::valgrind} {
set max_wait 60000
} else {
@@ -230,13 +245,20 @@ proc parse_options {} {
set ::simulate_error 1
} elseif {$opt eq {--valgrind}} {
set ::valgrind 1
} elseif {$opt eq {--host}} {
incr j
set ::host ${val}
} elseif {$opt eq {--tls}} {
package require tls 1.6
::tls::init \
-cafile "$::tlsdir/ca.crt" \
-certfile "$::tlsdir/redis.crt" \
-keyfile "$::tlsdir/redis.key"
-certfile "$::tlsdir/client.crt" \
-keyfile "$::tlsdir/client.key"
set ::tls 1
} elseif {$opt eq {--config}} {
set val2 [lindex $::argv [expr $j+2]]
dict set ::global_config $val $val2
incr j 2
} elseif {$opt eq "--help"} {
puts "--single <pattern> Only runs tests specified by pattern."
puts "--dont-clean Keep log files on exit."
@@ -244,6 +266,8 @@ proc parse_options {} {
puts "--fail Simulate a test failure."
puts "--valgrind Run with valgrind."
puts "--tls Run tests in TLS mode."
puts "--host <host> Use hostname instead of 127.0.0.1."
puts "--config <k> <v> Extra config argument(s)."
puts "--help Shows this help."
exit 0
} else {
@@ -391,6 +415,11 @@ proc check_leaks instance_types {
proc run_tests {} {
set tests [lsort [glob ../tests/*]]
foreach test $tests {
# Remove leaked_fds file before starting
if {$::leaked_fds_file != "" && [file exists $::leaked_fds_file]} {
file delete $::leaked_fds_file
}
if {$::run_matching ne {} && [string match $::run_matching $test] == 0} {
continue
}
@@ -398,12 +427,20 @@ proc run_tests {} {
puts [colorstr yellow "Testing unit: [lindex [file split $test] end]"]
source $test
check_leaks {redis sentinel}
# Check if a leaked fds file was created and abort the test.
if {$::leaked_fds_file != "" && [file exists $::leaked_fds_file]} {
puts [colorstr red "ERROR: Sentinel has leaked fds to scripts:"]
puts [exec cat $::leaked_fds_file]
puts "----"
incr ::failed
}
}
}
# Print a message and exists with 0 / 1 according to zero or more failures.
proc end_tests {} {
if {$::failed == 0} {
if {$::failed == 0 } {
puts "GOOD! No errors."
exit 0
} else {
+11
View File
@@ -296,4 +296,15 @@ tags {"aof"} {
assert_equal 3 [$client scard testkey]
}
}
start_server {overrides {appendonly {yes} appendfilename {appendonly.aof}}} {
test {GETEX should not append to AOF} {
set aof [file join [lindex [r config get dir] 1] appendonly.aof]
r set foo bar
set before [file size $aof]
r getex foo
set after [file size $aof]
assert_equal $before $after
}
}
}
+201
View File
@@ -0,0 +1,201 @@
# tests of corrupt ziplist payload with valid CRC
tags {"dump" "corruption"} {
proc generate_collections {suffix elements} {
set rd [redis_deferring_client]
for {set j 0} {$j < $elements} {incr j} {
# add both string values and integers
if {$j % 2 == 0} {set val $j} else {set val "_$j"}
$rd hset hash$suffix $j $val
$rd lpush list$suffix $val
$rd zadd zset$suffix $j $val
$rd sadd set$suffix $val
$rd xadd stream$suffix * item 1 value $val
}
for {set j 0} {$j < $elements * 5} {incr j} {
$rd read ; # Discard replies
}
$rd close
}
# generate keys with various types and encodings
proc generate_types {} {
r config set list-max-ziplist-size 5
r config set hash-max-ziplist-entries 5
r config set zset-max-ziplist-entries 5
r config set stream-node-max-entries 5
# create small (ziplist / listpack encoded) objects with 3 items
generate_collections "" 3
# add some metadata to the stream
r xgroup create stream mygroup 0
set records [r xreadgroup GROUP mygroup Alice COUNT 2 STREAMS stream >]
r xdel stream [lindex [lindex [lindex [lindex $records 0] 1] 1] 0]
r xack stream mygroup [lindex [lindex [lindex [lindex $records 0] 1] 0] 0]
# create other non-collection types
r incr int
r set string str
# create bigger objects with 10 items (more than a single ziplist / listpack)
generate_collections big 10
# make sure our big stream also has a listpack record that has different
# field names than the master recored
r xadd streambig * item 1 value 1
r xadd streambig * item 1 unique value
}
proc corrupt_payload {payload} {
set len [string length $payload]
set count 1 ;# usually corrupt only one byte
if {rand() > 0.9} { set count 2 }
while { $count > 0 } {
set idx [expr {int(rand() * $len)}]
set ch [binary format c [expr {int(rand()*255)}]]
set payload [string replace $payload $idx $idx $ch]
incr count -1
}
return $payload
}
# fuzzy tester for corrupt RESTORE payloads
# valgrind will make sure there were no leaks in the rdb loader error handling code
foreach sanitize_dump {no yes} {
if {$::accurate} {
set min_duration [expr {60 * 10}] ;# run at least 10 minutes
set min_cycles 1000 ;# run at least 1k cycles (max 16 minutes)
} else {
set min_duration 10 ; # run at least 10 seconds
set min_cycles 10 ; # run at least 10 cycles
}
# Don't execute this on FreeBSD due to a yet-undiscovered memory issue
# which causes tclsh to bloat.
if {[exec uname] == "FreeBSD"} {
set min_cycles 1
set min_duration 1
}
test "Fuzzer corrupt restore payloads - sanitize_dump: $sanitize_dump" {
if {$min_duration * 2 > $::timeout} {
fail "insufficient timeout"
}
# start a server, fill with data and save an RDB file once (avoid re-save)
start_server [list overrides [list "save" "" use-exit-on-panic yes crash-memcheck-enabled no loglevel verbose] ] {
set stdout [srv 0 stdout]
r config set sanitize-dump-payload $sanitize_dump
r debug set-skip-checksum-validation 1
set start_time [clock seconds]
generate_types
r save
set cycle 0
set stat_terminated_in_restore 0
set stat_terminated_in_traffic 0
set stat_terminated_by_signal 0
set stat_successful_restore 0
set stat_rejected_restore 0
set stat_traffic_commands_sent 0
# repeatedly DUMP a random key, corrupt it and try RESTORE into a new key
while true {
set k [r randomkey]
set dump [r dump $k]
set dump [corrupt_payload $dump]
set printable_dump [string2printable $dump]
set restore_failed false
set report_and_restart false
set sent {}
# RESTORE can fail, but hopefully not terminate
if { [catch { r restore "_$k" 0 $dump REPLACE } err] } {
set restore_failed true
# skip if return failed with an error response.
if {[string match "ERR*" $err]} {
incr stat_rejected_restore
} else {
set report_and_restart true
incr stat_terminated_in_restore
write_log_line 0 "corrupt payload: $printable_dump"
if {$sanitize_dump == 1} {
puts "Server crashed in RESTORE with payload: $printable_dump"
}
}
} else {
r ping ;# an attempt to check if the server didn't terminate (this will throw an error that will terminate the tests)
}
set print_commands false
if {!$restore_failed} {
# if RESTORE didn't fail or terminate, run some random traffic on the new key
incr stat_successful_restore
if { [ catch {
set sent [generate_fuzzy_traffic_on_key "_$k" 1] ;# traffic for 1 second
incr stat_traffic_commands_sent [llength $sent]
r del "_$k" ;# in case the server terminated, here's where we'll detect it.
} err ] } {
# if the server terminated update stats and restart it
set report_and_restart true
incr stat_terminated_in_traffic
set by_signal [count_log_message 0 "crashed by signal"]
incr stat_terminated_by_signal $by_signal
if {$by_signal != 0 || $sanitize_dump == 1 } {
puts "Server crashed (by signal: $by_signal), with payload: $printable_dump"
set print_commands true
}
}
}
# check valgrind report for invalid reads after each RESTORE
# payload so that we have a report that is easier to reproduce
set valgrind_errors [find_valgrind_errors [srv 0 stderr] false]
if {$valgrind_errors != ""} {
puts "valgrind found an issue for payload: $printable_dump"
set report_and_restart true
set print_commands true
}
if {$report_and_restart} {
if {$print_commands} {
puts "violating commands:"
foreach cmd $sent {
foreach arg $cmd {
puts -nonewline "[string2printable $arg] "
}
puts ""
}
}
# restart the server and re-apply debug configuration
write_log_line 0 "corrupt payload: $printable_dump"
restart_server 0 true true
r config set sanitize-dump-payload $sanitize_dump
r debug set-skip-checksum-validation 1
}
incr cycle
if { ([clock seconds]-$start_time) >= $min_duration && $cycle >= $min_cycles} {
break
}
}
if {$::verbose} {
puts "Done $cycle cycles in [expr {[clock seconds]-$start_time}] seconds."
puts "RESTORE: successful: $stat_successful_restore, rejected: $stat_rejected_restore"
puts "Total commands sent in traffic: $stat_traffic_commands_sent, crashes during traffic: $stat_terminated_in_traffic ($stat_terminated_by_signal by signal)."
}
}
# if we run sanitization we never expect the server to crash at runtime
if { $sanitize_dump == 1} {
assert_equal $stat_terminated_in_restore 0
assert_equal $stat_terminated_in_traffic 0
}
# make sure all terminations where due to assertion and not a SIGSEGV
assert_equal $stat_terminated_by_signal 0
}
}
} ;# tags
+522
View File
@@ -0,0 +1,522 @@
# tests of corrupt ziplist payload with valid CRC
# * setting crash-memcheck-enabled to no to avoid issues with valgrind
# * setting use-exit-on-panic to yes so that valgrind can search for leaks
# * settng debug set-skip-checksum-validation to 1 on some tests for which we
# didn't bother to fake a valid checksum
# * some tests set sanitize-dump-payload to no and some to yet, depending on
# what we want to test
tags {"dump" "corruption"} {
set corrupt_payload_7445 "\x0E\x01\x1D\x1D\x00\x00\x00\x16\x00\x00\x00\x03\x00\x00\x04\x43\x43\x43\x43\x06\x04\x42\x42\x42\x42\x06\x3F\x41\x41\x41\x41\xFF\x09\x00\x88\xA5\xCA\xA8\xC5\x41\xF4\x35"
test {corrupt payload: #7445 - with sanitize} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload yes
catch {
r restore key 0 $corrupt_payload_7445
} err
assert_match "*Bad data format*" $err
verify_log_message 0 "*integrity check failed*" 0
}
}
test {corrupt payload: #7445 - without sanitize - 1} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r restore key 0 $corrupt_payload_7445
catch {r lindex key 2}
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: #7445 - without sanitize - 2} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r restore key 0 $corrupt_payload_7445
catch {r lset key 2 "BEEF"}
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: hash with valid zip list header, invalid entry len} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r restore key 0 "\x0D\x1B\x1B\x00\x00\x00\x16\x00\x00\x00\x04\x00\x00\x02\x61\x00\x04\x02\x62\x00\x04\x14\x63\x00\x04\x02\x64\x00\xFF\x09\x00\xD9\x10\x54\x92\x15\xF5\x5F\x52"
r config set hash-max-ziplist-entries 1
catch {r hset key b b}
verify_log_message 0 "*zipEntrySafe*" 0
}
}
test {corrupt payload: invalid zlbytes header} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
catch {
r restore key 0 "\x0D\x1B\x25\x00\x00\x00\x16\x00\x00\x00\x04\x00\x00\x02\x61\x00\x04\x02\x62\x00\x04\x02\x63\x00\x04\x02\x64\x00\xFF\x09\x00\xB7\xF7\x6E\x9F\x43\x43\x14\xC6"
} err
assert_match "*Bad data format*" $err
}
}
test {corrupt payload: valid zipped hash header, dup records} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r restore key 0 "\x0D\x1B\x1B\x00\x00\x00\x16\x00\x00\x00\x04\x00\x00\x02\x61\x00\x04\x02\x62\x00\x04\x02\x61\x00\x04\x02\x64\x00\xFF\x09\x00\xA1\x98\x36\x78\xCC\x8E\x93\x2E"
r config set hash-max-ziplist-entries 1
# cause an assertion when converting to hash table
catch {r hset key b b}
verify_log_message 0 "*ziplist with dup elements dump*" 0
}
}
test {corrupt payload: quicklist big ziplist prev len} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r restore key 0 "\x0E\x01\x13\x13\x00\x00\x00\x0E\x00\x00\x00\x02\x00\x00\x02\x61\x00\x0E\x02\x62\x00\xFF\x09\x00\x49\x97\x30\xB2\x0D\xA1\xED\xAA"
catch {r lindex key -2}
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: quicklist small ziplist prev len} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload yes
catch {
r restore key 0 "\x0E\x01\x13\x13\x00\x00\x00\x0E\x00\x00\x00\x02\x00\x00\x02\x61\x00\x02\x02\x62\x00\xFF\x09\x00\xC7\x71\x03\x97\x07\x75\xB0\x63"
} err
assert_match "*Bad data format*" $err
verify_log_message 0 "*integrity check failed*" 0
}
}
test {corrupt payload: quicklist ziplist wrong count} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r restore key 0 "\x0E\x01\x13\x13\x00\x00\x00\x0E\x00\x00\x00\x03\x00\x00\x02\x61\x00\x04\x02\x62\x00\xFF\x09\x00\x4D\xE2\x0A\x2F\x08\x25\xDF\x91"
# we'll be able to push, but iterating on the list will assert
r lpush key header
r rpush key footer
catch { [r lrange key -1 -1] }
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: #3080 - quicklist} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
catch {
r RESTORE key 0 "\x0E\x01\x80\x00\x00\x00\x10\x41\x41\x41\x41\x41\x41\x41\x41\x02\x00\x00\x80\x41\x41\x41\x41\x07\x00\x03\xC7\x1D\xEF\x54\x68\xCC\xF3"
r DUMP key ;# DUMP was used in the original issue, but now even with shallow sanitization restore safely fails, so this is dead code
} err
assert_match "*Bad data format*" $err
verify_log_message 0 "*integrity check failed*" 0
}
}
test {corrupt payload: #3080 - ziplist} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
# shallow sanitization is enough for restore to safely reject the payload with wrong size
r config set sanitize-dump-payload no
catch {
r RESTORE key 0 "\x0A\x80\x00\x00\x00\x10\x41\x41\x41\x41\x41\x41\x41\x41\x02\x00\x00\x80\x41\x41\x41\x41\x07\x00\x39\x5B\x49\xE0\xC1\xC6\xDD\x76"
} err
assert_match "*Bad data format*" $err
verify_log_message 0 "*integrity check failed*" 0
}
}
test {corrupt payload: load corrupted rdb with no CRC - #3505} {
set server_path [tmpdir "server.rdb-corruption-test"]
exec cp tests/assets/corrupt_ziplist.rdb $server_path
set srv [start_server [list overrides [list "dir" $server_path "dbfilename" "corrupt_ziplist.rdb" loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no sanitize-dump-payload no]]]
# wait for termination
wait_for_condition 100 50 {
! [is_alive $srv]
} else {
fail "rdb loading didn't fail"
}
set stdout [dict get $srv stdout]
assert_equal [count_message_lines $stdout "Terminating server after rdb file reading failure."] 1
assert_lessthan 1 [count_message_lines $stdout "integrity check failed"]
kill_server $srv ;# let valgrind look for issues
}
test {corrupt payload: listpack invalid size header} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
catch {
r restore key 0 "\x0F\x01\x10\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x02\x40\x55\x5F\x00\x00\x00\x0F\x00\x01\x01\x00\x01\x02\x01\x88\x31\x00\x00\x00\x00\x00\x00\x00\x09\x88\x32\x00\x00\x00\x00\x00\x00\x00\x09\x00\x01\x00\x01\x00\x01\x00\x01\x02\x02\x88\x31\x00\x00\x00\x00\x00\x00\x00\x09\x88\x61\x00\x00\x00\x00\x00\x00\x00\x09\x88\x32\x00\x00\x00\x00\x00\x00\x00\x09\x88\x62\x00\x00\x00\x00\x00\x00\x00\x09\x08\x01\xFF\x0A\x01\x00\x00\x09\x00\x45\x91\x0A\x87\x2F\xA5\xF9\x2E"
} err
assert_match "*Bad data format*" $err
verify_log_message 0 "*Stream listpack integrity check failed*" 0
}
}
test {corrupt payload: listpack too long entry len} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r restore key 0 "\x0F\x01\x10\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x02\x40\x55\x55\x00\x00\x00\x0F\x00\x01\x01\x00\x01\x02\x01\x88\x31\x00\x00\x00\x00\x00\x00\x00\x09\x88\x32\x00\x00\x00\x00\x00\x00\x00\x09\x00\x01\x00\x01\x00\x01\x00\x01\x02\x02\x89\x31\x00\x00\x00\x00\x00\x00\x00\x09\x88\x61\x00\x00\x00\x00\x00\x00\x00\x09\x88\x32\x00\x00\x00\x00\x00\x00\x00\x09\x88\x62\x00\x00\x00\x00\x00\x00\x00\x09\x08\x01\xFF\x0A\x01\x00\x00\x09\x00\x40\x63\xC9\x37\x03\xA2\xE5\x68"
catch {
r xinfo stream key full
} err
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: listpack very long entry len} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r restore key 0 "\x0F\x01\x10\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x02\x40\x55\x55\x00\x00\x00\x0F\x00\x01\x01\x00\x01\x02\x01\x88\x31\x00\x00\x00\x00\x00\x00\x00\x09\x88\x32\x00\x00\x00\x00\x00\x00\x00\x09\x00\x01\x00\x01\x00\x01\x00\x01\x02\x02\x88\x31\x00\x00\x00\x00\x00\x00\x00\x09\x88\x61\x00\x00\x00\x00\x00\x00\x00\x09\x88\x32\x00\x00\x00\x00\x00\x00\x00\x09\x9C\x62\x00\x00\x00\x00\x00\x00\x00\x09\x08\x01\xFF\x0A\x01\x00\x00\x09\x00\x63\x6F\x42\x8E\x7C\xB5\xA2\x9D"
catch {
r xinfo stream key full
} err
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: listpack too long entry prev len} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload yes
catch {
r restore key 0 "\x0F\x01\x10\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x02\x40\x55\x55\x00\x00\x00\x0F\x00\x01\x01\x00\x15\x02\x01\x88\x31\x00\x00\x00\x00\x00\x00\x00\x09\x88\x32\x00\x00\x00\x00\x00\x00\x00\x09\x00\x01\x00\x01\x00\x01\x00\x01\x02\x02\x88\x31\x00\x00\x00\x00\x00\x00\x00\x09\x88\x61\x00\x00\x00\x00\x00\x00\x00\x09\x88\x32\x00\x00\x00\x00\x00\x00\x00\x09\x88\x62\x00\x00\x00\x00\x00\x00\x00\x09\x08\x01\xFF\x0A\x01\x00\x00\x09\x00\x06\xFB\x44\x24\x0A\x8E\x75\xEA"
} err
assert_match "*Bad data format*" $err
verify_log_message 0 "*Stream listpack integrity check failed*" 0
}
}
test {corrupt payload: hash ziplist with duplicate records} {
# when we do perform full sanitization, we expect duplicate records to fail the restore
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload yes
r debug set-skip-checksum-validation 1
catch { r RESTORE _hash 0 "\x0D\x3D\x3D\x00\x00\x00\x3A\x00\x00\x00\x14\x13\x00\xF5\x02\xF5\x02\xF2\x02\x53\x5F\x31\x04\xF3\x02\xF3\x02\xF7\x02\xF7\x02\xF8\x02\x02\x5F\x37\x04\xF1\x02\xF1\x02\xF6\x02\x02\x5F\x35\x04\xF4\x02\x02\x5F\x33\x04\xFA\x02\x02\x5F\x39\x04\xF9\x02\xF9\xFF\x09\x00\xB5\x48\xDE\x62\x31\xD0\xE5\x63" } err
assert_match "*Bad data format*" $err
}
}
test {corrupt payload: hash ziplist uneven record count} {
# when we do perform full sanitization, we expect duplicate records to fail the restore
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload yes
r debug set-skip-checksum-validation 1
catch { r RESTORE _hash 0 "\r\x1b\x1b\x00\x00\x00\x16\x00\x00\x00\x04\x00\x00\x02a\x00\x04\x02b\x00\x04\x02a\x00\x04\x02d\x00\xff\t\x00\xa1\x98\x36x\xcc\x8e\x93\x2e" } err
assert_match "*Bad data format*" $err
}
}
test {corrupt payload: hash dupliacte records} {
# when we do perform full sanitization, we expect duplicate records to fail the restore
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload yes
r debug set-skip-checksum-validation 1
catch { r RESTORE _hash 0 "\x04\x02\x01a\x01b\x01a\x01d\t\x00\xc6\x9c\xab\xbc\bk\x0c\x06" } err
assert_match "*Bad data format*" $err
}
}
test {corrupt payload: fuzzer findings - NPD in streamIteratorGetID} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
catch {
r RESTORE key 0 "\x0F\x01\x10\x00\x00\x01\x73\xBD\x68\x48\x71\x00\x00\x00\x00\x00\x00\x00\x00\x40\x42\x42\x00\x00\x00\x18\x00\x03\x01\x00\x01\x02\x01\x84\x69\x74\x65\x6D\x05\x85\x76\x61\x6C\x75\x65\x06\x00\x01\x02\x01\x00\x01\x00\x01\x01\x01\x00\x01\x05\x01\x02\x01\x00\x01\x01\x01\x01\x01\x82\x5F\x31\x03\x05\x01\x02\x01\x00\x01\x02\x01\x01\x01\x02\x01\x48\x01\xFF\x03\x81\x00\x00\x01\x73\xBD\x68\x48\x71\x02\x01\x07\x6D\x79\x67\x72\x6F\x75\x70\x81\x00\x00\x01\x73\xBD\x68\x48\x71\x00\x01\x00\x00\x01\x73\xBD\x68\x48\x71\x00\x00\x00\x00\x00\x00\x00\x00\x72\x48\x68\xBD\x73\x01\x00\x00\x01\x01\x05\x41\x6C\x69\x63\x65\x72\x48\x68\xBD\x73\x01\x00\x00\x01\x00\x00\x01\x73\xBD\x68\x48\x71\x00\x00\x00\x00\x00\x00\x00\x00\x09\x00\x80\xCD\xB0\xD5\x1A\xCE\xFF\x10"
r XREVRANGE key 725 233
}
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: fuzzer findings - listpack NPD on invalid stream} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
catch {
r RESTORE _stream 0 "\x0F\x01\x10\x00\x00\x01\x73\xDC\xB6\x6B\xF1\x00\x00\x00\x00\x00\x00\x00\x00\x40\x42\x42\x00\x00\x00\x18\x00\x03\x01\x00\x01\x02\x01\x84\x69\x74\x65\x6D\x05\x85\x76\x61\x6C\x75\x65\x06\x00\x01\x02\x01\x00\x01\x00\x01\x01\x01\x00\x01\x05\x01\x02\x01\x1F\x01\x00\x01\x01\x01\x6D\x5F\x31\x03\x05\x01\x02\x01\x29\x01\x00\x01\x01\x01\x02\x01\x05\x01\xFF\x03\x81\x00\x00\x01\x73\xDC\xB6\x6C\x1A\x00\x01\x07\x6D\x79\x67\x72\x6F\x75\x70\x81\x00\x00\x01\x73\xDC\xB6\x6B\xF1\x00\x01\x00\x00\x01\x73\xDC\xB6\x6B\xF1\x00\x00\x00\x00\x00\x00\x00\x00\x4B\x6C\xB6\xDC\x73\x01\x00\x00\x01\x01\x05\x41\x6C\x69\x63\x65\x3D\x6C\xB6\xDC\x73\x01\x00\x00\x01\x00\x00\x01\x73\xDC\xB6\x6B\xF1\x00\x00\x00\x00\x00\x00\x00\x00\x09\x00\xC7\x7D\x1C\xD7\x04\xFF\xE6\x9D"
r XREAD STREAMS _stream 519389898758
}
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: fuzzer findings - NPD in quicklistIndex} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
catch {
r RESTORE key 0 "\x0E\x01\x13\x13\x00\x00\x00\x10\x00\x00\x00\x03\x12\x00\xF3\x02\x02\x5F\x31\x04\xF1\xFF\x09\x00\xC9\x4B\x31\xFE\x61\xC0\x96\xFE"
r LSET key 290 290
}
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: fuzzer findings - invalid read in ziplistFind} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
catch {
r RESTORE key 0 "\x0D\x19\x19\x00\x00\x00\x16\x00\x00\x00\x06\x00\x00\xF1\x02\xF1\x02\xF2\x02\x02\x5F\x31\x04\x99\x02\xF3\xFF\x09\x00\xC5\xB8\x10\xC0\x8A\xF9\x16\xDF"
r HEXISTS key -688319650333
}
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: fuzzer findings - invalid ziplist encoding} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload yes
r debug set-skip-checksum-validation 1
catch {
r RESTORE _listbig 0 "\x0E\x02\x1B\x1B\x00\x00\x00\x16\x00\x00\x00\x05\x00\x00\x02\x5F\x39\x04\xF9\x02\x86\x5F\x37\x04\xF7\x02\x02\x5F\x35\xFF\x19\x19\x00\x00\x00\x16\x00\x00\x00\x05\x00\x00\xF5\x02\x02\x5F\x33\x04\xF3\x02\x02\x5F\x31\x04\xF1\xFF\x09\x00\x0C\xFC\x99\x2C\x23\x45\x15\x60"
} err
assert_match "*Bad data format*" $err
verify_log_message 0 "*integrity check failed*" 0
}
}
test {corrupt payload: fuzzer findings - hash crash} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload yes
r debug set-skip-checksum-validation 1
r RESTORE _hash 0 "\x0D\x19\x19\x00\x00\x00\x16\x00\x00\x00\x06\x00\x00\xF1\x02\xF1\x02\xF2\x02\x02\x5F\x31\x04\xF3\x02\xF3\xFF\x09\x00\x38\xB8\x10\xC0\x8A\xF9\x16\xDF"
r HSET _hash 394891450 1635910264
r HMGET _hash 887312884855
}
}
test {corrupt payload: fuzzer findings - uneven entry count in hash} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
r RESTORE _hashbig 0 "\x0D\x3D\x3D\x00\x00\x00\x38\x00\x00\x00\x14\x00\x00\xF2\x02\x02\x5F\x31\x04\x1C\x02\xF7\x02\xF1\x02\xF1\x02\xF5\x02\xF5\x02\xF4\x02\x02\x5F\x33\x04\xF6\x02\x02\x5F\x35\x04\xF8\x02\x02\x5F\x37\x04\xF9\x02\xF9\x02\xF3\x02\xF3\x02\xFA\x02\x02\x5F\x39\xFF\x09\x00\x73\xB7\x68\xC8\x97\x24\x8E\x88"
catch { r HSCAN _hashbig -250 }
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: fuzzer findings - invalid read in lzf_decompress} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
catch { r RESTORE _setbig 0 "\x02\x03\x02\x5F\x31\xC0\x02\xC3\x00\x09\x00\xE6\xDC\x76\x44\xFF\xEB\x3D\xFE" } err
assert_match "*Bad data format*" $err
}
}
test {corrupt payload: fuzzer findings - leak in rdbloading due to dup entry in set} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
catch { r RESTORE _setbig 0 "\x02\x0A\x02\x5F\x39\xC0\x06\x02\x5F\x31\xC0\x00\xC0\x04\x02\x5F\x35\xC0\x02\xC0\x08\x02\x5F\x31\x02\x5F\x33\x09\x00\x7A\x5A\xFB\x90\x3A\xE9\x3C\xBE" } err
assert_match "*Bad data format*" $err
}
}
test {corrupt payload: fuzzer findings - empty intset div by zero} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
r RESTORE _setbig 0 "\x02\xC0\xC0\x06\x02\x5F\x39\xC0\x02\x02\x5F\x33\xC0\x00\x02\x5F\x31\xC0\x04\xC0\x08\x02\x5F\x37\x02\x5F\x35\x09\x00\xC5\xD4\x6D\xBA\xAD\x14\xB7\xE7"
catch {r SRANDMEMBER _setbig }
}
}
test {corrupt payload: fuzzer findings - valgrind ziplist - crash report prints freed memory} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
r RESTORE _zsetbig 0 "\x0C\x3D\x3D\x00\x00\x00\x3A\x00\x00\x00\x14\x00\x00\xF1\x02\xF1\x02\x02\x5F\x31\x04\xF2\x02\xF3\x02\xF3\x02\x02\x5F\x33\x04\xF4\x02\xEE\x02\xF5\x02\x02\x5F\x35\x04\xF6\x02\xF7\x02\xF7\x02\x02\x5F\x37\x04\xF8\x02\xF9\x02\xF9\x02\x02\x5F\x39\x04\xFA\xFF\x09\x00\xAE\xF9\x77\x2A\x47\x24\x33\xF6"
catch { r ZREMRANGEBYSCORE _zsetbig -1050966020 724 }
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: fuzzer findings - valgrind ziplist prevlen reaches outside the ziplist} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
r RESTORE _listbig 0 "\x0E\x02\x1B\x1B\x00\x00\x00\x16\x00\x00\x00\x05\x00\x00\x02\x5F\x39\x04\xF9\x02\x02\x5F\x37\x04\xF7\x02\x02\x5F\x35\xFF\x19\x19\x00\x00\x00\x16\x00\x00\x00\x05\x00\x00\xF5\x02\x02\x5F\x33\x04\xF3\x95\x02\x5F\x31\x04\xF1\xFF\x09\x00\x0C\xFC\x99\x2C\x23\x45\x15\x60"
catch { r RPOP _listbig }
catch { r RPOP _listbig }
catch { r RPUSH _listbig 949682325 }
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: fuzzer findings - valgrind - bad rdbLoadDoubleValue} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
catch { r RESTORE _list 0 "\x03\x01\x11\x11\x00\x00\x00\x0A\x00\x00\x00\x01\x00\x00\xD0\x07\x1A\xE9\x02\xFF\x09\x00\x1A\x06\x07\x32\x41\x28\x3A\x46" } err
assert_match "*Bad data format*" $err
}
}
test {corrupt payload: fuzzer findings - valgrind ziplist prev too big} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
r RESTORE _list 0 "\x0E\x01\x13\x13\x00\x00\x00\x10\x00\x00\x00\x03\x00\x00\xF3\x02\x02\x5F\x31\xC1\xF1\xFF\x09\x00\xC9\x4B\x31\xFE\x61\xC0\x96\xFE"
catch { r RPUSHX _list -45 }
catch { r LREM _list -748 -840}
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: fuzzer findings - lzf decompression fails, avoid valgrind invalid read} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
catch {r RESTORE _stream 0 "\x0F\x02\x10\x00\x00\x01\x73\xDD\xAA\x2A\xB9\x00\x00\x00\x00\x00\x00\x00\x00\xC3\x40\x4B\x40\x5C\x18\x5C\x00\x00\x00\x24\x00\x05\x01\x00\x01\x02\x01\x84\x69\x74\x65\x6D\x05\x85\x76\x61\x6C\x75\x65\x06\x40\x10\x00\x00\x20\x01\x00\x01\x20\x03\x00\x05\x20\x1C\x40\x07\x05\x01\x01\x82\x5F\x31\x03\x80\x0D\x40\x00\x00\x02\x60\x19\x40\x27\x40\x19\x00\x33\x60\x19\x40\x29\x02\x01\x01\x04\x20\x19\x00\xFF\x10\x00\x00\x01\x73\xDD\xAA\x2A\xBC\x00\x00\x00\x00\x00\x00\x00\x00\xC3\x40\x4D\x40\x5E\x18\x5E\x00\x00\x00\x24\x00\x05\x01\x00\x01\x02\x01\x84\x69\x74\x65\x6D\x05\x85\x76\x61\x6C\x75\x65\x06\x40\x10\x00\x00\x20\x01\x06\x01\x01\x82\x5F\x35\x03\x05\x20\x1E\x17\x0B\x03\x01\x01\x06\x01\x40\x0B\x00\x01\x60\x0D\x02\x82\x5F\x37\x60\x19\x80\x00\x00\x08\x60\x19\x80\x27\x02\x82\x5F\x39\x20\x19\x00\xFF\x0A\x81\x00\x00\x01\x73\xDD\xAA\x2A\xBE\x00\x00\x09\x00\x21\x85\x77\x43\x71\x7B\x17\x88"} err
assert_match "*Bad data format*" $err
}
}
test {corrupt payload: fuzzer findings - stream bad lp_count} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload yes
r debug set-skip-checksum-validation 1
catch { r RESTORE _stream 0 "\x0F\x01\x10\x00\x00\x01\x73\xDE\xDF\x7D\x9B\x00\x00\x00\x00\x00\x00\x00\x00\x40\x42\x42\x00\x00\x00\x18\x00\x03\x01\x00\x01\x02\x01\x84\x69\x74\x65\x6D\x05\x85\x76\x61\x6C\x75\x65\x06\x00\x01\x02\x01\x00\x01\x00\x01\x01\x01\x00\x01\x56\x01\x02\x01\x22\x01\x00\x01\x01\x01\x82\x5F\x31\x03\x05\x01\x02\x01\x2C\x01\x00\x01\x01\x01\x02\x01\x05\x01\xFF\x03\x81\x00\x00\x01\x73\xDE\xDF\x7D\xC7\x00\x01\x07\x6D\x79\x67\x72\x6F\x75\x70\x81\x00\x00\x01\x73\xDE\xDF\x7D\x9B\x00\x01\x00\x00\x01\x73\xDE\xDF\x7D\x9B\x00\x00\x00\x00\x00\x00\x00\x00\xF9\x7D\xDF\xDE\x73\x01\x00\x00\x01\x01\x05\x41\x6C\x69\x63\x65\xEB\x7D\xDF\xDE\x73\x01\x00\x00\x01\x00\x00\x01\x73\xDE\xDF\x7D\x9B\x00\x00\x00\x00\x00\x00\x00\x00\x09\x00\xB2\xA8\xA7\x5F\x1B\x61\x72\xD5"} err
assert_match "*Bad data format*" $err
r ping
}
}
test {corrupt payload: fuzzer findings - stream bad lp_count - unsanitized} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
r RESTORE _stream 0 "\x0F\x01\x10\x00\x00\x01\x73\xDE\xDF\x7D\x9B\x00\x00\x00\x00\x00\x00\x00\x00\x40\x42\x42\x00\x00\x00\x18\x00\x03\x01\x00\x01\x02\x01\x84\x69\x74\x65\x6D\x05\x85\x76\x61\x6C\x75\x65\x06\x00\x01\x02\x01\x00\x01\x00\x01\x01\x01\x00\x01\x56\x01\x02\x01\x22\x01\x00\x01\x01\x01\x82\x5F\x31\x03\x05\x01\x02\x01\x2C\x01\x00\x01\x01\x01\x02\x01\x05\x01\xFF\x03\x81\x00\x00\x01\x73\xDE\xDF\x7D\xC7\x00\x01\x07\x6D\x79\x67\x72\x6F\x75\x70\x81\x00\x00\x01\x73\xDE\xDF\x7D\x9B\x00\x01\x00\x00\x01\x73\xDE\xDF\x7D\x9B\x00\x00\x00\x00\x00\x00\x00\x00\xF9\x7D\xDF\xDE\x73\x01\x00\x00\x01\x01\x05\x41\x6C\x69\x63\x65\xEB\x7D\xDF\xDE\x73\x01\x00\x00\x01\x00\x00\x01\x73\xDE\xDF\x7D\x9B\x00\x00\x00\x00\x00\x00\x00\x00\x09\x00\xB2\xA8\xA7\x5F\x1B\x61\x72\xD5"
catch { r XREVRANGE _stream 638932639 738}
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: fuzzer findings - stream integrity check issue} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload yes
r debug set-skip-checksum-validation 1
catch { r RESTORE _stream 0 "\x0F\x02\x10\x00\x00\x01\x75\x2D\xA2\x90\x67\x00\x00\x00\x00\x00\x00\x00\x00\xC3\x40\x4F\x40\x5C\x18\x5C\x00\x00\x00\x24\x00\x05\x01\x00\x01\x4A\x01\x84\x69\x74\x65\x6D\x05\x85\x76\x61\x6C\x75\x65\x06\x40\x10\x00\x00\x20\x01\x00\x01\x20\x03\x00\x05\x20\x1C\x40\x09\x05\x01\x01\x82\x5F\x31\x03\x80\x0D\x00\x02\x20\x0D\x00\x02\xA0\x19\x00\x03\x20\x0B\x02\x82\x5F\x33\xA0\x19\x00\x04\x20\x0D\x00\x04\x20\x19\x00\xFF\x10\x00\x00\x01\x75\x2D\xA2\x90\x67\x00\x00\x00\x00\x00\x00\x00\x05\xC3\x40\x56\x40\x60\x18\x60\x00\x00\x00\x24\x00\x05\x01\x00\x01\x02\x01\x84\x69\x74\x65\x6D\x05\x85\x76\x61\x6C\x75\x65\x06\x40\x10\x00\x00\x20\x01\x06\x01\x01\x82\x5F\x35\x03\x05\x20\x1E\x40\x0B\x03\x01\x01\x06\x01\x80\x0B\x00\x02\x20\x0B\x02\x82\x5F\x37\x60\x19\x03\x01\x01\xDF\xFB\x20\x05\x00\x08\x60\x1A\x20\x0C\x00\xFC\x20\x05\x02\x82\x5F\x39\x20\x1B\x00\xFF\x0A\x81\x00\x00\x01\x75\x2D\xA2\x90\x68\x01\x00\x09\x00\x1D\x6F\xC0\x69\x8A\xDE\xF7\x92" } err
assert_match "*Bad data format*" $err
}
}
test {corrupt payload: fuzzer findings - infinite loop} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
r RESTORE _stream 0 "\x0F\x01\x10\x00\x00\x01\x75\x3A\xA6\xD0\x93\x00\x00\x00\x00\x00\x00\x00\x00\x40\x42\x42\x00\x00\x00\x18\x00\x03\x01\x00\x01\x02\x01\x84\x69\x74\x65\x6D\x05\x85\x76\x61\x6C\x75\x65\x06\x00\x01\x02\x01\x00\x01\x00\x01\x01\x01\x00\x01\x05\x01\x02\x01\x00\x01\x01\x01\x01\x01\x82\x5F\x31\x03\xFD\x01\x02\x01\x00\x01\x02\x01\x01\x01\x02\x01\x05\x01\xFF\x03\x81\x00\x00\x01\x75\x3A\xA6\xD0\x93\x02\x01\x07\x6D\x79\x67\x72\x6F\x75\x70\x81\x00\x00\x01\x75\x3A\xA6\xD0\x93\x00\x01\x00\x00\x01\x75\x3A\xA6\xD0\x93\x00\x00\x00\x00\x00\x00\x00\x00\x94\xD0\xA6\x3A\x75\x01\x00\x00\x01\x01\x05\x41\x6C\x69\x63\x65\x94\xD0\xA6\x3A\x75\x01\x00\x00\x01\x00\x00\x01\x75\x3A\xA6\xD0\x93\x00\x00\x00\x00\x00\x00\x00\x00\x09\x00\xC4\x09\xAD\x69\x7E\xEE\xA6\x2F"
catch { r XREVRANGE _stream 288270516 971031845 }
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: fuzzer findings - hash convert asserts on RESTORE with shallow sanitization} {
# if we don't perform full sanitization, and the next command can assert on converting
# a ziplist to hash records, then we're ok with that happning in RESTORE too
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
catch { r RESTORE _hash 0 "\x0D\x3D\x3D\x00\x00\x00\x3A\x00\x00\x00\x14\x13\x00\xF5\x02\xF5\x02\xF2\x02\x53\x5F\x31\x04\xF3\x02\xF3\x02\xF7\x02\xF7\x02\xF8\x02\x02\x5F\x37\x04\xF1\x02\xF1\x02\xF6\x02\x02\x5F\x35\x04\xF4\x02\x02\x5F\x33\x04\xFA\x02\x02\x5F\x39\x04\xF9\x02\xF9\xFF\x09\x00\xB5\x48\xDE\x62\x31\xD0\xE5\x63" }
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: OOM in rdbGenericLoadStringObject} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
catch { r RESTORE x 0 "\x0A\x81\x7F\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x13\x00\x00\x00\x0E\x00\x00\x00\x02\x00\x00\x02\x61\x00\x04\x02\x62\x00\xFF\x09\x00\x57\x04\xE5\xCD\xD4\x37\x6C\x57" } err
assert_match "*Bad data format*" $err
r ping
}
}
test {corrupt payload: fuzzer findings - OOM in dictExpand} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
catch { r RESTORE x 0 "\x02\x81\x02\x5F\x31\xC0\x00\xC0\x02\x09\x00\xCD\x84\x2C\xB7\xE8\xA4\x49\x57" } err
assert_match "*Bad data format*" $err
r ping
}
}
test {corrupt payload: fuzzer findings - invalid tail offset after removal} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
r RESTORE _zset 0 "\x0C\x19\x19\x00\x00\x00\x02\x00\x00\x00\x06\x00\x00\xF1\x02\xF1\x02\x02\x5F\x31\x04\xF2\x02\xF3\x02\xF3\xFF\x09\x00\x4D\x72\x7B\x97\xCD\x9A\x70\xC1"
catch {r ZPOPMIN _zset}
catch {r ZPOPMAX _zset}
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: fuzzer findings - negative reply length} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload no
r debug set-skip-checksum-validation 1
r RESTORE _stream 0 "\x0F\x01\x10\x00\x00\x01\x75\xCF\xA1\x16\xA7\x00\x00\x00\x00\x00\x00\x00\x00\x40\x42\x42\x00\x00\x00\x18\x00\x03\x01\x00\x01\x02\x01\x84\x69\x74\x65\x6D\x05\x85\x76\x61\x6C\x75\x65\x06\x00\x01\x02\x01\x00\x01\x00\x01\x01\x01\x00\x01\x05\x01\x02\x01\x00\x01\x01\x01\x01\x01\x14\x5F\x31\x03\x05\x01\x02\x01\x00\x01\x02\x01\x01\x01\x02\x01\x05\x01\xFF\x03\x81\x00\x00\x01\x75\xCF\xA1\x16\xA7\x02\x01\x07\x6D\x79\x67\x72\x6F\x75\x70\x81\x00\x00\x01\x75\xCF\xA1\x16\xA7\x01\x01\x00\x00\x01\x75\xCF\xA1\x16\xA7\x00\x00\x00\x00\x00\x00\x00\x01\xA7\x16\xA1\xCF\x75\x01\x00\x00\x01\x01\x05\x41\x6C\x69\x63\x65\xA7\x16\xA1\xCF\x75\x01\x00\x00\x01\x00\x00\x01\x75\xCF\xA1\x16\xA7\x00\x00\x00\x00\x00\x00\x00\x01\x09\x00\x1B\x42\x52\xB8\xDD\x5C\xE5\x4E"
catch {r XADD _stream * -956 -2601503852}
catch {r XINFO STREAM _stream FULL}
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
test {corrupt payload: fuzzer findings - valgrind negative malloc} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload yes
r debug set-skip-checksum-validation 1
catch {r RESTORE _key 0 "\x0E\x01\x81\xD6\xD6\x00\x00\x00\x0A\x00\x00\x00\x01\x00\x00\x40\xC8\x6F\x2F\x36\xE2\xDF\xE3\x2E\x26\x64\x8B\x87\xD1\x7A\xBD\xFF\xEF\xEF\x63\x65\xF6\xF8\x8C\x4E\xEC\x96\x89\x56\x88\xF8\x3D\x96\x5A\x32\xBD\xD1\x36\xD8\x02\xE6\x66\x37\xCB\x34\x34\xC4\x52\xA7\x2A\xD5\x6F\x2F\x7E\xEE\xA2\x94\xD9\xEB\xA9\x09\x38\x3B\xE1\xA9\x60\xB6\x4E\x09\x44\x1F\x70\x24\xAA\x47\xA8\x6E\x30\xE1\x13\x49\x4E\xA1\x92\xC4\x6C\xF0\x35\x83\xD9\x4F\xD9\x9C\x0A\x0D\x7A\xE7\xB1\x61\xF5\xC1\x2D\xDC\xC3\x0E\x87\xA6\x80\x15\x18\xBA\x7F\x72\xDD\x14\x75\x46\x44\x0B\xCA\x9C\x8F\x1C\x3C\xD7\xDA\x06\x62\x18\x7E\x15\x17\x24\xAB\x45\x21\x27\xC2\xBC\xBB\x86\x6E\xD8\xBD\x8E\x50\xE0\xE0\x88\xA4\x9B\x9D\x15\x2A\x98\xFF\x5E\x78\x6C\x81\xFC\xA8\xC9\xC8\xE6\x61\xC8\xD1\x4A\x7F\x81\xD6\xA6\x1A\xAD\x4C\xC1\xA2\x1C\x90\x68\x15\x2A\x8A\x36\xC0\x58\xC3\xCC\xA6\x54\x19\x12\x0F\xEB\x46\xFF\x6E\xE3\xA7\x92\xF8\xFF\x09\x00\xD0\x71\xF7\x9F\xF7\x6A\xD6\x2E"} err
assert_match "*Bad data format*" $err
r ping
}
}
test {corrupt payload: fuzzer findings - valgrind invalid read} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload yes
r debug set-skip-checksum-validation 1
catch {r RESTORE _key 0 "\x05\x0A\x02\x5F\x39\x00\x00\x00\x00\x00\x00\x22\x40\xC0\x08\x00\x00\x00\x00\x00\x00\x20\x40\x02\x5F\x37\x00\x00\x00\x00\x00\x00\x1C\x40\xC0\x06\x00\x00\x00\x00\x00\x00\x18\x40\x02\x5F\x33\x00\x00\x00\x00\x00\x00\x14\x40\xC0\x04\x00\x00\x00\x00\x00\x00\x10\x40\x02\x5F\x33\x00\x00\x00\x00\x00\x00\x08\x40\xC0\x02\x00\x00\x00\x00\x00\x00\x00\x40\x02\x5F\x31\x00\x00\x00\x00\x00\x00\xF0\x3F\xC0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x09\x00\x3C\x66\xD7\x14\xA9\xDA\x3C\x69"} err
assert_match "*Bad data format*" $err
r ping
}
}
test {corrupt payload: fuzzer findings - HRANDFIELD on bad ziplist} {
start_server [list overrides [list loglevel verbose use-exit-on-panic yes crash-memcheck-enabled no] ] {
r config set sanitize-dump-payload yes
r debug set-skip-checksum-validation 1
r RESTORE _int 0 "\x04\xC0\x01\x09\x00\xF6\x8A\xB6\x7A\x85\x87\x72\x4D"
catch {r HRANDFIELD _int}
assert_equal [count_log_message 0 "crashed by signal"] 0
assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
}
}
} ;# tags
+290
View File
@@ -0,0 +1,290 @@
start_server {tags {"failover"}} {
start_server {} {
start_server {} {
set node_0 [srv 0 client]
set node_0_host [srv 0 host]
set node_0_port [srv 0 port]
set node_0_pid [srv 0 pid]
set node_1 [srv -1 client]
set node_1_host [srv -1 host]
set node_1_port [srv -1 port]
set node_1_pid [srv -1 pid]
set node_2 [srv -2 client]
set node_2_host [srv -2 host]
set node_2_port [srv -2 port]
set node_2_pid [srv -2 pid]
proc assert_digests_match {n1 n2 n3} {
assert_equal [$n1 debug digest] [$n2 debug digest]
assert_equal [$n2 debug digest] [$n3 debug digest]
}
test {failover command fails without connected replica} {
catch { $node_0 failover to $node_1_host $node_1_port } err
if {! [string match "ERR*" $err]} {
fail "failover command succeeded when replica not connected"
}
}
test {setup replication for following tests} {
$node_1 replicaof $node_0_host $node_0_port
$node_2 replicaof $node_0_host $node_0_port
wait_for_sync $node_1
wait_for_sync $node_2
}
test {failover command fails with invalid host} {
catch { $node_0 failover to invalidhost $node_1_port } err
assert_match "ERR*" $err
}
test {failover command fails with invalid port} {
catch { $node_0 failover to $node_1_host invalidport } err
assert_match "ERR*" $err
}
test {failover command fails with just force and timeout} {
catch { $node_0 FAILOVER FORCE TIMEOUT 100} err
assert_match "ERR*" $err
}
test {failover command fails when sent to a replica} {
catch { $node_1 failover to $node_1_host $node_1_port } err
assert_match "ERR*" $err
}
test {failover command fails with force without timeout} {
catch { $node_0 failover to $node_1_host $node_1_port FORCE } err
assert_match "ERR*" $err
}
test {failover command to specific replica works} {
set initial_psyncs [s -1 sync_partial_ok]
set initial_syncs [s -1 sync_full]
# Generate a delta between primary and replica
set load_handler [start_write_load $node_0_host $node_0_port 5]
exec kill -SIGSTOP [srv -1 pid]
wait_for_condition 50 100 {
[s 0 total_commands_processed] > 100
} else {
fail "Node 0 did not accept writes"
}
exec kill -SIGCONT [srv -1 pid]
# Execute the failover
$node_0 failover to $node_1_host $node_1_port
# Wait for failover to end
wait_for_condition 50 100 {
[s 0 master_failover_state] == "no-failover"
} else {
fail "Failover from node 0 to node 1 did not finish"
}
stop_write_load $load_handler
$node_2 replicaof $node_1_host $node_1_port
wait_for_sync $node_0
wait_for_sync $node_2
assert_match *slave* [$node_0 role]
assert_match *master* [$node_1 role]
assert_match *slave* [$node_2 role]
# We should accept psyncs from both nodes
assert_equal [expr [s -1 sync_partial_ok] - $initial_psyncs] 2
assert_equal [expr [s -1 sync_full] - $initial_psyncs] 0
assert_digests_match $node_0 $node_1 $node_2
}
test {failover command to any replica works} {
set initial_psyncs [s -2 sync_partial_ok]
set initial_syncs [s -2 sync_full]
wait_for_ofs_sync $node_1 $node_2
# We stop node 0 to and make sure node 2 is selected
exec kill -SIGSTOP $node_0_pid
$node_1 set CASE 1
$node_1 FAILOVER
# Wait for failover to end
wait_for_condition 50 100 {
[s -1 master_failover_state] == "no-failover"
} else {
fail "Failover from node 1 to node 2 did not finish"
}
exec kill -SIGCONT $node_0_pid
$node_0 replicaof $node_2_host $node_2_port
wait_for_sync $node_0
wait_for_sync $node_1
assert_match *slave* [$node_0 role]
assert_match *slave* [$node_1 role]
assert_match *master* [$node_2 role]
# We should accept Psyncs from both nodes
assert_equal [expr [s -2 sync_partial_ok] - $initial_psyncs] 2
assert_equal [expr [s -1 sync_full] - $initial_psyncs] 0
assert_digests_match $node_0 $node_1 $node_2
}
test {failover to a replica with force works} {
set initial_psyncs [s 0 sync_partial_ok]
set initial_syncs [s 0 sync_full]
exec kill -SIGSTOP $node_0_pid
# node 0 will never acknowledge this write
$node_2 set case 2
$node_2 failover to $node_0_host $node_0_port TIMEOUT 100 FORCE
# Wait for node 0 to give up on sync attempt and start failover
wait_for_condition 50 100 {
[s -2 master_failover_state] == "failover-in-progress"
} else {
fail "Failover from node 2 to node 0 did not timeout"
}
# Quick check that everyone is a replica, we never want a
# state where there are two masters.
assert_match *slave* [$node_1 role]
assert_match *slave* [$node_2 role]
exec kill -SIGCONT $node_0_pid
# Wait for failover to end
wait_for_condition 50 100 {
[s -2 master_failover_state] == "no-failover"
} else {
fail "Failover from node 2 to node 0 did not finish"
}
$node_1 replicaof $node_0_host $node_0_port
wait_for_sync $node_1
wait_for_sync $node_2
assert_match *master* [$node_0 role]
assert_match *slave* [$node_1 role]
assert_match *slave* [$node_2 role]
assert_equal [count_log_message -2 "time out exceeded, failing over."] 1
# We should accept both psyncs, although this is the condition we might not
# since we didn't catch up.
assert_equal [expr [s 0 sync_partial_ok] - $initial_psyncs] 2
assert_equal [expr [s 0 sync_full] - $initial_syncs] 0
assert_digests_match $node_0 $node_1 $node_2
}
test {failover with timeout aborts if replica never catches up} {
set initial_psyncs [s 0 sync_partial_ok]
set initial_syncs [s 0 sync_full]
# Stop replica so it never catches up
exec kill -SIGSTOP [srv -1 pid]
$node_0 SET CASE 1
$node_0 failover to [srv -1 host] [srv -1 port] TIMEOUT 500
# Wait for failover to end
wait_for_condition 50 20 {
[s 0 master_failover_state] == "no-failover"
} else {
fail "Failover from node_0 to replica did not finish"
}
exec kill -SIGCONT [srv -1 pid]
# We need to make sure the nodes actually sync back up
wait_for_ofs_sync $node_0 $node_1
wait_for_ofs_sync $node_0 $node_2
assert_match *master* [$node_0 role]
assert_match *slave* [$node_1 role]
assert_match *slave* [$node_2 role]
# Since we never caught up, there should be no syncs
assert_equal [expr [s 0 sync_partial_ok] - $initial_psyncs] 0
assert_equal [expr [s 0 sync_full] - $initial_syncs] 0
assert_digests_match $node_0 $node_1 $node_2
}
test {failovers can be aborted} {
set initial_psyncs [s 0 sync_partial_ok]
set initial_syncs [s 0 sync_full]
# Stop replica so it never catches up
exec kill -SIGSTOP [srv -1 pid]
$node_0 SET CASE 2
$node_0 failover to [srv -1 host] [srv -1 port] TIMEOUT 60000
assert_match [s 0 master_failover_state] "waiting-for-sync"
# Sanity check that read commands are still accepted
$node_0 GET CASE
$node_0 failover abort
assert_match [s 0 master_failover_state] "no-failover"
exec kill -SIGCONT [srv -1 pid]
# Just make sure everything is still synced
wait_for_ofs_sync $node_0 $node_1
wait_for_ofs_sync $node_0 $node_2
assert_match *master* [$node_0 role]
assert_match *slave* [$node_1 role]
assert_match *slave* [$node_2 role]
# Since we never caught up, there should be no syncs
assert_equal [expr [s 0 sync_partial_ok] - $initial_psyncs] 0
assert_equal [expr [s 0 sync_full] - $initial_syncs] 0
assert_digests_match $node_0 $node_1 $node_2
}
test {failover aborts if target rejects sync request} {
set initial_psyncs [s 0 sync_partial_ok]
set initial_syncs [s 0 sync_full]
# We block psync, so the failover will fail
$node_1 acl setuser default -psync
# We pause the target long enough to send a write command
# during the pause. This write will not be interrupted.
exec kill -SIGSTOP [srv -1 pid]
set rd [redis_deferring_client]
$rd SET FOO BAR
$node_0 failover to $node_1_host $node_1_port
exec kill -SIGCONT [srv -1 pid]
# Wait for failover to end
wait_for_condition 50 100 {
[s 0 master_failover_state] == "no-failover"
} else {
fail "Failover from node_0 to replica did not finish"
}
assert_equal [$rd read] "OK"
$rd close
# restore access to psync
$node_1 acl setuser default +psync
# We need to make sure the nodes actually sync back up
wait_for_sync $node_1
wait_for_sync $node_2
assert_match *master* [$node_0 role]
assert_match *slave* [$node_1 role]
assert_match *slave* [$node_2 role]
# We will cycle all of our replicas here and force a psync.
assert_equal [expr [s 0 sync_partial_ok] - $initial_psyncs] 2
assert_equal [expr [s 0 sync_full] - $initial_syncs] 0
assert_equal [count_log_message 0 "Failover target rejected psync request"] 1
assert_digests_match $node_0 $node_1 $node_2
}
}
}
}
+30 -3
View File
@@ -1,14 +1,26 @@
set server_path [tmpdir server.log]
set system_name [string tolower [exec uname -s]]
# ldd --version returns 1 under musl for unknown reasons. If this check stops working, that may be why
set is_musl [catch {exec ldd --version}]
set system_supported 0
if {$system_name eq {linux} && $is_musl eq 0 || $system_name eq {darwin}} {
# We only support darwin or Linux with glibc
if {$system_name eq {darwin}} {
set system_supported 1
} elseif {$system_name eq {linux} && $is_musl eq 0} {
# Avoid the test on libmusl, which does not support backtrace
set ldd [exec ldd src/keydb-server]
if {![string match {*libc.musl*} $ldd]} {
set system_supported 1
}
}
if {$system_supported} {
set server_path [tmpdir server.log]
start_server [list overrides [list dir $server_path]] {
test "Server is able to generate a stack trace on selected systems" {
r config set watchdog-period 200
r debug sleep 1
set pattern "*watchdogSignalHandler*"
set pattern "*STACK TRACE*"
set retry 10
while {$retry} {
set result [exec tail -100 < [srv 0 stdout]]
@@ -23,4 +35,19 @@ if {$system_name eq {linux} && $is_musl eq 0 || $system_name eq {darwin}} {
}
}
}
# Valgrind will complain that the process terminated by a signal, skip it.
if {!$::valgrind} {
set server_path [tmpdir server1.log]
start_server [list overrides [list dir $server_path]] {
test "Crash report generated on SIGABRT" {
set pid [s process_id]
exec kill -SIGABRT $pid
set pattern "*STACK TRACE*"
set result [exec tail -1000 < [srv 0 stdout]]
assert {[string match $pattern $result]}
}
}
}
}
+14 -17
View File
@@ -5,7 +5,7 @@ proc show_cluster_status {} {
# time info. Logs are in the following form:
#
# 11296:M 25 May 2020 17:37:14.652 # Server initialized
set log_regexp {^[0-9]+:[A-Z] [0-9]+ [A-z]+ [0-9]+ ([0-9:.]+) .*}
set log_regexp {^[0-9]+:^[0-9]+:[A-Z] [0-9]+ [A-z]+ [0-9]+ ([0-9:.]+) .*}
set repl_regexp {(master|repl|sync|backlog|meaningful|offset)}
puts "Master ID is $master_id"
@@ -25,15 +25,11 @@ proc show_cluster_status {} {
array set log {}
for {set j 0} {$j < 5} {incr j} {
set fd [open $R_log($j)]
set found 0
set tries 0
while {([gets $fd l] >= 0 || !$found) && $tries < 1000} {
while {[gets $fd l] >= 0} {
if {[regexp $log_regexp $l] &&
[regexp -nocase $repl_regexp $l]} {
lappend log($j) $l
set found 1
}
incr $tries
}
close $fd
}
@@ -98,7 +94,7 @@ start_server {} {
# master and slave instances while the
# master is loaded with writes.
set disconnect_period 2000 ; # Disconnect repl link every N ms.
set disconnect_period 1000 ; # Disconnect repl link every N ms.
for {set j 0} {$j < 5} {incr j} {
set R($j) [srv [expr 0-$j] client]
@@ -160,7 +156,7 @@ start_server {} {
test "PSYNC2: cluster is consistent after failover" {
$R($master_id) incr x; incr counter_value
for {set j 0} {$j < 5} {incr j} {
wait_for_condition 50 2000 {
wait_for_condition 50 1000 {
[$R($j) get x] == $counter_value
} else {
show_cluster_status
@@ -196,7 +192,7 @@ start_server {} {
set x [$R($master_id) get x]
test "PSYNC2: cluster is consistent after load (x = $x)" {
for {set j 0} {$j < 5} {incr j} {
wait_for_condition 50 2000 {
wait_for_condition 50 1000 {
[$R($j) get x] == $counter_value
} else {
show_cluster_status
@@ -284,12 +280,12 @@ start_server {} {
set sync_partial_err [status $R($master_id) sync_partial_err]
catch {
$R($slave_id) config rewrite
restart_server [expr {0-$slave_id}] true
restart_server [expr {0-$slave_id}] true false
set R($slave_id) [srv [expr {0-$slave_id}] client]
}
# note: just waiting for connected_slaves==4 has a race condition since
# we might do the check before the master realized that the slave disconnected
wait_for_condition 50 2000 {
wait_for_condition 50 1000 {
[status $R($master_id) sync_partial_ok] == $sync_partial + 1
} else {
puts "prev sync_full: $sync_count"
@@ -315,7 +311,7 @@ start_server {} {
$R($master_id) EVALSHA e6e0b547500efcec21eddb619ac3724081afee89 0
# Wait for the two to sync
wait_for_condition 50 2000 {
wait_for_condition 50 1000 {
[$R($master_id) debug digest] == [$R($slave_id) debug digest]
} else {
show_cluster_status
@@ -333,7 +329,7 @@ start_server {} {
catch {
$R($slave_id) config rewrite
restart_server [expr {0-$slave_id}] true
restart_server [expr {0-$slave_id}] true false
set R($slave_id) [srv [expr {0-$slave_id}] client]
}
@@ -343,7 +339,7 @@ start_server {} {
if {[catch {
$R($slave_id) slaveof $master_host $master_port
}]} {
after 2000
after 1000
} else {
break
}
@@ -351,7 +347,7 @@ start_server {} {
}
# The master should be back at 4 slaves eventually
wait_for_condition 50 2000 {
wait_for_condition 50 1000 {
[status $R($master_id) connected_slaves] == 4
} else {
show_cluster_status
@@ -362,7 +358,7 @@ start_server {} {
# However if the slave started with the full state of the
# scripting engine, we should now have the same digest.
wait_for_condition 50 2000 {
wait_for_condition 50 1000 {
[$R($master_id) debug digest] == [$R($slave_id) debug digest]
} else {
show_cluster_status
@@ -371,7 +367,8 @@ start_server {} {
}
if {$no_exit} {
while 1 { puts -nonewline .; flush stdout; after 2000}
while 1 { puts -nonewline .; flush stdout; after 1000}
}
}}}}}
+126 -3
View File
@@ -1,3 +1,5 @@
tags {"rdb"} {
set server_path [tmpdir "server.rdb-encoding-test"]
# Copy RDB with different encodings in server path
@@ -49,13 +51,23 @@ start_server [list overrides [list "dir" $server_path] keep_persistence true] {
}
}
r xgroup create stream mygroup 0
r xreadgroup GROUP mygroup Alice COUNT 1 STREAMS stream >
set records [r xreadgroup GROUP mygroup Alice COUNT 2 STREAMS stream >]
r xdel stream [lindex [lindex [lindex [lindex $records 0] 1] 1] 0]
r xack stream mygroup [lindex [lindex [lindex [lindex $records 0] 1] 0] 0]
set digest [r debug digest]
r config set sanitize-dump-payload no
r debug reload
set newdigest [r debug digest]
assert {$digest eq $newdigest}
r del stream
}
test {Test RDB stream encoding - sanitize dump} {
r config set sanitize-dump-payload yes
r debug reload
set newdigest [r debug digest]
assert {$digest eq $newdigest}
}
# delete the stream, maybe valgrind will find something
r del stream
}
# Helper function to start a server and kill it, just to check the error
@@ -155,7 +167,7 @@ test {client freed during loading} {
# 100mb of rdb, 100k keys will load in more than 1 second
r debug populate 100000 key 1000
restart_server 0 false
restart_server 0 false false
# make sure it's still loading
assert_equal [s loading] 1
@@ -189,3 +201,114 @@ test {client freed during loading} {
exec kill [srv 0 pid]
}
}
# Our COW metrics (Private_Dirty) work only on Linux
set system_name [string tolower [exec uname -s]]
if {$system_name eq {linux}} {
start_server {overrides {save ""}} {
test {Test child sending info} {
# make sure that rdb_last_cow_size and current_cow_size are zero (the test using new server),
# so that the comparisons during the test will be valid
assert {[s current_cow_size] == 0}
assert {[s current_save_keys_processed] == 0}
assert {[s current_save_keys_total] == 0}
assert {[s rdb_last_cow_size] == 0}
# using a 200us delay, the bgsave is empirically taking about 10 seconds.
# we need it to take more than some 5 seconds, since redis only report COW once a second.
r config set rdb-key-save-delay 200
r config set loglevel debug
# populate the db with 10k keys of 4k each
set rd [redis_deferring_client 0]
set size 4096
set cmd_count 10000
for {set k 0} {$k < $cmd_count} {incr k} {
$rd set key$k [string repeat A $size]
}
for {set k 0} {$k < $cmd_count} {incr k} {
catch { $rd read }
}
$rd close
# start background rdb save
r bgsave
set current_save_keys_total [s current_save_keys_total]
if {$::verbose} {
puts "Keys before bgsave start: current_save_keys_total"
}
# on each iteration, we will write some key to the server to trigger copy-on-write, and
# wait to see that it reflected in INFO.
set iteration 1
while 1 {
# take samples before writing new data to the server
set cow_size [s current_cow_size]
if {$::verbose} {
puts "COW info before copy-on-write: $cow_size"
}
set keys_processed [s current_save_keys_processed]
if {$::verbose} {
puts "current_save_keys_processed info : $keys_processed"
}
# trigger copy-on-write
r setrange key$iteration 0 [string repeat B $size]
# wait to see that current_cow_size value updated (as long as the child is in progress)
wait_for_condition 80 100 {
[s rdb_bgsave_in_progress] == 0 ||
[s current_cow_size] >= $cow_size + $size &&
[s current_save_keys_processed] > $keys_processed &&
[s current_fork_perc] > 0
} else {
if {$::verbose} {
puts "COW info on fail: [s current_cow_size]"
puts [exec tail -n 100 < [srv 0 stdout]]
}
fail "COW info wasn't reported"
}
# assert that $keys_processed is not greater than total keys.
assert_morethan_equal $current_save_keys_total $keys_processed
# for no accurate, stop after 2 iterations
if {!$::accurate && $iteration == 2} {
break
}
# stop iterating if the bgsave completed
if { [s rdb_bgsave_in_progress] == 0 } {
break
}
incr iteration 1
}
# make sure we saw report of current_cow_size
if {$iteration < 2 && $::verbose} {
puts [exec tail -n 100 < [srv 0 stdout]]
}
assert_morethan_equal $iteration 2
# if bgsave completed, check that rdb_last_cow_size (fork exit report)
# is at least 90% of last rdb_active_cow_size.
if { [s rdb_bgsave_in_progress] == 0 } {
set final_cow [s rdb_last_cow_size]
set cow_size [expr $cow_size * 0.9]
if {$final_cow < $cow_size && $::verbose} {
puts [exec tail -n 100 < [srv 0 stdout]]
}
assert_morethan_equal $final_cow $cow_size
}
}
}
} ;# system_name
} ;# tags
+168
View File
@@ -0,0 +1,168 @@
source tests/support/benchmark.tcl
proc cmdstat {cmd} {
return [cmdrstat $cmd r]
}
start_server {tags {"benchmark network"}} {
start_server {} {
set master_host [srv 0 host]
set master_port [srv 0 port]
test {benchmark: set,get} {
r config resetstat
r flushall
set cmd [redisbenchmark $master_host $master_port "-c 5 -n 10 -e -t set,get"]
if {[catch { exec {*}$cmd } error]} {
set first_line [lindex [split $error "\n"] 0]
puts [colorstr red "keydb-benchmark non zero code. first line: $first_line"]
fail "keydb-benchmark non zero code. first line: $first_line"
}
assert_match {*calls=10,*} [cmdstat set]
assert_match {*calls=10,*} [cmdstat get]
# assert one of the non benchmarked commands is not present
assert_match {} [cmdstat lrange]
}
test {benchmark: full test suite} {
r config resetstat
set cmd [redisbenchmark $master_host $master_port "-c 10 -n 100 -e"]
if {[catch { exec {*}$cmd } error]} {
set first_line [lindex [split $error "\n"] 0]
puts [colorstr red "keydb-benchmark non zero code. first line: $first_line"]
fail "keydb-benchmark non zero code. first line: $first_line"
}
# ping total calls are 2*issued commands per test due to PING_INLINE and PING_MBULK
assert_match {*calls=200,*} [cmdstat ping]
assert_match {*calls=100,*} [cmdstat set]
assert_match {*calls=100,*} [cmdstat get]
assert_match {*calls=100,*} [cmdstat incr]
# lpush total calls are 2*issued commands per test due to the lrange tests
assert_match {*calls=200,*} [cmdstat lpush]
assert_match {*calls=100,*} [cmdstat rpush]
assert_match {*calls=100,*} [cmdstat lpop]
assert_match {*calls=100,*} [cmdstat rpop]
assert_match {*calls=100,*} [cmdstat sadd]
assert_match {*calls=100,*} [cmdstat hset]
assert_match {*calls=100,*} [cmdstat spop]
assert_match {*calls=100,*} [cmdstat zadd]
assert_match {*calls=100,*} [cmdstat zpopmin]
assert_match {*calls=400,*} [cmdstat lrange]
assert_match {*calls=100,*} [cmdstat mset]
# assert one of the non benchmarked commands is not present
assert_match {} [cmdstat rpoplpush]
}
test {benchmark: multi-thread set,get} {
r config resetstat
r flushall
set cmd [redisbenchmark $master_host $master_port "--threads 10 -c 5 -n 10 -e -t set,get"]
if {[catch { exec {*}$cmd } error]} {
set first_line [lindex [split $error "\n"] 0]
puts [colorstr red "keydb-benchmark non zero code. first line: $first_line"]
fail "keydb-benchmark non zero code. first line: $first_line"
}
assert_match {*calls=10,*} [cmdstat set]
assert_match {*calls=10,*} [cmdstat get]
# assert one of the non benchmarked commands is not present
assert_match {} [cmdstat lrange]
# ensure only one key was populated
assert_match {1} [scan [regexp -inline {keys\=([\d]*)} [r info keyspace]] keys=%d]
}
test {benchmark: pipelined full set,get} {
r config resetstat
r flushall
set cmd [redisbenchmark $master_host $master_port "-P 5 -c 10 -n 10010 -e -t set,get"]
if {[catch { exec {*}$cmd } error]} {
set first_line [lindex [split $error "\n"] 0]
puts [colorstr red "keydb-benchmark non zero code. first line: $first_line"]
fail "keydb-benchmark non zero code. first line: $first_line"
}
assert_match {*calls=10010,*} [cmdstat set]
assert_match {*calls=10010,*} [cmdstat get]
# assert one of the non benchmarked commands is not present
assert_match {} [cmdstat lrange]
# ensure only one key was populated
assert_match {1} [scan [regexp -inline {keys\=([\d]*)} [r info keyspace]] keys=%d]
}
test {benchmark: arbitrary command} {
r config resetstat
r flushall
set cmd [redisbenchmark $master_host $master_port "-c 5 -n 150 -e INCRBYFLOAT mykey 10.0"]
if {[catch { exec {*}$cmd } error]} {
set first_line [lindex [split $error "\n"] 0]
puts [colorstr red "keydb-benchmark non zero code. first line: $first_line"]
fail "keydb-benchmark non zero code. first line: $first_line"
}
assert_match {*calls=150,*} [cmdstat incrbyfloat]
# assert one of the non benchmarked commands is not present
assert_match {} [cmdstat get]
# ensure only one key was populated
assert_match {1} [scan [regexp -inline {keys\=([\d]*)} [r info keyspace]] keys=%d]
}
test {benchmark: keyspace length} {
r flushall
r config resetstat
set cmd [redisbenchmark $master_host $master_port "-r 50 -t set -n 1000"]
if {[catch { exec {*}$cmd } error]} {
set first_line [lindex [split $error "\n"] 0]
puts [colorstr red "keydb-benchmark non zero code. first line: $first_line"]
fail "keydb-benchmark non zero code. first line: $first_line"
}
assert_match {*calls=1000,*} [cmdstat set]
# assert one of the non benchmarked commands is not present
assert_match {} [cmdstat get]
# ensure the keyspace has the desired size
assert_match {50} [scan [regexp -inline {keys\=([\d]*)} [r info keyspace]] keys=%d]
}
# tls specific tests
if {$::tls} {
test {benchmark: specific tls-ciphers} {
r flushall
r config resetstat
set cmd [redisbenchmark $master_host $master_port "-r 50 -t set -n 1000 --tls-ciphers \"DEFAULT:-AES128-SHA256\""]
if {[catch { exec {*}$cmd } error]} {
set first_line [lindex [split $error "\n"] 0]
puts [colorstr red "keydb-benchmark non zero code. first line: $first_line"]
fail "keydb-benchmark non zero code. first line: $first_line"
}
assert_match {*calls=1000,*} [cmdstat set]
# assert one of the non benchmarked commands is not present
assert_match {} [cmdstat get]
}
test {benchmark: specific tls-ciphersuites} {
r flushall
r config resetstat
set ciphersuites_supported 1
set cmd [redisbenchmark $master_host $master_port "-r 50 -t set -n 1000 --tls-ciphersuites \"TLS_AES_128_GCM_SHA256\""]
if {[catch { exec {*}$cmd } error]} {
set first_line [lindex [split $error "\n"] 0]
if {[string match "*Invalid option*" $first_line]} {
set ciphersuites_supported 0
if {$::verbose} {
puts "Skipping test, TLSv1.3 not supported."
}
} else {
puts [colorstr red "keydb-benchmark non zero code. first line: $first_line"]
fail "keydb-benchmark non zero code. first line: $first_line"
}
}
if {$ciphersuites_supported} {
assert_match {*calls=1000,*} [cmdstat set]
# assert one of the non benchmarked commands is not present
assert_match {} [cmdstat get]
}
}
}
}
}
+1 -1
View File
@@ -109,7 +109,7 @@ start_server {tags {"cli"}} {
test_interactive_cli "INFO response should be printed raw" {
set lines [split [run_command $fd info] "\n"]
foreach line $lines {
assert [regexp {^$|^#|^[a-z0-9_]+:.+} $line]
assert [regexp {^$|^#|^[^#:]+:} $line]
}
}
+9 -7
View File
@@ -39,17 +39,19 @@ start_server {tags {"repl"}} {
}
test {No write if min-slaves-max-lag is > of the slave lag} {
r -1 deferred 1
r config set min-slaves-to-write 1
r config set min-slaves-max-lag 2
r -1 debug sleep 6
exec kill -SIGSTOP [srv -1 pid]
assert {[r set foo 12345] eq {OK}}
after 4000
wait_for_condition 100 100 {
[catch {r set foo 12345}] != 0
} else {
fail "Master didn't become readonly"
}
catch {r set foo 12345} err
assert {[r -1 read] eq {OK}}
r -1 deferred 0
set err
} {NOREPLICAS*}
assert_match {NOREPLICAS*} $err
}
exec kill -SIGCONT [srv -1 pid]
test {min-slaves-to-write is ignored by slaves} {
r config set min-slaves-to-write 1
+1 -1
View File
@@ -1,4 +1,4 @@
start_server {tags {"repl"}} {
start_server {tags {"repl network"}} {
start_server {} {
set master [srv -1 client]
+191 -3
View File
@@ -1,4 +1,11 @@
start_server {tags {"repl"} overrides {hz 100}} {
proc log_file_matches {log pattern} {
set fp [open $log r]
set content [read $fp]
close $fp
string match $pattern $content
}
start_server {tags {"repl network"}} {
set slave [srv 0 client]
set slave_host [srv 0 host]
set slave_port [srv 0 port]
@@ -70,7 +77,29 @@ start_server {tags {"repl"}} {
assert_equal [$A debug digest] [$B debug digest]
}
test {GETSET replication} {
$A config resetstat
$A config set loglevel debug
$B config set loglevel debug
r set test foo
assert_equal [r getset test bar] foo
wait_for_condition 500 10 {
[$A get test] eq "bar"
} else {
fail "getset wasn't propagated"
}
assert_equal [r set test vaz get] bar
wait_for_condition 500 10 {
[$A get test] eq "vaz"
} else {
fail "set get wasn't propagated"
}
assert_match {*calls=3,*} [cmdrstat set $A]
assert_match {} [cmdrstat getset $A]
}
test {BRPOPLPUSH replication, when blocking against empty list} {
$A config resetstat
set rd [redis_deferring_client]
$rd brpoplpush a b 5
r lpush a foo
@@ -79,9 +108,12 @@ start_server {tags {"repl"}} {
} else {
fail "Master and replica have different digest: [$A debug digest] VS [$B debug digest]"
}
assert_match {*calls=1,*} [cmdrstat rpoplpush $A]
assert_match {} [cmdrstat lmove $A]
}
test {BRPOPLPUSH replication, list exists} {
$A config resetstat
set rd [redis_deferring_client]
r lpush c 1
r lpush c 2
@@ -89,6 +121,39 @@ start_server {tags {"repl"}} {
$rd brpoplpush c d 5
after 1000
assert_equal [$A debug digest] [$B debug digest]
assert_match {*calls=1,*} [cmdrstat rpoplpush $A]
assert_match {} [cmdrstat lmove $A]
}
foreach wherefrom {left right} {
foreach whereto {left right} {
test "BLMOVE ($wherefrom, $whereto) replication, when blocking against empty list" {
$A config resetstat
set rd [redis_deferring_client]
$rd blmove a b $wherefrom $whereto 5
r lpush a foo
wait_for_condition 50 100 {
[$A debug digest] eq [$B debug digest]
} else {
fail "Master and replica have different digest: [$A debug digest] VS [$B debug digest]"
}
assert_match {*calls=1,*} [cmdrstat lmove $A]
assert_match {} [cmdrstat rpoplpush $A]
}
test "BLMOVE ($wherefrom, $whereto) replication, list exists" {
$A config resetstat
set rd [redis_deferring_client]
r lpush c 1
r lpush c 2
r lpush c 3
$rd blmove c d $wherefrom $whereto 5
after 1000
assert_equal [$A debug digest] [$B debug digest]
assert_match {*calls=1,*} [cmdrstat lmove $A]
assert_match {} [cmdrstat rpoplpush $A]
}
}
}
test {BLPOP followed by role change, issue #2473} {
@@ -400,7 +465,12 @@ test {diskless loading short read} {
$master config set repl-diskless-sync yes
$master config set rdbcompression no
$replica config set repl-diskless-load swapdb
$master config set hz 500
$replica config set hz 500
$master config set dynamic-hz no
$replica config set dynamic-hz no
# Try to fill the master with all types of data types / encodings
set start [clock clicks -milliseconds]
for {set k 0} {$k < 3} {incr k} {
for {set i 0} {$i < 10} {incr i} {
r set "$k int_$i" [expr {int(rand()*10000)}]
@@ -422,14 +492,21 @@ test {diskless loading short read} {
}
}
if {$::verbose} {
set end [clock clicks -milliseconds]
set duration [expr $end - $start]
puts "filling took $duration ms (TODO: use pipeline)"
set start [clock clicks -milliseconds]
}
# Start the replication process...
set loglines [count_log_lines -1]
$master config set repl-diskless-sync-delay 0
$replica replicaof $master_host $master_port
# kill the replication at various points
set attempts 3
if {$::accurate} { set attempts 10 }
set attempts 100
if {$::accurate} { set attempts 500 }
for {set i 0} {$i < $attempts} {incr i} {
# wait for the replica to start reading the rdb
# using the log file since the replica only responds to INFO once in 2mb
@@ -462,6 +539,11 @@ test {diskless loading short read} {
fail "Replica didn't disconnect"
}
}
if {$::verbose} {
set end [clock clicks -milliseconds]
set duration [expr $end - $start]
puts "test took $duration ms"
}
# enable fast shutdown
$master config set rdb-key-save-delay 0
}
@@ -635,6 +717,47 @@ start_server {tags {"repl"}} {
}
}
test "diskless replication child being killed is collected" {
# when diskless master is waiting for the replica to become writable
# it removes the read event from the rdb pipe so if the child gets killed
# the replica will hung. and the master may not collect the pid with wait3
start_server {tags {"repl"}} {
set master [srv 0 client]
set master_host [srv 0 host]
set master_port [srv 0 port]
set master_pid [srv 0 pid]
$master config set repl-diskless-sync yes
$master config set repl-diskless-sync-delay 0
# put enough data in the db that the rdb file will be bigger than the socket buffers
$master debug populate 20000 test 10000
$master config set rdbcompression no
start_server {} {
set replica [srv 0 client]
set loglines [count_log_lines 0]
$replica config set repl-diskless-load swapdb
$replica config set key-load-delay 1000000
$replica replicaof $master_host $master_port
# wait for the replicas to start reading the rdb
wait_for_log_messages 0 {"*Loading DB in memory*"} $loglines 800 10
# wait to be sure the eplica is hung and the master is blocked on write
after 500
# simulate the OOM killer or anyone else kills the child
set fork_child_pid [get_child_pid -1]
exec kill -9 $fork_child_pid
# wait for the parent to notice the child have exited
wait_for_condition 50 100 {
[s -1 rdb_bgsave_in_progress] == 0
} else {
fail "rdb child didn't terminate"
}
}
}
}
test {replicaof right after disconnection} {
# this is a rare race condition that was reproduced sporadically by the psync2 unit.
# see details in #7205
@@ -686,3 +809,68 @@ test {replicaof right after disconnection} {
}
}
}
test {Kill rdb child process if its dumping RDB is not useful} {
start_server {tags {"repl"}} {
set slave1 [srv 0 client]
start_server {} {
set slave2 [srv 0 client]
start_server {} {
set master [srv 0 client]
set master_host [srv 0 host]
set master_port [srv 0 port]
for {set i 0} {$i < 10} {incr i} {
$master set $i $i
}
# Generating RDB will cost 10s(10 * 1s)
$master config set rdb-key-save-delay 1000000
$master config set repl-diskless-sync no
$master config set save ""
$slave1 slaveof $master_host $master_port
$slave2 slaveof $master_host $master_port
# Wait for starting child
wait_for_condition 50 100 {
([s 0 rdb_bgsave_in_progress] == 1) &&
([string match "*wait_bgsave*" [s 0 slave0]]) &&
([string match "*wait_bgsave*" [s 0 slave1]])
} else {
fail "rdb child didn't start"
}
# Slave1 disconnect with master
$slave1 slaveof no one
# Shouldn't kill child since another slave wait for rdb
after 100
assert {[s 0 rdb_bgsave_in_progress] == 1}
# Slave2 disconnect with master
$slave2 slaveof no one
# Should kill child
wait_for_condition 20 10 {
[s 0 rdb_bgsave_in_progress] eq 0
} else {
fail "can't kill rdb child"
}
# If have save parameters, won't kill child
$master config set save "900 1"
$slave1 slaveof $master_host $master_port
$slave2 slaveof $master_host $master_port
wait_for_condition 50 100 {
([s 0 rdb_bgsave_in_progress] == 1) &&
([string match "*wait_bgsave*" [s 0 slave0]]) &&
([string match "*wait_bgsave*" [s 0 slave1]])
} else {
fail "rdb child didn't start"
}
$slave1 slaveof no one
$slave2 slaveof no one
after 200
assert {[s 0 rdb_bgsave_in_progress] == 1}
catch {$master shutdown nosave}
}
}
}
}
+18 -7
View File
@@ -2,13 +2,18 @@
# find the OS
uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not')
# Compile flags for linux / osx
ifeq ($(uname_S),Linux)
SHOBJ_CFLAGS ?= -W -Wall -fno-common -g -ggdb -std=c99 -O2
SHOBJ_LDFLAGS ?= -shared
else
ifeq ($(uname_S),Darwin)
SHOBJ_CFLAGS ?= -W -Wall -dynamic -fno-common -g -ggdb -std=c99 -O2
SHOBJ_LDFLAGS ?= -bundle -undefined dynamic_lookup
else # Linux, others
SHOBJ_CFLAGS ?= -W -Wall -fno-common -g -ggdb -std=c99 -O2
SHOBJ_LDFLAGS ?= -shared
endif
# Needed to satisfy __stack_chk_fail_local on Linux with -m32, due to gcc
# -fstack-protector by default. Breaks on FreeBSD so we exclude it.
ifneq ($(uname_S),FreeBSD)
LIBS = -lc
endif
TEST_MODULES = \
@@ -20,13 +25,19 @@ TEST_MODULES = \
misc.so \
hooks.so \
blockonkeys.so \
blockonbackground.so \
scan.so \
datatype.so \
auth.so \
keyspace_events.so \
blockedclient.so \
getkeys.so \
timers.so
test_lazyfree.so \
timer.so \
defragtest.so \
hash.so \
zset.so \
stream.so
.PHONY: all
@@ -40,7 +51,7 @@ all: $(TEST_MODULES)
$(CC) -I../../src $(CFLAGS) $(SHOBJ_CFLAGS) -fPIC -c $< -o $@
%.so: %.xo
$(LD) -o $@ $< $(SHOBJ_LDFLAGS) $(LDFLAGS) $(LIBS) -lc
$(LD) -o $@ $< $(SHOBJ_LDFLAGS) $(LDFLAGS) $(LIBS)
.PHONY: clean
+11
View File
@@ -65,6 +65,12 @@ int acquire_gil(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
return REDISMODULE_OK;
}
if ((allFlags & REDISMODULE_CTX_FLAGS_DENY_BLOCKING) &&
(flags & REDISMODULE_CTX_FLAGS_DENY_BLOCKING)) {
RedisModule_ReplyWithSimpleString(ctx, "Blocked client is not allowed");
return REDISMODULE_OK;
}
/* This command handler tries to acquire the GIL twice
* once in the worker thread using "RedisModule_ThreadSafeContextLock"
* second in the sub-worker thread
@@ -137,6 +143,11 @@ int do_bg_rm_call(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
RedisModule_ReplyWithSimpleString(ctx, "Blocked client is not supported inside multi");
return REDISMODULE_OK;
}
if ((allFlags & REDISMODULE_CTX_FLAGS_DENY_BLOCKING) &&
(flags & REDISMODULE_CTX_FLAGS_DENY_BLOCKING)) {
RedisModule_ReplyWithSimpleString(ctx, "Blocked client is not allowed");
return REDISMODULE_OK;
}
/* Make a copy of the arguments and pass them to the thread. */
bg_call_data *bg = RedisModule_Alloc(sizeof(bg_call_data));
+219
View File
@@ -0,0 +1,219 @@
#define REDISMODULE_EXPERIMENTAL_API
#define _XOPEN_SOURCE 700
#include "redismodule.h"
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#define UNUSED(x) (void)(x)
/* Reply callback for blocking command BLOCK.DEBUG */
int HelloBlock_Reply(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
UNUSED(argv);
UNUSED(argc);
int *myint = RedisModule_GetBlockedClientPrivateData(ctx);
return RedisModule_ReplyWithLongLong(ctx,*myint);
}
/* Timeout callback for blocking command BLOCK.DEBUG */
int HelloBlock_Timeout(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
UNUSED(argv);
UNUSED(argc);
RedisModuleBlockedClient *bc = RedisModule_GetBlockedClientHandle(ctx);
RedisModule_BlockedClientMeasureTimeEnd(bc);
return RedisModule_ReplyWithSimpleString(ctx,"Request timedout");
}
/* Private data freeing callback for BLOCK.DEBUG command. */
void HelloBlock_FreeData(RedisModuleCtx *ctx, void *privdata) {
UNUSED(ctx);
RedisModule_Free(privdata);
}
/* The thread entry point that actually executes the blocking part
* of the command BLOCK.DEBUG. */
void *BlockDebug_ThreadMain(void *arg) {
void **targ = arg;
RedisModuleBlockedClient *bc = targ[0];
long long delay = (unsigned long)targ[1];
long long enable_time_track = (unsigned long)targ[2];
if (enable_time_track)
RedisModule_BlockedClientMeasureTimeStart(bc);
RedisModule_Free(targ);
struct timespec ts;
ts.tv_sec = delay / 1000;
ts.tv_nsec = (delay % 1000) * 1000000;
nanosleep(&ts, NULL);
int *r = RedisModule_Alloc(sizeof(int));
*r = rand();
if (enable_time_track)
RedisModule_BlockedClientMeasureTimeEnd(bc);
RedisModule_UnblockClient(bc,r);
return NULL;
}
/* The thread entry point that actually executes the blocking part
* of the command BLOCK.DOUBLE_DEBUG. */
void *DoubleBlock_ThreadMain(void *arg) {
void **targ = arg;
RedisModuleBlockedClient *bc = targ[0];
long long delay = (unsigned long)targ[1];
RedisModule_BlockedClientMeasureTimeStart(bc);
RedisModule_Free(targ);
struct timespec ts;
ts.tv_sec = delay / 1000;
ts.tv_nsec = (delay % 1000) * 1000000;
nanosleep(&ts, NULL);
int *r = RedisModule_Alloc(sizeof(int));
*r = rand();
RedisModule_BlockedClientMeasureTimeEnd(bc);
/* call again RedisModule_BlockedClientMeasureTimeStart() and
* RedisModule_BlockedClientMeasureTimeEnd and ensure that the
* total execution time is 2x the delay. */
RedisModule_BlockedClientMeasureTimeStart(bc);
nanosleep(&ts, NULL);
RedisModule_BlockedClientMeasureTimeEnd(bc);
RedisModule_UnblockClient(bc,r);
return NULL;
}
void HelloBlock_Disconnected(RedisModuleCtx *ctx, RedisModuleBlockedClient *bc) {
RedisModule_Log(ctx,"warning","Blocked client %p disconnected!",
(void*)bc);
}
/* BLOCK.DEBUG <delay_ms> <timeout_ms> -- Block for <count> milliseconds, then reply with
* a random number. Timeout is the command timeout, so that you can test
* what happens when the delay is greater than the timeout. */
int HelloBlock_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 3) return RedisModule_WrongArity(ctx);
long long delay;
long long timeout;
if (RedisModule_StringToLongLong(argv[1],&delay) != REDISMODULE_OK) {
return RedisModule_ReplyWithError(ctx,"ERR invalid count");
}
if (RedisModule_StringToLongLong(argv[2],&timeout) != REDISMODULE_OK) {
return RedisModule_ReplyWithError(ctx,"ERR invalid count");
}
pthread_t tid;
RedisModuleBlockedClient *bc = RedisModule_BlockClient(ctx,HelloBlock_Reply,HelloBlock_Timeout,HelloBlock_FreeData,timeout);
/* Here we set a disconnection handler, however since this module will
* block in sleep() in a thread, there is not much we can do in the
* callback, so this is just to show you the API. */
RedisModule_SetDisconnectCallback(bc,HelloBlock_Disconnected);
/* Now that we setup a blocking client, we need to pass the control
* to the thread. However we need to pass arguments to the thread:
* the delay and a reference to the blocked client handle. */
void **targ = RedisModule_Alloc(sizeof(void*)*3);
targ[0] = bc;
targ[1] = (void*)(unsigned long) delay;
// pass 1 as flag to enable time tracking
targ[2] = (void*)(unsigned long) 1;
if (pthread_create(&tid,NULL,BlockDebug_ThreadMain,targ) != 0) {
RedisModule_AbortBlock(bc);
return RedisModule_ReplyWithError(ctx,"-ERR Can't start thread");
}
return REDISMODULE_OK;
}
/* BLOCK.DEBUG_NOTRACKING <delay_ms> <timeout_ms> -- Block for <count> milliseconds, then reply with
* a random number. Timeout is the command timeout, so that you can test
* what happens when the delay is greater than the timeout.
* this command does not track background time so the background time should no appear in stats*/
int HelloBlockNoTracking_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 3) return RedisModule_WrongArity(ctx);
long long delay;
long long timeout;
if (RedisModule_StringToLongLong(argv[1],&delay) != REDISMODULE_OK) {
return RedisModule_ReplyWithError(ctx,"ERR invalid count");
}
if (RedisModule_StringToLongLong(argv[2],&timeout) != REDISMODULE_OK) {
return RedisModule_ReplyWithError(ctx,"ERR invalid count");
}
pthread_t tid;
RedisModuleBlockedClient *bc = RedisModule_BlockClient(ctx,HelloBlock_Reply,HelloBlock_Timeout,HelloBlock_FreeData,timeout);
/* Here we set a disconnection handler, however since this module will
* block in sleep() in a thread, there is not much we can do in the
* callback, so this is just to show you the API. */
RedisModule_SetDisconnectCallback(bc,HelloBlock_Disconnected);
/* Now that we setup a blocking client, we need to pass the control
* to the thread. However we need to pass arguments to the thread:
* the delay and a reference to the blocked client handle. */
void **targ = RedisModule_Alloc(sizeof(void*)*3);
targ[0] = bc;
targ[1] = (void*)(unsigned long) delay;
// pass 0 as flag to enable time tracking
targ[2] = (void*)(unsigned long) 0;
if (pthread_create(&tid,NULL,BlockDebug_ThreadMain,targ) != 0) {
RedisModule_AbortBlock(bc);
return RedisModule_ReplyWithError(ctx,"-ERR Can't start thread");
}
return REDISMODULE_OK;
}
/* BLOCK.DOUBLE_DEBUG <delay_ms> -- Block for 2 x <count> milliseconds,
* then reply with a random number.
* This command is used to test multiple calls to RedisModule_BlockedClientMeasureTimeStart()
* and RedisModule_BlockedClientMeasureTimeEnd() within the same execution. */
int HelloDoubleBlock_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 2) return RedisModule_WrongArity(ctx);
long long delay;
if (RedisModule_StringToLongLong(argv[1],&delay) != REDISMODULE_OK) {
return RedisModule_ReplyWithError(ctx,"ERR invalid count");
}
pthread_t tid;
RedisModuleBlockedClient *bc = RedisModule_BlockClient(ctx,HelloBlock_Reply,HelloBlock_Timeout,HelloBlock_FreeData,0);
/* Now that we setup a blocking client, we need to pass the control
* to the thread. However we need to pass arguments to the thread:
* the delay and a reference to the blocked client handle. */
void **targ = RedisModule_Alloc(sizeof(void*)*2);
targ[0] = bc;
targ[1] = (void*)(unsigned long) delay;
if (pthread_create(&tid,NULL,DoubleBlock_ThreadMain,targ) != 0) {
RedisModule_AbortBlock(bc);
return RedisModule_ReplyWithError(ctx,"-ERR Can't start thread");
}
return REDISMODULE_OK;
}
int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
UNUSED(argv);
UNUSED(argc);
if (RedisModule_Init(ctx,"block",1,REDISMODULE_APIVER_1)
== REDISMODULE_ERR) return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"block.debug",
HelloBlock_RedisCommand,"",0,0,0) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"block.double_debug",
HelloDoubleBlock_RedisCommand,"",0,0,0) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"block.debug_no_track",
HelloBlockNoTracking_RedisCommand,"",0,0,0) == REDISMODULE_ERR)
return REDISMODULE_ERR;
return REDISMODULE_OK;
}
+167
View File
@@ -2,6 +2,7 @@
#include "redismodule.h"
#include <string.h>
#include <strings.h>
#include <assert.h>
#include <unistd.h>
@@ -65,6 +66,8 @@ int get_fsl(RedisModuleCtx *ctx, RedisModuleString *keyname, int mode, int creat
RedisModule_CloseKey(key);
if (reply_on_failure)
RedisModule_ReplyWithError(ctx, REDISMODULE_ERRORMSG_WRONGTYPE);
RedisModuleCallReply *reply = RedisModule_Call(ctx, "INCR", "c", "fsl_wrong_type");
RedisModule_FreeCallReply(reply);
return 0;
}
@@ -298,6 +301,154 @@ int fsl_getall(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
return REDISMODULE_OK;
}
/* Callback for blockonkeys_popall */
int blockonkeys_popall_reply_callback(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
REDISMODULE_NOT_USED(argc);
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_WRITE);
if (RedisModule_KeyType(key) == REDISMODULE_KEYTYPE_LIST) {
RedisModuleString *elem;
long len = 0;
RedisModule_ReplyWithArray(ctx, REDISMODULE_POSTPONED_ARRAY_LEN);
while ((elem = RedisModule_ListPop(key, REDISMODULE_LIST_HEAD)) != NULL) {
len++;
RedisModule_ReplyWithString(ctx, elem);
RedisModule_FreeString(ctx, elem);
}
RedisModule_ReplySetArrayLength(ctx, len);
} else {
RedisModule_ReplyWithError(ctx, "ERR Not a list");
}
RedisModule_CloseKey(key);
return REDISMODULE_OK;
}
int blockonkeys_popall_timeout_callback(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
REDISMODULE_NOT_USED(argv);
REDISMODULE_NOT_USED(argc);
return RedisModule_ReplyWithError(ctx, "ERR Timeout");
}
/* BLOCKONKEYS.POPALL key
*
* Blocks on an empty key for up to 3 seconds. When unblocked by a list
* operation like LPUSH, all the elements are popped and returned. Fails with an
* error on timeout. */
int blockonkeys_popall(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 2)
return RedisModule_WrongArity(ctx);
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_READ);
if (RedisModule_KeyType(key) == REDISMODULE_KEYTYPE_EMPTY) {
RedisModule_BlockClientOnKeys(ctx, blockonkeys_popall_reply_callback,
blockonkeys_popall_timeout_callback,
NULL, 3000, &argv[1], 1, NULL);
} else {
RedisModule_ReplyWithError(ctx, "ERR Key not empty");
}
RedisModule_CloseKey(key);
return REDISMODULE_OK;
}
/* BLOCKONKEYS.LPUSH key val [val ..]
* BLOCKONKEYS.LPUSH_UNBLOCK key val [val ..]
*
* A module equivalent of LPUSH. If the name LPUSH_UNBLOCK is used,
* RM_SignalKeyAsReady() is also called. */
int blockonkeys_lpush(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc < 3)
return RedisModule_WrongArity(ctx);
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_WRITE);
if (RedisModule_KeyType(key) != REDISMODULE_KEYTYPE_EMPTY &&
RedisModule_KeyType(key) != REDISMODULE_KEYTYPE_LIST) {
RedisModule_ReplyWithError(ctx, REDISMODULE_ERRORMSG_WRONGTYPE);
} else {
for (int i = 2; i < argc; i++) {
if (RedisModule_ListPush(key, REDISMODULE_LIST_HEAD,
argv[i]) != REDISMODULE_OK) {
RedisModule_CloseKey(key);
return RedisModule_ReplyWithError(ctx, "ERR Push failed");
}
}
}
RedisModule_CloseKey(key);
/* signal key as ready if the command is lpush_unblock */
size_t len;
const char *str = RedisModule_StringPtrLen(argv[0], &len);
if (!strncasecmp(str, "blockonkeys.lpush_unblock", len)) {
RedisModule_SignalKeyAsReady(ctx, argv[1]);
}
return RedisModule_ReplyWithSimpleString(ctx, "OK");
}
/* Callback for the BLOCKONKEYS.BLPOPN command */
int blockonkeys_blpopn_reply_callback(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
REDISMODULE_NOT_USED(argc);
long long n;
RedisModule_StringToLongLong(argv[2], &n);
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_WRITE);
int result;
if (RedisModule_KeyType(key) == REDISMODULE_KEYTYPE_LIST &&
RedisModule_ValueLength(key) >= (size_t)n) {
RedisModule_ReplyWithArray(ctx, n);
for (long i = 0; i < n; i++) {
RedisModuleString *elem = RedisModule_ListPop(key, REDISMODULE_LIST_HEAD);
RedisModule_ReplyWithString(ctx, elem);
RedisModule_FreeString(ctx, elem);
}
result = REDISMODULE_OK;
} else if (RedisModule_KeyType(key) == REDISMODULE_KEYTYPE_LIST ||
RedisModule_KeyType(key) == REDISMODULE_KEYTYPE_EMPTY) {
/* continue blocking */
result = REDISMODULE_ERR;
} else {
result = RedisModule_ReplyWithError(ctx, REDISMODULE_ERRORMSG_WRONGTYPE);
}
RedisModule_CloseKey(key);
return result;
}
int blockonkeys_blpopn_timeout_callback(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
REDISMODULE_NOT_USED(argv);
REDISMODULE_NOT_USED(argc);
return RedisModule_ReplyWithError(ctx, "ERR Timeout");
}
/* BLOCKONKEYS.BLPOPN key N
*
* Blocks until key has N elements and then pops them or fails after 3 seconds.
*/
int blockonkeys_blpopn(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc < 3) return RedisModule_WrongArity(ctx);
long long n;
if (RedisModule_StringToLongLong(argv[2], &n) != REDISMODULE_OK) {
return RedisModule_ReplyWithError(ctx, "ERR Invalid N");
}
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_WRITE);
int keytype = RedisModule_KeyType(key);
if (keytype != REDISMODULE_KEYTYPE_EMPTY &&
keytype != REDISMODULE_KEYTYPE_LIST) {
RedisModule_ReplyWithError(ctx, REDISMODULE_ERRORMSG_WRONGTYPE);
} else if (keytype == REDISMODULE_KEYTYPE_LIST &&
RedisModule_ValueLength(key) >= (size_t)n) {
RedisModule_ReplyWithArray(ctx, n);
for (long i = 0; i < n; i++) {
RedisModuleString *elem = RedisModule_ListPop(key, REDISMODULE_LIST_HEAD);
RedisModule_ReplyWithString(ctx, elem);
RedisModule_FreeString(ctx, elem);
}
} else {
RedisModule_BlockClientOnKeys(ctx, blockonkeys_blpopn_reply_callback,
blockonkeys_blpopn_timeout_callback,
NULL, 3000, &argv[1], 1, NULL);
}
RedisModule_CloseKey(key);
return REDISMODULE_OK;
}
int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
REDISMODULE_NOT_USED(argv);
REDISMODULE_NOT_USED(argc);
@@ -334,5 +485,21 @@ int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
if (RedisModule_CreateCommand(ctx,"fsl.getall",fsl_getall,"",0,0,0) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx, "blockonkeys.popall", blockonkeys_popall,
"", 1, 1, 1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx, "blockonkeys.lpush", blockonkeys_lpush,
"", 1, 1, 1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx, "blockonkeys.lpush_unblock", blockonkeys_lpush,
"", 1, 1, 1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx, "blockonkeys.blpopn", blockonkeys_blpopn,
"", 1, 1, 1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
return REDISMODULE_OK;
}
+34 -3
View File
@@ -41,6 +41,32 @@ static void datatype_free(void *value) {
}
}
static void *datatype_copy(RedisModuleString *fromkey, RedisModuleString *tokey, const void *value) {
const DataType *old = value;
/* Answers to ultimate questions cannot be copied! */
if (old->intval == 42)
return NULL;
DataType *new = (DataType *) RedisModule_Alloc(sizeof(DataType));
new->intval = old->intval;
new->strval = RedisModule_CreateStringFromString(NULL, old->strval);
/* Breaking the rules here! We return a copy that also includes traces
* of fromkey/tokey to confirm we get what we expect.
*/
size_t len;
const char *str = RedisModule_StringPtrLen(fromkey, &len);
RedisModule_StringAppendBuffer(NULL, new->strval, "/", 1);
RedisModule_StringAppendBuffer(NULL, new->strval, str, len);
RedisModule_StringAppendBuffer(NULL, new->strval, "/", 1);
str = RedisModule_StringPtrLen(tokey, &len);
RedisModule_StringAppendBuffer(NULL, new->strval, str, len);
return new;
}
static int datatype_set(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 4) {
RedisModule_WrongArity(ctx);
@@ -97,9 +123,13 @@ static int datatype_get(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
DataType *dt = RedisModule_ModuleTypeGetValue(key);
RedisModule_CloseKey(key);
RedisModule_ReplyWithArray(ctx, 2);
RedisModule_ReplyWithLongLong(ctx, dt->intval);
RedisModule_ReplyWithString(ctx, dt->strval);
if (!dt) {
RedisModule_ReplyWithNullArray(ctx);
} else {
RedisModule_ReplyWithArray(ctx, 2);
RedisModule_ReplyWithLongLong(ctx, dt->intval);
RedisModule_ReplyWithString(ctx, dt->strval);
}
return REDISMODULE_OK;
}
@@ -161,6 +191,7 @@ int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
.rdb_load = datatype_load,
.rdb_save = datatype_save,
.free = datatype_free,
.copy = datatype_copy
};
datatype = RedisModule_CreateDataType(ctx, "test___dt", 1, &datatype_methods);
+234
View File
@@ -0,0 +1,234 @@
/* A module that implements defrag callback mechanisms.
*/
#define REDISMODULE_EXPERIMENTAL_API
#include "redismodule.h"
static RedisModuleType *FragType;
struct FragObject {
unsigned long len;
void **values;
int maxstep;
};
/* Make sure we get the expected cursor */
unsigned long int last_set_cursor = 0;
unsigned long int datatype_attempts = 0;
unsigned long int datatype_defragged = 0;
unsigned long int datatype_resumes = 0;
unsigned long int datatype_wrong_cursor = 0;
unsigned long int global_attempts = 0;
unsigned long int global_defragged = 0;
int global_strings_len = 0;
RedisModuleString **global_strings = NULL;
static void createGlobalStrings(RedisModuleCtx *ctx, int count)
{
global_strings_len = count;
global_strings = RedisModule_Alloc(sizeof(RedisModuleString *) * count);
for (int i = 0; i < count; i++) {
global_strings[i] = RedisModule_CreateStringFromLongLong(ctx, i);
}
}
static int defragGlobalStrings(RedisModuleDefragCtx *ctx)
{
for (int i = 0; i < global_strings_len; i++) {
RedisModuleString *new = RedisModule_DefragRedisModuleString(ctx, global_strings[i]);
global_attempts++;
if (new != NULL) {
global_strings[i] = new;
global_defragged++;
}
}
return 0;
}
static void FragInfo(RedisModuleInfoCtx *ctx, int for_crash_report) {
REDISMODULE_NOT_USED(for_crash_report);
RedisModule_InfoAddSection(ctx, "stats");
RedisModule_InfoAddFieldLongLong(ctx, "datatype_attempts", datatype_attempts);
RedisModule_InfoAddFieldLongLong(ctx, "datatype_defragged", datatype_defragged);
RedisModule_InfoAddFieldLongLong(ctx, "datatype_resumes", datatype_resumes);
RedisModule_InfoAddFieldLongLong(ctx, "datatype_wrong_cursor", datatype_wrong_cursor);
RedisModule_InfoAddFieldLongLong(ctx, "global_attempts", global_attempts);
RedisModule_InfoAddFieldLongLong(ctx, "global_defragged", global_defragged);
}
struct FragObject *createFragObject(unsigned long len, unsigned long size, int maxstep) {
struct FragObject *o = RedisModule_Alloc(sizeof(*o));
o->len = len;
o->values = RedisModule_Alloc(sizeof(RedisModuleString*) * len);
o->maxstep = maxstep;
for (unsigned long i = 0; i < len; i++) {
o->values[i] = RedisModule_Calloc(1, size);
}
return o;
}
/* FRAG.RESETSTATS */
static int fragResetStatsCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
REDISMODULE_NOT_USED(argv);
REDISMODULE_NOT_USED(argc);
datatype_attempts = 0;
datatype_defragged = 0;
datatype_resumes = 0;
datatype_wrong_cursor = 0;
global_attempts = 0;
global_defragged = 0;
RedisModule_ReplyWithSimpleString(ctx, "OK");
return REDISMODULE_OK;
}
/* FRAG.CREATE key len size maxstep */
static int fragCreateCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 5)
return RedisModule_WrongArity(ctx);
RedisModuleKey *key = RedisModule_OpenKey(ctx,argv[1],
REDISMODULE_READ|REDISMODULE_WRITE);
int type = RedisModule_KeyType(key);
if (type != REDISMODULE_KEYTYPE_EMPTY)
{
return RedisModule_ReplyWithError(ctx, "ERR key exists");
}
long long len;
if ((RedisModule_StringToLongLong(argv[2], &len) != REDISMODULE_OK)) {
return RedisModule_ReplyWithError(ctx, "ERR invalid len");
}
long long size;
if ((RedisModule_StringToLongLong(argv[3], &size) != REDISMODULE_OK)) {
return RedisModule_ReplyWithError(ctx, "ERR invalid size");
}
long long maxstep;
if ((RedisModule_StringToLongLong(argv[4], &maxstep) != REDISMODULE_OK)) {
return RedisModule_ReplyWithError(ctx, "ERR invalid maxstep");
}
struct FragObject *o = createFragObject(len, size, maxstep);
RedisModule_ModuleTypeSetValue(key, FragType, o);
RedisModule_ReplyWithSimpleString(ctx, "OK");
RedisModule_CloseKey(key);
return REDISMODULE_OK;
}
void FragFree(void *value) {
struct FragObject *o = value;
for (unsigned long i = 0; i < o->len; i++)
RedisModule_Free(o->values[i]);
RedisModule_Free(o->values);
RedisModule_Free(o);
}
size_t FragFreeEffort(RedisModuleString *key, const void *value) {
REDISMODULE_NOT_USED(key);
const struct FragObject *o = value;
return o->len;
}
int FragDefrag(RedisModuleDefragCtx *ctx, RedisModuleString *key, void **value) {
REDISMODULE_NOT_USED(key);
unsigned long i = 0;
int steps = 0;
/* Attempt to get cursor, validate it's what we're exepcting */
if (RedisModule_DefragCursorGet(ctx, &i) == REDISMODULE_OK) {
if (i > 0) datatype_resumes++;
/* Validate we're expecting this cursor */
if (i != last_set_cursor) datatype_wrong_cursor++;
} else {
if (last_set_cursor != 0) datatype_wrong_cursor++;
}
/* Attempt to defrag the object itself */
datatype_attempts++;
struct FragObject *o = RedisModule_DefragAlloc(ctx, *value);
if (o == NULL) {
/* Not defragged */
o = *value;
} else {
/* Defragged */
*value = o;
datatype_defragged++;
}
/* Deep defrag now */
for (; i < o->len; i++) {
datatype_attempts++;
void *new = RedisModule_DefragAlloc(ctx, o->values[i]);
if (new) {
o->values[i] = new;
datatype_defragged++;
}
if ((o->maxstep && ++steps > o->maxstep) ||
((i % 64 == 0) && RedisModule_DefragShouldStop(ctx)))
{
RedisModule_DefragCursorSet(ctx, i);
last_set_cursor = i;
return 1;
}
}
last_set_cursor = 0;
return 0;
}
int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
REDISMODULE_NOT_USED(argv);
REDISMODULE_NOT_USED(argc);
if (RedisModule_Init(ctx, "defragtest", 1, REDISMODULE_APIVER_1)
== REDISMODULE_ERR) return REDISMODULE_ERR;
if (RedisModule_GetTypeMethodVersion() < REDISMODULE_TYPE_METHOD_VERSION) {
return REDISMODULE_ERR;
}
long long glen;
if (argc != 1 || RedisModule_StringToLongLong(argv[0], &glen) == REDISMODULE_ERR) {
return REDISMODULE_ERR;
}
createGlobalStrings(ctx, glen);
RedisModuleTypeMethods tm = {
.version = REDISMODULE_TYPE_METHOD_VERSION,
.free = FragFree,
.free_effort = FragFreeEffort,
.defrag = FragDefrag
};
FragType = RedisModule_CreateDataType(ctx, "frag_type", 0, &tm);
if (FragType == NULL) return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx, "frag.create",
fragCreateCommand, "write deny-oom", 1, 1, 1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx, "frag.resetstats",
fragResetStatsCommand, "write deny-oom", 1, 1, 1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
RedisModule_RegisterInfoFunc(ctx, FragInfo);
RedisModule_RegisterDefragFunc(ctx, defragGlobalStrings);
return REDISMODULE_OK;
}
+90
View File
@@ -0,0 +1,90 @@
#include "redismodule.h"
#include <strings.h>
#include <errno.h>
#include <stdlib.h>
/* If a string is ":deleted:", the special value for deleted hash fields is
* returned; otherwise the input string is returned. */
static RedisModuleString *value_or_delete(RedisModuleString *s) {
if (!strcasecmp(RedisModule_StringPtrLen(s, NULL), ":delete:"))
return REDISMODULE_HASH_DELETE;
else
return s;
}
/* HASH.SET key flags field1 value1 [field2 value2 ..]
*
* Sets 1-4 fields. Returns the same as RedisModule_HashSet().
* Flags is a string of "nxa" where n = NX, x = XX, a = COUNT_ALL.
* To delete a field, use the value ":delete:".
*/
int hash_set(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc < 5 || argc % 2 == 0 || argc > 11)
return RedisModule_WrongArity(ctx);
RedisModule_AutoMemory(ctx);
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_WRITE);
size_t flags_len;
const char *flags_str = RedisModule_StringPtrLen(argv[2], &flags_len);
int flags = REDISMODULE_HASH_NONE;
for (size_t i = 0; i < flags_len; i++) {
switch (flags_str[i]) {
case 'n': flags |= REDISMODULE_HASH_NX; break;
case 'x': flags |= REDISMODULE_HASH_XX; break;
case 'a': flags |= REDISMODULE_HASH_COUNT_ALL; break;
}
}
/* Test some varargs. (In real-world, use a loop and set one at a time.) */
int result;
errno = 0;
if (argc == 5) {
result = RedisModule_HashSet(key, flags,
argv[3], value_or_delete(argv[4]),
NULL);
} else if (argc == 7) {
result = RedisModule_HashSet(key, flags,
argv[3], value_or_delete(argv[4]),
argv[5], value_or_delete(argv[6]),
NULL);
} else if (argc == 9) {
result = RedisModule_HashSet(key, flags,
argv[3], value_or_delete(argv[4]),
argv[5], value_or_delete(argv[6]),
argv[7], value_or_delete(argv[8]),
NULL);
} else if (argc == 11) {
result = RedisModule_HashSet(key, flags,
argv[3], value_or_delete(argv[4]),
argv[5], value_or_delete(argv[6]),
argv[7], value_or_delete(argv[8]),
argv[9], value_or_delete(argv[10]),
NULL);
} else {
return RedisModule_ReplyWithError(ctx, "ERR too many fields");
}
/* Check errno */
if (result == 0) {
if (errno == ENOTSUP)
return RedisModule_ReplyWithError(ctx, REDISMODULE_ERRORMSG_WRONGTYPE);
else
RedisModule_Assert(errno == ENOENT);
}
return RedisModule_ReplyWithLongLong(ctx, result);
}
int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
REDISMODULE_NOT_USED(argv);
REDISMODULE_NOT_USED(argc);
if (RedisModule_Init(ctx, "hash", 1, REDISMODULE_APIVER_1) ==
REDISMODULE_OK &&
RedisModule_CreateCommand(ctx, "hash.set", hash_set, "",
1, 1, 1) == REDISMODULE_OK) {
return REDISMODULE_OK;
} else {
return REDISMODULE_ERR;
}
}
+5
View File
@@ -21,6 +21,11 @@ void InfoFunc(RedisModuleInfoCtx *ctx, int for_crash_report) {
RedisModule_InfoAddFieldLongLong(ctx, "expires", 1);
RedisModule_InfoEndDictField(ctx);
RedisModule_InfoAddSection(ctx, "unsafe");
RedisModule_InfoBeginDictField(ctx, "unsafe:field");
RedisModule_InfoAddFieldLongLong(ctx, "value", 1);
RedisModule_InfoEndDictField(ctx);
if (for_crash_report) {
RedisModule_InfoAddSection(ctx, "Klingon");
RedisModule_InfoAddFieldCString(ctx, "one", "wa’");
+107 -2
View File
@@ -39,7 +39,7 @@
/** strores all the keys on which we got 'loaded' keyspace notification **/
RedisModuleDict *loaded_event_log = NULL;
static int KeySpace_Notification(RedisModuleCtx *ctx, int type, const char *event, RedisModuleString *key){
static int KeySpace_NotificationLoaded(RedisModuleCtx *ctx, int type, const char *event, RedisModuleString *key){
REDISMODULE_NOT_USED(ctx);
REDISMODULE_NOT_USED(type);
@@ -55,6 +55,29 @@ static int KeySpace_Notification(RedisModuleCtx *ctx, int type, const char *even
return REDISMODULE_OK;
}
static int KeySpace_NotificationGeneric(RedisModuleCtx *ctx, int type, const char *event, RedisModuleString *key) {
REDISMODULE_NOT_USED(type);
if (strcmp(event, "del") == 0) {
RedisModuleString *copykey = RedisModule_CreateStringPrintf(ctx, "%s_copy", RedisModule_StringPtrLen(key, NULL));
RedisModuleCallReply* rep = RedisModule_Call(ctx, "DEL", "s!", copykey);
RedisModule_FreeString(ctx, copykey);
RedisModule_FreeCallReply(rep);
int ctx_flags = RedisModule_GetContextFlags(ctx);
if (ctx_flags & REDISMODULE_CTX_FLAGS_LUA) {
RedisModuleCallReply* rep = RedisModule_Call(ctx, "INCR", "c", "lua");
RedisModule_FreeCallReply(rep);
}
if (ctx_flags & REDISMODULE_CTX_FLAGS_MULTI) {
RedisModuleCallReply* rep = RedisModule_Call(ctx, "INCR", "c", "multi");
RedisModule_FreeCallReply(rep);
}
}
return REDISMODULE_OK;
}
static int cmdIsKeyLoaded(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){
if(argc != 2){
return RedisModule_WrongArity(ctx);
@@ -75,6 +98,68 @@ static int cmdIsKeyLoaded(RedisModuleCtx *ctx, RedisModuleString **argv, int arg
return REDISMODULE_OK;
}
static int cmdDelKeyCopy(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 2)
return RedisModule_WrongArity(ctx);
RedisModuleCallReply* rep = RedisModule_Call(ctx, "DEL", "s!", argv[1]);
if (!rep) {
RedisModule_ReplyWithError(ctx, "NULL reply returned");
} else {
RedisModule_ReplyWithCallReply(ctx, rep);
RedisModule_FreeCallReply(rep);
}
return REDISMODULE_OK;
}
/* Call INCR and propagate using RM_Call with `!`. */
static int cmdIncrCase1(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 2)
return RedisModule_WrongArity(ctx);
RedisModuleCallReply* rep = RedisModule_Call(ctx, "INCR", "s!", argv[1]);
if (!rep) {
RedisModule_ReplyWithError(ctx, "NULL reply returned");
} else {
RedisModule_ReplyWithCallReply(ctx, rep);
RedisModule_FreeCallReply(rep);
}
return REDISMODULE_OK;
}
/* Call INCR and propagate using RM_Replicate. */
static int cmdIncrCase2(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 2)
return RedisModule_WrongArity(ctx);
RedisModuleCallReply* rep = RedisModule_Call(ctx, "INCR", "s", argv[1]);
if (!rep) {
RedisModule_ReplyWithError(ctx, "NULL reply returned");
} else {
RedisModule_ReplyWithCallReply(ctx, rep);
RedisModule_FreeCallReply(rep);
}
RedisModule_Replicate(ctx, "INCR", "s", argv[1]);
return REDISMODULE_OK;
}
/* Call INCR and propagate using RM_ReplicateVerbatim. */
static int cmdIncrCase3(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 2)
return RedisModule_WrongArity(ctx);
RedisModuleCallReply* rep = RedisModule_Call(ctx, "INCR", "s", argv[1]);
if (!rep) {
RedisModule_ReplyWithError(ctx, "NULL reply returned");
} else {
RedisModule_ReplyWithCallReply(ctx, rep);
RedisModule_FreeCallReply(rep);
}
RedisModule_ReplicateVerbatim(ctx);
return REDISMODULE_OK;
}
/* This function must be present on each Redis module. It is used in order to
* register the commands into the Redis server. */
int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
@@ -94,7 +179,11 @@ int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
return REDISMODULE_ERR;
}
if(RedisModule_SubscribeToKeyspaceEvents(ctx, REDISMODULE_NOTIFY_LOADED, KeySpace_Notification) != REDISMODULE_OK){
if(RedisModule_SubscribeToKeyspaceEvents(ctx, REDISMODULE_NOTIFY_LOADED, KeySpace_NotificationLoaded) != REDISMODULE_OK){
return REDISMODULE_ERR;
}
if(RedisModule_SubscribeToKeyspaceEvents(ctx, REDISMODULE_NOTIFY_GENERIC, KeySpace_NotificationGeneric) != REDISMODULE_OK){
return REDISMODULE_ERR;
}
@@ -102,6 +191,22 @@ int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
return REDISMODULE_ERR;
}
if (RedisModule_CreateCommand(ctx,"keyspace.del_key_copy", cmdDelKeyCopy,"",0,0,0) == REDISMODULE_ERR){
return REDISMODULE_ERR;
}
if (RedisModule_CreateCommand(ctx,"keyspace.incr_case1", cmdIncrCase1,"",0,0,0) == REDISMODULE_ERR){
return REDISMODULE_ERR;
}
if (RedisModule_CreateCommand(ctx,"keyspace.incr_case2", cmdIncrCase2,"",0,0,0) == REDISMODULE_ERR){
return REDISMODULE_ERR;
}
if (RedisModule_CreateCommand(ctx,"keyspace.incr_case3", cmdIncrCase3,"",0,0,0) == REDISMODULE_ERR){
return REDISMODULE_ERR;
}
return REDISMODULE_OK;
}
+29 -15
View File
@@ -51,18 +51,31 @@ void timerHandler(RedisModuleCtx *ctx, void *data) {
RedisModule_Replicate(ctx,"INCR","c","timer");
times++;
if (times < 10)
if (times < 3)
RedisModule_CreateTimer(ctx,100,timerHandler,NULL);
else
times = 0;
}
int propagateTestTimerCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
{
REDISMODULE_NOT_USED(argv);
REDISMODULE_NOT_USED(argc);
RedisModuleTimerID timer_id =
RedisModule_CreateTimer(ctx,100,timerHandler,NULL);
REDISMODULE_NOT_USED(timer_id);
RedisModule_ReplyWithSimpleString(ctx,"OK");
return REDISMODULE_OK;
}
/* The thread entry point. */
void *threadMain(void *arg) {
REDISMODULE_NOT_USED(arg);
RedisModuleCtx *ctx = RedisModule_GetThreadSafeContext(NULL);
RedisModule_SelectDb(ctx,9); /* Tests ran in database number 9. */
for (int i = 0; i < 10; i++) {
for (int i = 0; i < 3; i++) {
RedisModule_ThreadSafeContextLock(ctx);
RedisModule_Replicate(ctx,"INCR","c","a-from-thread");
RedisModule_Replicate(ctx,"INCR","c","b-from-thread");
@@ -72,15 +85,11 @@ void *threadMain(void *arg) {
return NULL;
}
int propagateTestCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
int propagateTestThreadCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
{
REDISMODULE_NOT_USED(argv);
REDISMODULE_NOT_USED(argc);
RedisModuleTimerID timer_id =
RedisModule_CreateTimer(ctx,100,timerHandler,NULL);
REDISMODULE_NOT_USED(timer_id);
pthread_t tid;
if (pthread_create(&tid,NULL,threadMain,NULL) != 0)
return RedisModule_ReplyWithError(ctx,"-ERR Can't start thread");
@@ -90,7 +99,7 @@ int propagateTestCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc
return REDISMODULE_OK;
}
int propagateTest2Command(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
int propagateTestSimpleCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
{
REDISMODULE_NOT_USED(argv);
REDISMODULE_NOT_USED(argc);
@@ -102,7 +111,7 @@ int propagateTest2Command(RedisModuleCtx *ctx, RedisModuleString **argv, int arg
return REDISMODULE_OK;
}
int propagateTest3Command(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
int propagateTestMixedCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
{
REDISMODULE_NOT_USED(argv);
REDISMODULE_NOT_USED(argc);
@@ -129,18 +138,23 @@ int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
if (RedisModule_Init(ctx,"propagate-test",1,REDISMODULE_APIVER_1)
== REDISMODULE_ERR) return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"propagate-test",
propagateTestCommand,
if (RedisModule_CreateCommand(ctx,"propagate-test.timer",
propagateTestTimerCommand,
"",1,1,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"propagate-test-2",
propagateTest2Command,
if (RedisModule_CreateCommand(ctx,"propagate-test.thread",
propagateTestThreadCommand,
"",1,1,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"propagate-test-3",
propagateTest3Command,
if (RedisModule_CreateCommand(ctx,"propagate-test.simple",
propagateTestSimpleCommand,
"",1,1,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"propagate-test.mixed",
propagateTestMixedCommand,
"",1,1,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
+258
View File
@@ -0,0 +1,258 @@
#include "redismodule.h"
#include <string.h>
#include <strings.h>
#include <assert.h>
#include <unistd.h>
#include <errno.h>
/* Command which adds a stream entry with automatic ID, like XADD *.
*
* Syntax: STREAM.ADD key field1 value1 [ field2 value2 ... ]
*
* The response is the ID of the added stream entry or an error message.
*/
int stream_add(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc < 2 || argc % 2 != 0) {
RedisModule_WrongArity(ctx);
return REDISMODULE_OK;
}
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_WRITE);
RedisModuleStreamID id;
if (RedisModule_StreamAdd(key, REDISMODULE_STREAM_ADD_AUTOID, &id,
&argv[2], (argc-2)/2) == REDISMODULE_OK) {
RedisModuleString *id_str = RedisModule_CreateStringFromStreamID(ctx, &id);
RedisModule_ReplyWithString(ctx, id_str);
RedisModule_FreeString(ctx, id_str);
} else {
RedisModule_ReplyWithError(ctx, "ERR StreamAdd failed");
}
RedisModule_CloseKey(key);
return REDISMODULE_OK;
}
/* Command which adds a stream entry N times.
*
* Syntax: STREAM.ADD key N field1 value1 [ field2 value2 ... ]
*
* Returns the number of successfully added entries.
*/
int stream_addn(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc < 3 || argc % 2 == 0) {
RedisModule_WrongArity(ctx);
return REDISMODULE_OK;
}
long long n, i;
if (RedisModule_StringToLongLong(argv[2], &n) == REDISMODULE_ERR) {
RedisModule_ReplyWithError(ctx, "N must be a number");
return REDISMODULE_OK;
}
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_WRITE);
for (i = 0; i < n; i++) {
if (RedisModule_StreamAdd(key, REDISMODULE_STREAM_ADD_AUTOID, NULL,
&argv[3], (argc-3)/2) == REDISMODULE_ERR)
break;
}
RedisModule_ReplyWithLongLong(ctx, i);
RedisModule_CloseKey(key);
return REDISMODULE_OK;
}
/* STREAM.DELETE key stream-id */
int stream_delete(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 3) return RedisModule_WrongArity(ctx);
RedisModuleStreamID id;
if (RedisModule_StringToStreamID(argv[2], &id) != REDISMODULE_OK) {
return RedisModule_ReplyWithError(ctx, "Invalid stream ID");
}
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_WRITE);
if (RedisModule_StreamDelete(key, &id) == REDISMODULE_OK) {
RedisModule_ReplyWithSimpleString(ctx, "OK");
} else {
RedisModule_ReplyWithError(ctx, "ERR StreamDelete failed");
}
RedisModule_CloseKey(key);
return REDISMODULE_OK;
}
/* STREAM.RANGE key start-id end-id
*
* Returns an array of stream items. Each item is an array on the form
* [stream-id, [field1, value1, field2, value2, ...]].
*
* A funny side-effect used for testing RM_StreamIteratorDelete() is that if any
* entry has a field named "selfdestruct", the stream entry is deleted. It is
* however included in the results of this command.
*/
int stream_range(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 4) {
RedisModule_WrongArity(ctx);
return REDISMODULE_OK;
}
RedisModuleStreamID startid, endid;
if (RedisModule_StringToStreamID(argv[2], &startid) != REDISMODULE_OK ||
RedisModule_StringToStreamID(argv[3], &endid) != REDISMODULE_OK) {
RedisModule_ReplyWithError(ctx, "Invalid stream ID");
return REDISMODULE_OK;
}
/* If startid > endid, we swap and set the reverse flag. */
int flags = 0;
if (startid.ms > endid.ms ||
(startid.ms == endid.ms && startid.seq > endid.seq)) {
RedisModuleStreamID tmp = startid;
startid = endid;
endid = tmp;
flags |= REDISMODULE_STREAM_ITERATOR_REVERSE;
}
/* Open key and start iterator. */
int openflags = REDISMODULE_READ | REDISMODULE_WRITE;
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], openflags);
if (RedisModule_StreamIteratorStart(key, flags,
&startid, &endid) != REDISMODULE_OK) {
/* Key is not a stream, etc. */
RedisModule_ReplyWithError(ctx, "ERR StreamIteratorStart failed");
RedisModule_CloseKey(key);
return REDISMODULE_OK;
}
/* Check error handling: Delete current entry when no current entry. */
assert(RedisModule_StreamIteratorDelete(key) ==
REDISMODULE_ERR);
assert(errno == ENOENT);
/* Check error handling: Fetch fields when no current entry. */
assert(RedisModule_StreamIteratorNextField(key, NULL, NULL) ==
REDISMODULE_ERR);
assert(errno == ENOENT);
/* Return array. */
RedisModule_ReplyWithArray(ctx, REDISMODULE_POSTPONED_ARRAY_LEN);
RedisModule_AutoMemory(ctx);
RedisModuleStreamID id;
long numfields;
long len = 0;
while (RedisModule_StreamIteratorNextID(key, &id,
&numfields) == REDISMODULE_OK) {
RedisModule_ReplyWithArray(ctx, 2);
RedisModuleString *id_str = RedisModule_CreateStringFromStreamID(ctx, &id);
RedisModule_ReplyWithString(ctx, id_str);
RedisModule_ReplyWithArray(ctx, numfields * 2);
int delete = 0;
RedisModuleString *field, *value;
for (long i = 0; i < numfields; i++) {
assert(RedisModule_StreamIteratorNextField(key, &field, &value) ==
REDISMODULE_OK);
RedisModule_ReplyWithString(ctx, field);
RedisModule_ReplyWithString(ctx, value);
/* check if this is a "selfdestruct" field */
size_t field_len;
const char *field_str = RedisModule_StringPtrLen(field, &field_len);
if (!strncmp(field_str, "selfdestruct", field_len)) delete = 1;
}
if (delete) {
assert(RedisModule_StreamIteratorDelete(key) == REDISMODULE_OK);
}
/* check error handling: no more fields to fetch */
assert(RedisModule_StreamIteratorNextField(key, &field, &value) ==
REDISMODULE_ERR);
assert(errno == ENOENT);
len++;
}
RedisModule_ReplySetArrayLength(ctx, len);
RedisModule_StreamIteratorStop(key);
RedisModule_CloseKey(key);
return REDISMODULE_OK;
}
/*
* STREAM.TRIM key (MAXLEN (=|~) length | MINID (=|~) id)
*/
int stream_trim(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 5) {
RedisModule_WrongArity(ctx);
return REDISMODULE_OK;
}
/* Parse args */
int trim_by_id = 0; /* 0 = maxlen, 1 = minid */
long long maxlen;
RedisModuleStreamID minid;
size_t arg_len;
const char *arg = RedisModule_StringPtrLen(argv[2], &arg_len);
if (!strcasecmp(arg, "minid")) {
trim_by_id = 1;
if (RedisModule_StringToStreamID(argv[4], &minid) != REDISMODULE_OK) {
RedisModule_ReplyWithError(ctx, "ERR Invalid stream ID");
return REDISMODULE_OK;
}
} else if (!strcasecmp(arg, "maxlen")) {
if (RedisModule_StringToLongLong(argv[4], &maxlen) == REDISMODULE_ERR) {
RedisModule_ReplyWithError(ctx, "ERR Maxlen must be a number");
return REDISMODULE_OK;
}
} else {
RedisModule_ReplyWithError(ctx, "ERR Invalid arguments");
return REDISMODULE_OK;
}
/* Approx or exact */
int flags;
arg = RedisModule_StringPtrLen(argv[3], &arg_len);
if (arg_len == 1 && arg[0] == '~') {
flags = REDISMODULE_STREAM_TRIM_APPROX;
} else if (arg_len == 1 && arg[0] == '=') {
flags = 0;
} else {
RedisModule_ReplyWithError(ctx, "ERR Invalid approx-or-exact mark");
return REDISMODULE_OK;
}
/* Trim */
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_WRITE);
long long trimmed;
if (trim_by_id) {
trimmed = RedisModule_StreamTrimByID(key, flags, &minid);
} else {
trimmed = RedisModule_StreamTrimByLength(key, flags, maxlen);
}
/* Return result */
if (trimmed < 0) {
RedisModule_ReplyWithError(ctx, "ERR Trimming failed");
} else {
RedisModule_ReplyWithLongLong(ctx, trimmed);
}
RedisModule_CloseKey(key);
return REDISMODULE_OK;
}
int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
REDISMODULE_NOT_USED(argv);
REDISMODULE_NOT_USED(argc);
if (RedisModule_Init(ctx, "stream", 1, REDISMODULE_APIVER_1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx, "stream.add", stream_add, "",
1, 1, 1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx, "stream.addn", stream_addn, "",
1, 1, 1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx, "stream.delete", stream_delete, "",
1, 1, 1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx, "stream.range", stream_range, "",
1, 1, 1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx, "stream.trim", stream_trim, "",
1, 1, 1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
return REDISMODULE_OK;
}
+196
View File
@@ -0,0 +1,196 @@
/* This module emulates a linked list for lazyfree testing of modules, which
is a simplified version of 'hellotype.c'
*/
#include "redismodule.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdint.h>
static RedisModuleType *LazyFreeLinkType;
struct LazyFreeLinkNode {
int64_t value;
struct LazyFreeLinkNode *next;
};
struct LazyFreeLinkObject {
struct LazyFreeLinkNode *head;
size_t len; /* Number of elements added. */
};
struct LazyFreeLinkObject *createLazyFreeLinkObject(void) {
struct LazyFreeLinkObject *o;
o = RedisModule_Alloc(sizeof(*o));
o->head = NULL;
o->len = 0;
return o;
}
void LazyFreeLinkInsert(struct LazyFreeLinkObject *o, int64_t ele) {
struct LazyFreeLinkNode *next = o->head, *newnode, *prev = NULL;
while(next && next->value < ele) {
prev = next;
next = next->next;
}
newnode = RedisModule_Alloc(sizeof(*newnode));
newnode->value = ele;
newnode->next = next;
if (prev) {
prev->next = newnode;
} else {
o->head = newnode;
}
o->len++;
}
void LazyFreeLinkReleaseObject(struct LazyFreeLinkObject *o) {
struct LazyFreeLinkNode *cur, *next;
cur = o->head;
while(cur) {
next = cur->next;
RedisModule_Free(cur);
cur = next;
}
RedisModule_Free(o);
}
/* LAZYFREELINK.INSERT key value */
int LazyFreeLinkInsert_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
RedisModule_AutoMemory(ctx); /* Use automatic memory management. */
if (argc != 3) return RedisModule_WrongArity(ctx);
RedisModuleKey *key = RedisModule_OpenKey(ctx,argv[1],
REDISMODULE_READ|REDISMODULE_WRITE);
int type = RedisModule_KeyType(key);
if (type != REDISMODULE_KEYTYPE_EMPTY &&
RedisModule_ModuleTypeGetType(key) != LazyFreeLinkType)
{
return RedisModule_ReplyWithError(ctx,REDISMODULE_ERRORMSG_WRONGTYPE);
}
long long value;
if ((RedisModule_StringToLongLong(argv[2],&value) != REDISMODULE_OK)) {
return RedisModule_ReplyWithError(ctx,"ERR invalid value: must be a signed 64 bit integer");
}
struct LazyFreeLinkObject *hto;
if (type == REDISMODULE_KEYTYPE_EMPTY) {
hto = createLazyFreeLinkObject();
RedisModule_ModuleTypeSetValue(key,LazyFreeLinkType,hto);
} else {
hto = RedisModule_ModuleTypeGetValue(key);
}
LazyFreeLinkInsert(hto,value);
RedisModule_SignalKeyAsReady(ctx,argv[1]);
RedisModule_ReplyWithLongLong(ctx,hto->len);
RedisModule_ReplicateVerbatim(ctx);
return REDISMODULE_OK;
}
/* LAZYFREELINK.LEN key */
int LazyFreeLinkLen_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
RedisModule_AutoMemory(ctx); /* Use automatic memory management. */
if (argc != 2) return RedisModule_WrongArity(ctx);
RedisModuleKey *key = RedisModule_OpenKey(ctx,argv[1],
REDISMODULE_READ|REDISMODULE_WRITE);
int type = RedisModule_KeyType(key);
if (type != REDISMODULE_KEYTYPE_EMPTY &&
RedisModule_ModuleTypeGetType(key) != LazyFreeLinkType)
{
return RedisModule_ReplyWithError(ctx,REDISMODULE_ERRORMSG_WRONGTYPE);
}
struct LazyFreeLinkObject *hto = RedisModule_ModuleTypeGetValue(key);
RedisModule_ReplyWithLongLong(ctx,hto ? hto->len : 0);
return REDISMODULE_OK;
}
void *LazyFreeLinkRdbLoad(RedisModuleIO *rdb, int encver) {
if (encver != 0) {
return NULL;
}
uint64_t elements = RedisModule_LoadUnsigned(rdb);
struct LazyFreeLinkObject *hto = createLazyFreeLinkObject();
while(elements--) {
int64_t ele = RedisModule_LoadSigned(rdb);
LazyFreeLinkInsert(hto,ele);
}
return hto;
}
void LazyFreeLinkRdbSave(RedisModuleIO *rdb, void *value) {
struct LazyFreeLinkObject *hto = value;
struct LazyFreeLinkNode *node = hto->head;
RedisModule_SaveUnsigned(rdb,hto->len);
while(node) {
RedisModule_SaveSigned(rdb,node->value);
node = node->next;
}
}
void LazyFreeLinkAofRewrite(RedisModuleIO *aof, RedisModuleString *key, void *value) {
struct LazyFreeLinkObject *hto = value;
struct LazyFreeLinkNode *node = hto->head;
while(node) {
RedisModule_EmitAOF(aof,"LAZYFREELINK.INSERT","sl",key,node->value);
node = node->next;
}
}
void LazyFreeLinkFree(void *value) {
LazyFreeLinkReleaseObject(value);
}
size_t LazyFreeLinkFreeEffort(RedisModuleString *key, const void *value) {
REDISMODULE_NOT_USED(key);
const struct LazyFreeLinkObject *hto = value;
return hto->len;
}
void LazyFreeLinkUnlink(RedisModuleString *key, const void *value) {
REDISMODULE_NOT_USED(key);
REDISMODULE_NOT_USED(value);
/* Here you can know which key and value is about to be freed. */
}
int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
REDISMODULE_NOT_USED(argv);
REDISMODULE_NOT_USED(argc);
if (RedisModule_Init(ctx,"lazyfreetest",1,REDISMODULE_APIVER_1)
== REDISMODULE_ERR) return REDISMODULE_ERR;
/* We only allow our module to be loaded when the redis core version is greater than the version of my module */
if (RedisModule_GetTypeMethodVersion() < REDISMODULE_TYPE_METHOD_VERSION) {
return REDISMODULE_ERR;
}
RedisModuleTypeMethods tm = {
.version = REDISMODULE_TYPE_METHOD_VERSION,
.rdb_load = LazyFreeLinkRdbLoad,
.rdb_save = LazyFreeLinkRdbSave,
.aof_rewrite = LazyFreeLinkAofRewrite,
.free = LazyFreeLinkFree,
.free_effort = LazyFreeLinkFreeEffort,
.unlink = LazyFreeLinkUnlink,
};
LazyFreeLinkType = RedisModule_CreateDataType(ctx,"test_lazy",0,&tm);
if (LazyFreeLinkType == NULL) return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"lazyfreelink.insert",
LazyFreeLinkInsert_RedisCommand,"write deny-oom",1,1,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"lazyfreelink.len",
LazyFreeLinkLen_RedisCommand,"readonly",1,1,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
return REDISMODULE_OK;
}
+42
View File
@@ -13,6 +13,45 @@ RedisModuleType *testrdb_type = NULL;
RedisModuleString *before_str = NULL;
RedisModuleString *after_str = NULL;
void replBackupCallback(RedisModuleCtx *ctx, RedisModuleEvent e, uint64_t sub, void *data)
{
REDISMODULE_NOT_USED(e);
REDISMODULE_NOT_USED(data);
static RedisModuleString *before_str_backup = NULL;
static RedisModuleString *after_str_backup = NULL;
switch (sub) {
case REDISMODULE_SUBEVENT_REPL_BACKUP_CREATE:
assert(before_str_backup == NULL);
assert(after_str_backup == NULL);
before_str_backup = before_str;
after_str_backup = after_str;
before_str = NULL;
after_str = NULL;
break;
case REDISMODULE_SUBEVENT_REPL_BACKUP_RESTORE:
if (before_str)
RedisModule_FreeString(ctx, before_str);
if (after_str)
RedisModule_FreeString(ctx, after_str);
before_str = before_str_backup;
after_str = after_str_backup;
before_str_backup = NULL;
after_str_backup = NULL;
break;
case REDISMODULE_SUBEVENT_REPL_BACKUP_DISCARD:
if (before_str_backup)
RedisModule_FreeString(ctx, before_str_backup);
if (after_str_backup)
RedisModule_FreeString(ctx, after_str_backup);
before_str_backup = NULL;
after_str_backup = NULL;
break;
default:
assert(0);
}
}
void *testrdb_type_load(RedisModuleIO *rdb, int encver) {
int count = RedisModule_LoadSigned(rdb);
RedisModuleString *str = RedisModule_LoadString(rdb);
@@ -247,6 +286,9 @@ int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
if (RedisModule_CreateCommand(ctx,"testrdb.get.key", testrdb_get_key,"",1,1,1) == REDISMODULE_ERR)
return REDISMODULE_ERR;
RedisModule_SubscribeToServerEvent(ctx,
RedisModuleEvent_ReplBackup, replBackupCallback);
return REDISMODULE_OK;
}
+103
View File
@@ -0,0 +1,103 @@
#define REDISMODULE_EXPERIMENTAL_API
#include "redismodule.h"
static void timer_callback(RedisModuleCtx *ctx, void *data)
{
RedisModuleString *keyname = data;
RedisModuleCallReply *reply;
reply = RedisModule_Call(ctx, "INCR", "s", keyname);
if (reply != NULL)
RedisModule_FreeCallReply(reply);
RedisModule_FreeString(ctx, keyname);
}
int test_createtimer(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
{
if (argc != 3) {
RedisModule_WrongArity(ctx);
return REDISMODULE_OK;
}
long long period;
if (RedisModule_StringToLongLong(argv[1], &period) == REDISMODULE_ERR) {
RedisModule_ReplyWithError(ctx, "Invalid time specified.");
return REDISMODULE_OK;
}
RedisModuleString *keyname = argv[2];
RedisModule_RetainString(ctx, keyname);
RedisModuleTimerID id = RedisModule_CreateTimer(ctx, period, timer_callback, keyname);
RedisModule_ReplyWithLongLong(ctx, id);
return REDISMODULE_OK;
}
int test_gettimer(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
{
if (argc != 2) {
RedisModule_WrongArity(ctx);
return REDISMODULE_OK;
}
long long id;
if (RedisModule_StringToLongLong(argv[1], &id) == REDISMODULE_ERR) {
RedisModule_ReplyWithError(ctx, "Invalid id specified.");
return REDISMODULE_OK;
}
uint64_t remaining;
RedisModuleString *keyname;
if (RedisModule_GetTimerInfo(ctx, id, &remaining, (void **)&keyname) == REDISMODULE_ERR) {
RedisModule_ReplyWithNull(ctx);
} else {
RedisModule_ReplyWithArray(ctx, 2);
RedisModule_ReplyWithString(ctx, keyname);
RedisModule_ReplyWithLongLong(ctx, remaining);
}
return REDISMODULE_OK;
}
int test_stoptimer(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
{
if (argc != 2) {
RedisModule_WrongArity(ctx);
return REDISMODULE_OK;
}
long long id;
if (RedisModule_StringToLongLong(argv[1], &id) == REDISMODULE_ERR) {
RedisModule_ReplyWithError(ctx, "Invalid id specified.");
return REDISMODULE_OK;
}
int ret = 0;
RedisModuleString *keyname;
if (RedisModule_StopTimer(ctx, id, (void **) &keyname) == REDISMODULE_OK) {
RedisModule_FreeString(ctx, keyname);
ret = 1;
}
RedisModule_ReplyWithLongLong(ctx, ret);
return REDISMODULE_OK;
}
int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
REDISMODULE_NOT_USED(argv);
REDISMODULE_NOT_USED(argc);
if (RedisModule_Init(ctx,"timer",1,REDISMODULE_APIVER_1)== REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"test.createtimer", test_createtimer,"",0,0,0) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"test.gettimer", test_gettimer,"",0,0,0) == REDISMODULE_ERR)
return REDISMODULE_ERR;
if (RedisModule_CreateCommand(ctx,"test.stoptimer", test_stoptimer,"",0,0,0) == REDISMODULE_ERR)
return REDISMODULE_ERR;
return REDISMODULE_OK;
}
+30
View File
@@ -0,0 +1,30 @@
#include "redismodule.h"
/* ZSET.REM key element
*
* Removes an occurrence of an element from a sorted set. Replies with the
* number of removed elements (0 or 1).
*/
int zset_rem(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc != 3) return RedisModule_WrongArity(ctx);
RedisModule_AutoMemory(ctx);
int keymode = REDISMODULE_READ | REDISMODULE_WRITE;
RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], keymode);
int deleted;
if (RedisModule_ZsetRem(key, argv[2], &deleted) == REDISMODULE_OK)
return RedisModule_ReplyWithLongLong(ctx, deleted);
else
return RedisModule_ReplyWithError(ctx, "ERR ZsetRem failed");
}
int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
REDISMODULE_NOT_USED(argv);
REDISMODULE_NOT_USED(argc);
if (RedisModule_Init(ctx, "zset", 1, REDISMODULE_APIVER_1) ==
REDISMODULE_OK &&
RedisModule_CreateCommand(ctx, "zset.rem", zset_rem, "",
1, 1, 1) == REDISMODULE_OK)
return REDISMODULE_OK;
else
return REDISMODULE_ERR;
}
+4 -1
View File
@@ -10,7 +10,10 @@ set ::tlsdir "../../tls"
proc main {} {
parse_options
spawn_instance sentinel $::sentinel_base_port $::instances_count
if {$::leaked_fds_file != ""} {
set ::env(LEAKED_FDS_FILE) $::leaked_fds_file
}
spawn_instance sentinel $::sentinel_base_port $::instances_count [list "sentinel deny-scripts-reconfig no"] "../tests/includes/sentinel.conf"
spawn_instance redis $::redis_base_port $::instances_count
run_tests
cleanup
+1 -1
View File
@@ -1,5 +1,5 @@
# Check the basic monitoring and failover capabilities.
source "../tests/includes/start-init-tests.tcl"
source "../tests/includes/init-tests.tcl"
if {$::simulate_error} {
+67
View File
@@ -0,0 +1,67 @@
proc set_redis_announce_ip {addr} {
foreach_redis_id id {
R $id config set replica-announce-ip $addr
}
}
proc set_sentinel_config {keyword value} {
foreach_sentinel_id id {
S $id sentinel config set $keyword $value
}
}
proc set_all_instances_hostname {hostname} {
foreach_sentinel_id id {
set_instance_attrib sentinel $id host $hostname
}
foreach_redis_id id {
set_instance_attrib redis $id host $hostname
}
}
test "(pre-init) Configure instances and sentinel for hostname use" {
set ::host "localhost"
restart_killed_instances
set_all_instances_hostname $::host
set_redis_announce_ip $::host
set_sentinel_config resolve-hostnames yes
set_sentinel_config announce-hostnames yes
}
source "../tests/includes/init-tests.tcl"
proc verify_hostname_announced {hostname} {
foreach_sentinel_id id {
# Master is reported with its hostname
if {![string equal [lindex [S $id SENTINEL GET-MASTER-ADDR-BY-NAME mymaster] 0] $hostname]} {
return 0
}
# Replicas are reported with their hostnames
foreach replica [S $id SENTINEL REPLICAS mymaster] {
if {![string equal [dict get $replica ip] $hostname]} {
return 0
}
}
}
return 1
}
test "Sentinel announces hostnames" {
# Check initial state
verify_hostname_announced $::host
# Disable announce-hostnames and confirm IPs are used
set_sentinel_config announce-hostnames no
assert {[verify_hostname_announced "127.0.0.1"] || [verify_hostname_announced "::1"]}
}
# We need to revert any special configuration because all tests currently
# share the same instances.
test "(post-cleanup) Configure instances and sentinel for IPs" {
set ::host "127.0.0.1"
set_all_instances_hostname $::host
set_redis_announce_ip $::host
set_sentinel_config resolve-hostnames no
set_sentinel_config announce-hostnames no
}
+50
View File
@@ -0,0 +1,50 @@
source "../tests/includes/init-tests.tcl"
set ::user "testuser"
set ::password "secret"
proc setup_acl {} {
foreach_sentinel_id id {
assert_equal {OK} [S $id ACL SETUSER $::user >$::password +@all on]
assert_equal {OK} [S $id ACL SETUSER default off]
S $id CLIENT KILL USER default SKIPME no
assert_equal {OK} [S $id AUTH $::user $::password]
}
}
proc teardown_acl {} {
foreach_sentinel_id id {
assert_equal {OK} [S $id ACL SETUSER default on]
assert_equal {1} [S $id ACL DELUSER $::user]
S $id SENTINEL CONFIG SET sentinel-user ""
S $id SENTINEL CONFIG SET sentinel-pass ""
}
}
test "(post-init) Set up ACL configuration" {
setup_acl
assert_equal $::user [S 1 ACL WHOAMI]
}
test "SENTINEL CONFIG SET handles on-the-fly credentials reconfiguration" {
# Make sure we're starting with a broken state...
after 5000
catch {S 1 SENTINEL CKQUORUM mymaster} err
assert_match {*NOQUORUM*} $err
foreach_sentinel_id id {
assert_equal {OK} [S $id SENTINEL CONFIG SET sentinel-user $::user]
assert_equal {OK} [S $id SENTINEL CONFIG SET sentinel-pass $::password]
}
after 5000
assert_match {*OK*} [S 1 SENTINEL CKQUORUM mymaster]
}
test "(post-cleanup) Tear down ACL configuration" {
teardown_acl
}
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env tclsh
#
# This script detects file descriptors that have leaked from a parent process.
#
# Our goal is to detect file descriptors that were opened by the parent and
# not cleaned up prior to exec(), but not file descriptors that were inherited
# from the grandparent which the parent knows nothing about. To do that, we
# look up every potential leak and try to match it against open files by the
# grandparent process.
# Get PID of parent process
proc get_parent_pid {_pid} {
set fd [open "/proc/$_pid/status" "r"]
set content [read $fd]
close $fd
if {[regexp {\nPPid:\s+(\d+)} $content _ ppid]} {
return $ppid
}
error "failed to get parent pid"
}
# Read symlink to get info about the specified fd of the specified process.
# The result can be the file name or an arbitrary string that identifies it.
# When not able to read, an empty string is returned.
proc get_fdlink {_pid fd} {
if { [catch {set fdlink [file readlink "/proc/$_pid/fd/$fd"]} err] } {
return ""
}
return $fdlink
}
# Linux only
set os [exec uname]
if {$os != "Linux"} {
puts "Only Linux is supported."
exit 0
}
if {![info exists env(LEAKED_FDS_FILE)]} {
puts "Missing LEAKED_FDS_FILE environment variable."
exit 0
}
set outfile $::env(LEAKED_FDS_FILE)
set parent_pid [get_parent_pid [pid]]
set grandparent_pid [get_parent_pid $parent_pid]
set leaked_fds {}
# Look for fds that were directly inherited from our parent but not from
# our grandparent (tcl)
foreach fd [glob -tails -directory "/proc/self/fd" *] {
# Ignore stdin/stdout/stderr
if {$fd == 0 || $fd == 1 || $fd == 2} {
continue
}
set fdlink [get_fdlink "self" $fd]
if {$fdlink == ""} {
continue
}
# We ignore fds that existed in the grandparent, or fds that don't exist
# in our parent (Sentinel process).
if {[get_fdlink $grandparent_pid $fd] == $fdlink ||
[get_fdlink $parent_pid $fd] != $fdlink} {
continue
}
lappend leaked_fds [list $fd $fdlink]
}
# Produce report only if we found leaks
if {[llength $leaked_fds] > 0} {
set fd [open $outfile "w"]
puts $fd [join $leaked_fds "\n"]
close $fd
}
+9 -1
View File
@@ -1,6 +1,6 @@
# Initialization tests -- most units will start including this.
test "(init) Restart killed instances" {
proc restart_killed_instances {} {
foreach type {redis sentinel} {
foreach_${type}_id id {
if {[get_instance_attrib $type $id pid] == -1} {
@@ -12,6 +12,10 @@ test "(init) Restart killed instances" {
}
}
test "(init) Restart killed instances" {
restart_killed_instances
}
test "(init) Remove old master entry from sentinels" {
foreach_sentinel_id id {
catch {S $id SENTINEL REMOVE mymaster}
@@ -37,6 +41,10 @@ test "(init) Sentinels can start monitoring a master" {
S $id SENTINEL SET mymaster down-after-milliseconds 2000
S $id SENTINEL SET mymaster failover-timeout 20000
S $id SENTINEL SET mymaster parallel-syncs 10
if {$::leaked_fds_file != "" && [exec uname] == "Linux"} {
S $id SENTINEL SET mymaster notification-script ../../tests/helpers/check_leaked_fds.tcl
S $id SENTINEL SET mymaster client-reconfig-script ../../tests/helpers/check_leaked_fds.tcl
}
}
}
@@ -0,0 +1,11 @@
# assume master is down after being unresponsive for 20s
sentinel down-after-milliseconds setmaster 20000
# reconfigure one slave at a time
sentinel parallel-syncs setmaster 2
# wait for 4m before assuming failover went wrong
sentinel failover-timeout setmaster 240000
# monitoring set
sentinel monitor setmaster 10.0.0.1 30000 2
@@ -0,0 +1,18 @@
test "(start-init) Flush config and compare rewrite config file lines" {
foreach_sentinel_id id {
assert_match "OK" [S $id SENTINEL FLUSHCONFIG]
set file1 ../tests/includes/sentinel.conf
set file2 [file join "sentinel_${id}" "sentinel.conf"]
set fh1 [open $file1 r]
set fh2 [open $file2 r]
while {[gets $fh1 line1]} {
if {[gets $fh2 line2]} {
assert [string equal $line1 $line2]
} else {
fail "sentinel config file rewrite sequence changed"
}
}
close $fh1
close $fh2
}
}
+19
View File
@@ -0,0 +1,19 @@
proc redisbenchmark_tls_config {testsdir} {
set tlsdir [file join $testsdir tls]
set cert [file join $tlsdir client.crt]
set key [file join $tlsdir client.key]
set cacert [file join $tlsdir ca.crt]
if {$::tls} {
return [list --tls --cert $cert --key $key --cacert $cacert]
} else {
return {}
}
}
proc redisbenchmark {host port {opts {}}} {
set cmd [list src/keydb-benchmark -h $host -p $port]
lappend cmd {*}[redisbenchmark_tls_config "tests"]
lappend cmd {*}$opts
return $cmd
}
+2 -2
View File
@@ -1,7 +1,7 @@
proc rediscli_tls_config {testsdir} {
set tlsdir [file join $testsdir tls]
set cert [file join $tlsdir redis.crt]
set key [file join $tlsdir redis.key]
set cert [file join $tlsdir client.crt]
set key [file join $tlsdir client.key]
set cacert [file join $tlsdir ca.crt]
if {$::tls} {
+2 -2
View File
@@ -24,10 +24,10 @@ set ::redis_cluster::plain_commands {
get set setnx setex psetex append strlen exists setbit getbit
setrange getrange substr incr decr rpush lpush rpushx lpushx
linsert rpop lpop brpop llen lindex lset lrange ltrim lrem
sadd srem sismember scard spop srandmember smembers sscan zadd
sadd srem sismember smismember scard spop srandmember smembers sscan zadd
zincrby zrem zremrangebyscore zremrangebyrank zremrangebylex zrange
zrangebyscore zrevrangebyscore zrangebylex zrevrangebylex zcount
zlexcount zrevrange zcard zscore zrank zrevrank zscan hset hsetnx
zlexcount zrevrange zcard zscore zmscore zrank zrevrank zscan hset hsetnx
hget hmset hmget hincrby hincrbyfloat hdel hlen hkeys hvals
hgetall hexists hscan incrby decrby incrbyfloat getset move
expire expireat pexpire pexpireat type ttl pttl persist restore
+6 -2
View File
@@ -44,8 +44,8 @@ proc redis {{server 127.0.0.1} {port 6379} {defer 0} {tls 0} {tlsoptions {}}} {
package require tls
::tls::init \
-cafile "$::tlsdir/ca.crt" \
-certfile "$::tlsdir/redis.crt" \
-keyfile "$::tlsdir/redis.key" \
-certfile "$::tlsdir/client.crt" \
-keyfile "$::tlsdir/client.key" \
{*}$tlsoptions
set fd [::tls::socket $server $port]
} else {
@@ -109,6 +109,7 @@ proc ::redis::__dispatch__raw__ {id method argv} {
}
::redis::redis_write $fd $cmd
if {[catch {flush $fd}]} {
catch {close $fd}
set ::redis::fd($id) {}
return -code error "I/O error reading reply"
}
@@ -243,13 +244,16 @@ proc ::redis::redis_read_reply {id fd} {
_ {redis_read_null $fd}
: -
+ {redis_read_line $fd}
, {expr {double([redis_read_line $fd])}}
- {return -code error [redis_read_line $fd]}
$ {redis_bulk_read $fd}
> -
~ -
* {redis_multi_bulk_read $id $fd}
% {redis_read_map $id $fd}
default {
if {$type eq {}} {
catch {close $fd}
set ::redis::fd($id) {}
return -code error "I/O error reading reply"
}
+93 -28
View File
@@ -13,7 +13,7 @@ proc start_server_error {config_file error} {
}
proc check_valgrind_errors stderr {
set res [find_valgrind_errors $stderr]
set res [find_valgrind_errors $stderr true]
if {$res != ""} {
send_data_packet $::test_server_fd err "Valgrind error: $res\n"
}
@@ -50,11 +50,17 @@ proc kill_server config {
tags {"leaks"} {
test "Check for memory leaks (pid $pid)" {
set output {0 leaks}
catch {exec leaks $pid} output
if {[string match {*process does not exist*} $output] ||
[string match {*cannot examine*} $output]} {
# In a few tests we kill the server process.
set output "0 leaks"
catch {exec leaks $pid} output option
# In a few tests we kill the server process, so leaks will not find it.
# It'll exits with exit code >1 on error, so we ignore these.
if {[dict exists $option -errorcode]} {
set details [dict get $option -errorcode]
if {[lindex $details 0] eq "CHILDSTATUS"} {
set status [lindex $details 2]
if {$status > 1} {
set output "0 leaks"
}
}
}
set output
} {*0 leaks*}
@@ -66,6 +72,8 @@ proc kill_server config {
# kill server and wait for the process to be totally exited
send_data_packet $::test_server_fd server-killing $pid
catch {exec kill $pid}
# Node might have been stopped in the test
catch {exec kill -SIGCONT $pid}
if {$::valgrind} {
set max_wait 60000
} else {
@@ -146,20 +154,48 @@ proc server_is_up {host port retrynum} {
return 0
}
# Check if current ::tags match requested tags. If ::allowtags are used,
# there must be some intersection. If ::denytags are used, no intersection
# is allowed. Returns 1 if tags are acceptable or 0 otherwise, in which
# case err_return names a return variable for the message to be logged.
proc tags_acceptable {err_return} {
upvar $err_return err
# If tags are whitelisted, make sure there's match
if {[llength $::allowtags] > 0} {
set matched 0
foreach tag $::allowtags {
if {[lsearch $::tags $tag] >= 0} {
incr matched
}
}
if {$matched < 1} {
set err "Tag: none of the tags allowed"
return 0
}
}
foreach tag $::denytags {
if {[lsearch $::tags $tag] >= 0} {
set err "Tag: $tag denied"
return 0
}
}
return 1
}
# doesn't really belong here, but highly coupled to code in start_server
proc tags {tags code} {
# If we 'tags' contain multiple tags, quoted and seperated by spaces,
# we want to get rid of the quotes in order to have a proper list
set tags [string map { \" "" } $tags]
set ::tags [concat $::tags $tags]
# We skip unwanted tags
foreach tag $::denytags {
if {[lsearch $::tags $tag] >= 0} {
incr ::num_aborted
send_data_packet $::test_server_fd ignore "Tag: $tag"
set ::tags [lrange $::tags 0 end-[llength $tags]]
return
}
if {![tags_acceptable err]} {
incr ::num_aborted
send_data_packet $::test_server_fd ignore $err
set ::tags [lrange $::tags 0 end-[llength $tags]]
return
}
uplevel 1 $code
set ::tags [lrange $::tags 0 end-[llength $tags]]
@@ -225,10 +261,18 @@ proc wait_server_started {config_file stdout pid} {
return $port_busy
}
proc dump_server_log {srv} {
set pid [dict get $srv "pid"]
puts "\n===== Start of server log (pid $pid) =====\n"
puts [exec cat [dict get $srv "stdout"]]
puts "===== End of server log (pid $pid) =====\n"
}
proc start_server {options {code undefined}} {
# setup defaults
set baseconfig "default.conf"
set overrides {}
set omit {}
set tags {}
set keep_persistence false
@@ -241,6 +285,9 @@ proc start_server {options {code undefined}} {
"overrides" {
set overrides $value
}
"omit" {
set omit $value
}
"tags" {
# If we 'tags' contain multiple tags, quoted and seperated by spaces,
# we want to get rid of the quotes in order to have a proper list
@@ -257,13 +304,11 @@ proc start_server {options {code undefined}} {
}
# We skip unwanted tags
foreach tag $::denytags {
if {[lsearch $::tags $tag] >= 0} {
incr ::num_aborted
send_data_packet $::test_server_fd ignore "Tag: $tag"
set ::tags [lrange $::tags 0 end-[llength $tags]]
return
}
if {![tags_acceptable err]} {
incr ::num_aborted
send_data_packet $::test_server_fd ignore $err
set ::tags [lrange $::tags 0 end-[llength $tags]]
return
}
# If we are running against an external server, we just push the
@@ -306,8 +351,10 @@ proc start_server {options {code undefined}} {
set data [split [exec cat "tests/assets/$baseconfig"] "\n"]
set config {}
if {$::tls} {
dict set config "tls-cert-file" [format "%s/tests/tls/redis.crt" [pwd]]
dict set config "tls-key-file" [format "%s/tests/tls/redis.key" [pwd]]
dict set config "tls-cert-file" [format "%s/tests/tls/server.crt" [pwd]]
dict set config "tls-key-file" [format "%s/tests/tls/server.key" [pwd]]
dict set config "tls-client-cert-file" [format "%s/tests/tls/client.crt" [pwd]]
dict set config "tls-client-key-file" [format "%s/tests/tls/client.key" [pwd]]
dict set config "tls-dh-params-file" [format "%s/tests/tls/redis.dh" [pwd]]
dict set config "tls-ca-cert-file" [format "%s/tests/tls/ca.crt" [pwd]]
dict set config "loglevel" "debug"
@@ -346,6 +393,11 @@ proc start_server {options {code undefined}} {
dict set config $directive $arguments
}
# remove directives that are marked to be omitted
foreach directive $omit {
dict unset config $directive
}
# write new configuration to temporary file
set config_file [tmpfile redis.conf]
create_server_config_file $config_file $config
@@ -440,7 +492,7 @@ proc start_server {options {code undefined}} {
while 1 {
# check that the server actually started and is ready for connections
if {[exec grep -i "Ready to accept" | wc -l < $stdout] > 0} {
if {[count_message_lines $stdout "Thread 0 alive"] > 0} {
break
}
after 10
@@ -452,6 +504,9 @@ proc start_server {options {code undefined}} {
# connect client (after server dict is put on the stack)
reconnect
# remember previous num_failed to catch new errors
set prev_num_failed $::num_failed
# execute provided block
set num_tests $::num_tests
if {[catch { uplevel 1 $code } error]} {
@@ -489,6 +544,10 @@ proc start_server {options {code undefined}} {
# Re-raise, let handler up the stack take care of this.
error $error $backtrace
}
} else {
if {$::dump_logs && $prev_num_failed != $::num_failed} {
dump_server_log $srv
}
}
# fetch srv back from the server list, in case it was restarted by restart_server (new PID)
@@ -514,13 +573,19 @@ proc start_server {options {code undefined}} {
}
}
proc restart_server {level wait_ready} {
proc restart_server {level wait_ready rotate_logs} {
set srv [lindex $::servers end+$level]
kill_server $srv
set pid [dict get $srv "pid"]
set stdout [dict get $srv "stdout"]
set stderr [dict get $srv "stderr"]
set config_file [dict get $srv "config_file"]
if {$rotate_logs} {
set ts [clock format [clock seconds] -format %y%m%d%H%M%S]
file rename $stdout $stdout.$ts.$pid
file rename $stderr $stderr.$ts.$pid
}
set prev_ready_count [count_message_lines $stdout "Ready to accept"]
# if we're inside a test, write the test name to the server log file
if {[info exists ::cur_test]} {
@@ -529,7 +594,7 @@ proc restart_server {level wait_ready} {
close $fd
}
set prev_ready_count [exec grep -i "Ready to accept" | wc -l < $stdout]
set config_file [dict get $srv "config_file"]
set pid [spawn_server $config_file $stdout $stderr]
@@ -544,7 +609,7 @@ proc restart_server {level wait_ready} {
if {$wait_ready} {
while 1 {
# check that the server actually started and is ready for connections
if {[exec grep -i "Ready to accept" | wc -l < $stdout] > $prev_ready_count} {
if {[count_message_lines $stdout "Thread 0 alive"] > $prev_ready_count} {
break
}
after 10
+30 -18
View File
@@ -31,36 +31,48 @@ proc assert_match {pattern value} {
}
}
proc assert_failed {expected_err detail} {
if {$detail ne ""} {
set detail "(detail: $detail)"
} else {
set detail "(context: [info frame -2])"
}
error "assertion:$expected_err $detail"
}
proc assert_equal {value expected {detail ""}} {
if {$expected ne $value} {
if {$detail ne ""} {
set detail "(detail: $detail)"
} else {
set detail "(context: [info frame -1])"
}
error "assertion:Expected '$value' to be equal to '$expected' $detail"
assert_failed "Expected '$value' to be equal to '$expected'" $detail
}
}
proc assert_lessthan {value expected {detail ""}} {
if {!($value < $expected)} {
if {$detail ne ""} {
set detail "(detail: $detail)"
} else {
set detail "(context: [info frame -1])"
}
error "assertion:Expected '$value' to be lessthan to '$expected' $detail"
assert_failed "Expected '$value' to be less than '$expected'" $detail
}
}
proc assert_lessthan_equal {value expected {detail ""}} {
if {!($value <= $expected)} {
assert_failed "Expected '$value' to be less than or equal to '$expected'" $detail
}
}
proc assert_morethan {value expected {detail ""}} {
if {!($value > $expected)} {
assert_failed "Expected '$value' to be more than '$expected'" $detail
}
}
proc assert_morethan_equal {value expected {detail ""}} {
if {!($value >= $expected)} {
assert_failed "Expected '$value' to be more than or equal to '$expected'" $detail
}
}
proc assert_range {value min max {detail ""}} {
if {!($value <= $max && $value >= $min)} {
if {$detail ne ""} {
set detail "(detail: $detail)"
} else {
set detail "(context: [info frame -1])"
}
error "assertion:Expected '$value' to be between to '$min' and '$max' $detail"
assert_failed "Expected '$value' to be between to '$min' and '$max'" $detail
}
}
+189 -15
View File
@@ -19,7 +19,11 @@ proc randstring {min max {type binary}} {
set maxval 52
}
while {$len} {
append output [format "%c" [expr {$minval+int(rand()*($maxval-$minval+1))}]]
set rr [expr {$minval+int(rand()*($maxval-$minval+1))}]
if {$type eq {alpha} && $rr eq 92} {
set rr 90; # avoid putting '\' char in the string, it can mess up TCL processing
}
append output [format "%c" $rr]
incr len -1
}
return $output
@@ -53,13 +57,17 @@ proc warnings_from_file {filename} {
join $result "\n"
}
# Return value for INFO property
proc status {r property} {
if {[regexp "\r\n(\t*?)$property:(.*?)\r\n" [{*}$r info] _ __ value]} {
proc getInfoProperty {infostr property} {
if {[regexp "\r\n$property:(.*?)\r\n" $infostr _ value]} {
set _ $value
}
}
# Return value for INFO property
proc status {r property} {
set _ [getInfoProperty [{*}$r info] $property]
}
proc waitForBgsave r {
while 1 {
if {[status r rdb_bgsave_in_progress] eq 1} {
@@ -89,12 +97,10 @@ proc waitForBgrewriteaof r {
}
proc wait_for_sync r {
while 1 {
if {[status $r master_link_status] eq "down"} {
after 10
} else {
break
}
wait_for_condition 50 100 {
[status $r master_link_status] eq "up"
} else {
fail "replica didn't sync in time"
}
}
@@ -116,7 +122,23 @@ proc wait_done_loading r {
# count current log lines in server's stdout
proc count_log_lines {srv_idx} {
set _ [exec wc -l < [srv $srv_idx stdout]]
set _ [string trim [exec wc -l < [srv $srv_idx stdout]]]
}
# returns the number of times a line with that pattern appears in a file
proc count_message_lines {file pattern} {
set res 0
# exec fails when grep exists with status other than 0 (when the patter wasn't found)
catch {
set res [string trim [exec grep $pattern $file 2> /dev/null | wc -l]]
}
return $res
}
# returns the number of times a line with that pattern appears in the log
proc count_log_message {srv_idx pattern} {
set stdout [srv $srv_idx stdout]
return [count_message_lines $stdout $pattern]
}
# verify pattern exists in server's sdtout after a certain line number
@@ -445,22 +467,31 @@ proc colorstr {color str} {
}
}
proc find_valgrind_errors {stderr} {
proc find_valgrind_errors {stderr on_termination} {
set fd [open $stderr]
set buf [read $fd]
close $fd
# Look for stack trace (" at 0x") and other errors (Invalid, Mismatched, etc).
# Look for "Warnings", but not the "set address range perms". These don't indicate any real concern.
# Look for the absense of a leak free summary (happens when redis isn't terminated properly).
# corrupt-dump unit, not sure why but it seems they don't indicate any real concern.
if {[regexp -- { at 0x} $buf] ||
[regexp -- {^(?=.*Warning)(?:(?!set address range perms).)*$} $buf] ||
[regexp -- {Invalid} $buf] ||
[regexp -- {Mismatched} $buf] ||
[regexp -- {uninitialized} $buf] ||
[regexp -- {has a fishy} $buf] ||
[regexp -- {overlap} $buf] ||
(![regexp -- {definitely lost: 0 bytes} $buf] &&
[regexp -- {overlap} $buf]} {
return $buf
}
# If the process didn't terminate yet, we can't look for the summary report
if {!$on_termination} {
return ""
}
# Look for the absense of a leak free summary (happens when redis isn't terminated properly).
if {(![regexp -- {definitely lost: 0 bytes} $buf] &&
![regexp -- {no leaks are possible} $buf])} {
return $buf
}
@@ -532,3 +563,146 @@ proc get_child_pid {idx} {
return $child_pid
}
proc cmdrstat {cmd r} {
if {[regexp "\r\ncmdstat_$cmd:(.*?)\r\n" [$r info commandstats] _ value]} {
set _ $value
}
}
proc errorrstat {cmd r} {
if {[regexp "\r\nerrorstat_$cmd:(.*?)\r\n" [$r info errorstats] _ value]} {
set _ $value
}
}
proc generate_fuzzy_traffic_on_key {key duration} {
# Commands per type, blocking commands removed
# TODO: extract these from help.h or elsewhere, and improve to include other types
set string_commands {APPEND BITCOUNT BITFIELD BITOP BITPOS DECR DECRBY GET GETBIT GETRANGE GETSET INCR INCRBY INCRBYFLOAT MGET MSET MSETNX PSETEX SET SETBIT SETEX SETNX SETRANGE STRALGO STRLEN}
set hash_commands {HDEL HEXISTS HGET HGETALL HINCRBY HINCRBYFLOAT HKEYS HLEN HMGET HMSET HSCAN HSET HSETNX HSTRLEN HVALS HRANDFIELD}
set zset_commands {ZADD ZCARD ZCOUNT ZINCRBY ZINTERSTORE ZLEXCOUNT ZPOPMAX ZPOPMIN ZRANGE ZRANGEBYLEX ZRANGEBYSCORE ZRANK ZREM ZREMRANGEBYLEX ZREMRANGEBYRANK ZREMRANGEBYSCORE ZREVRANGE ZREVRANGEBYLEX ZREVRANGEBYSCORE ZREVRANK ZSCAN ZSCORE ZUNIONSTORE ZRANDMEMBER}
set list_commands {LINDEX LINSERT LLEN LPOP LPOS LPUSH LPUSHX LRANGE LREM LSET LTRIM RPOP RPOPLPUSH RPUSH RPUSHX}
set set_commands {SADD SCARD SDIFF SDIFFSTORE SINTER SINTERSTORE SISMEMBER SMEMBERS SMOVE SPOP SRANDMEMBER SREM SSCAN SUNION SUNIONSTORE}
set stream_commands {XACK XADD XCLAIM XDEL XGROUP XINFO XLEN XPENDING XRANGE XREAD XREADGROUP XREVRANGE XTRIM}
set commands [dict create string $string_commands hash $hash_commands zset $zset_commands list $list_commands set $set_commands stream $stream_commands]
set type [r type $key]
set cmds [dict get $commands $type]
set start_time [clock seconds]
set sent {}
set succeeded 0
while {([clock seconds]-$start_time) < $duration} {
# find a random command for our key type
set cmd_idx [expr {int(rand()*[llength $cmds])}]
set cmd [lindex $cmds $cmd_idx]
# get the command details from redis
if { [ catch {
set cmd_info [lindex [r command info $cmd] 0]
} err ] } {
# if we failed, it means redis crashed after the previous command
return $sent
}
# try to build a valid command argument
set arity [lindex $cmd_info 1]
set arity [expr $arity < 0 ? - $arity: $arity]
set firstkey [lindex $cmd_info 3]
set i 1
if {$cmd == "XINFO"} {
lappend cmd "STREAM"
lappend cmd $key
lappend cmd "FULL"
incr i 3
}
if {$cmd == "XREAD"} {
lappend cmd "STREAMS"
lappend cmd $key
randpath {
lappend cmd \$
} {
lappend cmd [randomValue]
}
incr i 3
}
if {$cmd == "XADD"} {
lappend cmd $key
randpath {
lappend cmd "*"
} {
lappend cmd [randomValue]
}
lappend cmd [randomValue]
lappend cmd [randomValue]
incr i 4
}
for {} {$i < $arity} {incr i} {
if {$i == $firstkey} {
lappend cmd $key
} else {
lappend cmd [randomValue]
}
}
# execute the command, we expect commands to fail on syntax errors
lappend sent $cmd
if { ! [ catch {
r {*}$cmd
} err ] } {
incr succeeded
}
}
# print stats so that we know if we managed to generate commands that actually made senes
#if {$::verbose} {
# set count [llength $sent]
# puts "Fuzzy traffic sent: $count, succeeded: $succeeded"
#}
# return the list of commands we sent
return $sent
}
# write line to server log file
proc write_log_line {srv_idx msg} {
set logfile [srv $srv_idx stdout]
set fd [open $logfile "a+"]
puts $fd "### $msg"
close $fd
}
proc string2printable s {
set res {}
set has_special_chars false
foreach i [split $s {}] {
scan $i %c int
# non printable characters, including space and excluding: " \ $ { }
if {$int < 32 || $int > 122 || $int == 34 || $int == 36 || $int == 92} {
set has_special_chars true
}
# TCL8.5 has issues mixing \x notation and normal chars in the same
# source code string, so we'll convert the entire string.
append res \\x[format %02X $int]
}
if {!$has_special_chars} {
return $s
}
set res "\"$res\""
return $res
}
# Check that probability of each element are between {min_prop} and {max_prop}.
proc check_histogram_distribution {res min_prop max_prop} {
unset -nocomplain mydict
foreach key $res {
dict incr mydict $key 1
}
foreach key [dict keys $mydict] {
set value [dict get $mydict $key]
set probability [expr {double($value) / [llength $res]}]
if {$probability < $min_prop || $probability > $max_prop} {
return false
}
}
return true
}
+26 -9
View File
@@ -18,6 +18,7 @@ set ::all_tests {
unit/protocol
unit/keyspace
unit/scan
unit/info
unit/type/string
unit/type/incr
unit/type/list
@@ -51,12 +52,16 @@ set ::all_tests {
integration/replication-multimaster-connect
integration/aof
integration/rdb
integration/corrupt-dump
integration/corrupt-dump-fuzzer
integration/convert-zipmap-hash-on-load
integration/logging
integration/psync2
integration/psync2-reg
integration/psync2-pingoff
integration/failover
integration/redis-cli
integration/redis-benchmark
unit/pubsub
unit/slowlog
unit/scripting
@@ -76,8 +81,9 @@ set ::all_tests {
unit/tls
unit/tracking
unit/oom-score-adj
unit/loadsave
unit/shutdown
unit/networking
unit/loadsave
}
# Index to the next test to run in the ::all_tests list.
set ::next_test 0
@@ -113,6 +119,7 @@ set ::active_servers {} ; # Pids of active Redis instances.
set ::dont_clean 0
set ::wait_server 0
set ::stop_on_failure 0
set ::dump_logs 0
set ::loop 0
set ::endurance 0
set ::tlsdir "tests/tls"
@@ -141,7 +148,8 @@ proc execute_test_file name {
# as argument, and an associated name.
# It will run the specified code and signal it to the test server when
# finished.
proc execute_test_code {name code} {
proc execute_test_code {name filename code} {
set ::curfile $filename
eval $code
send_data_packet $::test_server_fd done "$name"
}
@@ -185,6 +193,10 @@ proc reconnect {args} {
set port [dict get $srv "port"]
set config [dict get $srv "config"]
set client [redis $host $port 0 $::tls]
if {[dict exists $srv "client"]} {
set old [dict get $srv "client"]
$old close
}
dict set srv "client" $client
# select the right db when we don't have to authenticate
@@ -241,7 +253,7 @@ proc s {args} {
# test server, so that the test server will send them again to
# clients once the clients are idle.
proc run_solo {name code} {
if {$::numclients == 1 || $::loop < 0 || $::external || $::endurance} {
if {$::numclients == 1 || $::loop || $::external || $::endurance} {
# run_solo is not supported in these scenarios, just run the code.
if {$::endurance} {
puts "Skipping solo tests because endurance mode is enabled"
@@ -250,7 +262,7 @@ proc run_solo {name code} {
}
return
}
send_data_packet $::test_server_fd run_solo [list $name $code]
send_data_packet $::test_server_fd run_solo [list $name $::curfile $code]
}
proc cleanup {} {
@@ -266,7 +278,7 @@ proc test_server_main {} {
set tclsh [info nameofexecutable]
# Open a listening socket, trying different ports in order to find a
# non busy one.
set clientport [find_available_port 11111 32]
set clientport [find_available_port [expr {$::baseport - 32}] 32]
if {!$::quiet} {
puts "Starting test server at port $clientport"
}
@@ -520,8 +532,8 @@ proc test_client_main server_port {
if {$cmd eq {run}} {
execute_test_file $data
} elseif {$cmd eq {run_code}} {
foreach {name code} $data break
execute_test_code $name $code
foreach {name filename code} $data break
execute_test_code $name $filename $code
} else {
error "Unknown test client command: $cmd"
}
@@ -559,6 +571,7 @@ proc print_help_screen {} {
"--stop Blocks once the first test fails."
"--loop Execute the specified set of tests forever."
"--wait-server Wait after server is started (so that you can attach a debugger)."
"--dump-logs Dump server log on test failure."
"--tls Run tests in TLS mode."
"--host <addr> Run tests against an external host."
"--port <port> TCP port to use against external host."
@@ -608,8 +621,8 @@ for {set j 0} {$j < [llength $argv]} {incr j} {
set ::tls 1
::tls::init \
-cafile "$::tlsdir/ca.crt" \
-certfile "$::tlsdir/redis.crt" \
-keyfile "$::tlsdir/redis.key"
-certfile "$::tlsdir/client.crt" \
-keyfile "$::tlsdir/client.key"
} elseif {$opt eq {--host}} {
set ::external 1
set ::host $arg
@@ -661,6 +674,8 @@ for {set j 0} {$j < [llength $argv]} {incr j} {
set ::no_latency 1
} elseif {$opt eq {--wait-server}} {
set ::wait_server 1
} elseif {$opt eq {--dump-logs}} {
set ::dump_logs 1
} elseif {$opt eq {--stop}} {
set ::stop_on_failure 1
} elseif {$opt eq {--loop}} {
@@ -727,6 +742,7 @@ if {[llength $filtered_tests] < [llength $::all_tests]} {
}
proc attach_to_replication_stream {} {
r config set repl-ping-replica-period 3600
if {$::tls} {
set s [::tls::socket [srv 0 "host"] [srv 0 "port"]]
} else {
@@ -784,6 +800,7 @@ proc assert_replication_stream {s patterns} {
proc close_replication_stream {s} {
close $s
r config set repl-ping-replica-period 10
}
# With the parallel test running multiple Redis instances at the same time
+133
View File
@@ -81,6 +81,110 @@ start_server {tags {"acl"}} {
set e
} {*NOPERM*key*}
test {By default users are able to publish to any channel} {
r ACL setuser psuser on >pspass +acl +client +@pubsub
r AUTH psuser pspass
r PUBLISH foo bar
} {0}
test {By default users are able to subscribe to any channel} {
set rd [redis_deferring_client]
$rd AUTH psuser pspass
$rd read
$rd SUBSCRIBE foo
assert_match {subscribe foo 1} [$rd read]
$rd close
} {0}
test {By default users are able to subscribe to any pattern} {
set rd [redis_deferring_client]
$rd AUTH psuser pspass
$rd read
$rd PSUBSCRIBE bar*
assert_match {psubscribe bar\* 1} [$rd read]
$rd close
} {0}
test {It's possible to allow publishing to a subset of channels} {
r ACL setuser psuser resetchannels &foo:1 &bar:*
assert_equal {0} [r PUBLISH foo:1 somemessage]
assert_equal {0} [r PUBLISH bar:2 anothermessage]
catch {r PUBLISH zap:3 nosuchmessage} e
set e
} {*NOPERM*channel*}
test {It's possible to allow subscribing to a subset of channels} {
set rd [redis_deferring_client]
$rd AUTH psuser pspass
$rd read
$rd SUBSCRIBE foo:1
assert_match {subscribe foo:1 1} [$rd read]
$rd SUBSCRIBE bar:2
assert_match {subscribe bar:2 2} [$rd read]
$rd SUBSCRIBE zap:3
catch {$rd read} e
set e
} {*NOPERM*channel*}
test {It's possible to allow subscribing to a subset of channel patterns} {
set rd [redis_deferring_client]
$rd AUTH psuser pspass
$rd read
$rd PSUBSCRIBE foo:1
assert_match {psubscribe foo:1 1} [$rd read]
$rd PSUBSCRIBE bar:*
assert_match {psubscribe bar:\* 2} [$rd read]
$rd PSUBSCRIBE bar:baz
catch {$rd read} e
set e
} {*NOPERM*channel*}
test {Subscribers are killed when revoked of channel permission} {
set rd [redis_deferring_client]
r ACL setuser psuser resetchannels &foo:1
$rd AUTH psuser pspass
$rd read
$rd CLIENT SETNAME deathrow
$rd read
$rd SUBSCRIBE foo:1
$rd read
r ACL setuser psuser resetchannels
assert_no_match {*deathrow*} [r CLIENT LIST]
$rd close
} {0}
test {Subscribers are killed when revoked of pattern permission} {
set rd [redis_deferring_client]
r ACL setuser psuser resetchannels &bar:*
$rd AUTH psuser pspass
$rd read
$rd CLIENT SETNAME deathrow
$rd read
$rd PSUBSCRIBE bar:*
$rd read
r ACL setuser psuser resetchannels
assert_no_match {*deathrow*} [r CLIENT LIST]
$rd close
} {0}
test {Subscribers are pardoned if literal permissions are retained and/or gaining allchannels} {
set rd [redis_deferring_client]
r ACL setuser psuser resetchannels &foo:1 &bar:*
$rd AUTH psuser pspass
$rd read
$rd CLIENT SETNAME pardoned
$rd read
$rd SUBSCRIBE foo:1
$rd read
$rd PSUBSCRIBE bar:*
$rd read
r ACL setuser psuser resetchannels &foo:1 &bar:* &baz:qaz &zoo:*
assert_match {*pardoned*} [r CLIENT LIST]
r ACL setuser psuser allchannels
assert_match {*pardoned*} [r CLIENT LIST]
$rd close
} {0}
test {Users can be configured to authenticate with any password} {
r ACL setuser newuser nopass
r AUTH newuser zipzapblabla
@@ -113,6 +217,25 @@ start_server {tags {"acl"}} {
set e
} {*NOPERM*}
test {ACLs set can include subcommands, if already full command exists} {
r ACL setuser bob +memory|doctor
set cmdstr [dict get [r ACL getuser bob] commands]
assert_equal {-@all +memory|doctor} $cmdstr
# Validate the commands have got engulfed to +memory.
r ACL setuser bob +memory
set cmdstr [dict get [r ACL getuser bob] commands]
assert_equal {-@all +memory} $cmdstr
# Appending to the existing access string of bob.
r ACL setuser bob +@all +client|id
# Validate the new commands has got engulfed to +@all.
set cmdstr [dict get [r ACL getuser bob] commands]
assert_equal {+@all} $cmdstr
r CLIENT ID; # Should not fail
r MEMORY DOCTOR; # Should not fail
}
# Note that the order of the generated ACL rules is not stable in Redis
# so we need to match the different parts and not as a whole string.
test {ACL GETUSER is able to translate back command permissions} {
@@ -166,6 +289,7 @@ start_server {tags {"acl"}} {
r ACL LOG RESET
r ACL setuser antirez >foo on +set ~object:1234
r ACL setuser antirez +eval +multi +exec
r ACL setuser antirez resetchannels +publish
r AUTH antirez foo
catch {r GET foo}
r AUTH default ""
@@ -195,6 +319,15 @@ start_server {tags {"acl"}} {
assert {[dict get $entry object] eq {somekeynotallowed}}
}
test {ACL LOG is able to log channel access violations and channel name} {
r AUTH antirez foo
catch {r PUBLISH somechannelnotallowed nullmsg}
r AUTH default ""
set entry [lindex [r ACL LOG] 0]
assert {[dict get $entry reason] eq {channel}}
assert {[dict get $entry object] eq {somechannelnotallowed}}
}
test {ACL LOG RESET is able to flush the entries in the log} {
r ACL LOG RESET
assert {[llength [r ACL LOG]] == 0}
+41
View File
@@ -25,3 +25,44 @@ start_server {tags {"auth"} overrides {requirepass foobar}} {
r incr foo
} {101}
}
start_server {tags {"auth_binary_password"}} {
test {AUTH fails when binary password is wrong} {
r config set requirepass "abc\x00def"
catch {r auth abc} err
set _ $err
} {WRONGPASS*}
test {AUTH succeeds when binary password is correct} {
r config set requirepass "abc\x00def"
r auth "abc\x00def"
} {OK}
start_server {tags {"masterauth"}} {
set master [srv -1 client]
set master_host [srv -1 host]
set master_port [srv -1 port]
set slave [srv 0 client]
test {MASTERAUTH test with binary password} {
$master config set requirepass "abc\x00def"
# Configure the replica with masterauth
set loglines [count_log_lines 0]
$slave slaveof $master_host $master_port
$slave config set masterauth "abc"
# Verify replica is not able to sync with master
wait_for_log_messages 0 {"*Unable to AUTH to MASTER*"} $loglines 1000 10
assert_equal {down} [s 0 master_link_status]
# Test replica with the correct masterauth
$slave config set masterauth "abc\x00def"
wait_for_condition 50 100 {
[s 0 master_link_status] eq {up}
} else {
fail "Can't turn the instance into a replica"
}
}
}
}
+4 -4
View File
@@ -12,7 +12,7 @@ start_server {tags {"dump"}} {
r del foo
r restore foo 5000 $encoded
set ttl [r pttl foo]
assert {$ttl >= 3000 && $ttl <= 5000}
assert_range $ttl 3000 5000
r get foo
} {bar}
@@ -22,7 +22,7 @@ start_server {tags {"dump"}} {
r del foo
r restore foo 2569591501 $encoded
set ttl [r pttl foo]
assert {$ttl >= (2569591501-3000) && $ttl <= 2569591501}
assert_range $ttl (2569591501-3000) 2569591501
r get foo
} {bar}
@@ -33,7 +33,7 @@ start_server {tags {"dump"}} {
set now [clock milliseconds]
r restore foo [expr $now+3000] $encoded absttl
set ttl [r pttl foo]
assert {$ttl >= 2900 && $ttl <= 3100}
assert_range $ttl 2000 3100
r get foo
} {bar}
@@ -170,7 +170,7 @@ start_server {tags {"dump"}} {
$second set list somevalue
catch {r -1 migrate $second_host $second_port list 9 5000 copy} e
assert_match {ERR*} $e
set res [r -1 migrate $second_host $second_port list 9 5000 copy replace]
set ret [r -1 migrate $second_host $second_port list 9 5000 copy replace]
assert {$ret eq {OK}}
assert {[$first exists list] == 1}
assert {[$second exists list] == 1}
+173 -10
View File
@@ -209,19 +209,153 @@ start_server {tags {"expire"}} {
set e
} {*not an integer*}
test {SET - use EX/PX option, TTL should not be reseted after loadaof} {
r config set appendonly yes
r set foo bar EX 100
after 2000
r debug loadaof
set ttl [r ttl foo]
assert {$ttl <= 98 && $ttl > 90}
test {SET with EX with big integer should report an error} {
catch {r set foo bar EX 10000000000000000} e
set e
} {ERR invalid expire time in set}
test {SET with EX with smallest integer should report an error} {
catch {r SET foo bar EX -9999999999999999} e
set e
} {ERR invalid expire time in set}
test {GETEX with big integer should report an error} {
r set foo bar
catch {r GETEX foo EX 10000000000000000} e
set e
} {ERR invalid expire time in getex}
test {GETEX with smallest integer should report an error} {
r set foo bar
catch {r GETEX foo EX -9999999999999999} e
set e
} {ERR invalid expire time in getex}
test {EXPIRE with big integer overflows when converted to milliseconds} {
r set foo bar
catch {r EXPIRE foo 10000000000000000} e
set e
} {ERR invalid expire time in expire}
test {PEXPIRE with big integer overflow when basetime is added} {
r set foo bar
catch {r PEXPIRE foo 9223372036854770000} e
set e
} {ERR invalid expire time in pexpire}
test {EXPIRE with big negative integer} {
r set foo bar
catch {r EXPIRE foo -9999999999999999} e
assert_match {ERR invalid expire time in expire} $e
r ttl foo
} {-1}
test {PEXPIREAT with big integer works} {
r set foo bar
r PEXPIREAT foo 9223372036854770000
} {1}
test {PEXPIREAT with big negative integer works} {
r set foo bar
r PEXPIREAT foo -9223372036854770000
r ttl foo
} {-2}
test {EXPIRE and SET/GETEX EX/PX/EXAT/PXAT option, TTL should not be reset after loadaof} {
# This test makes sure that expire times are propagated as absolute
# times to the AOF file and not as relative time, so that when the AOF
# is reloaded the TTLs are not being shifted forward to the future.
# We want the time to logically pass when the server is restarted!
r config set appendonly yes
r set foo1 bar EX 100
r set foo2 bar PX 100000
r set foo3 bar
r set foo4 bar
r expire foo3 100
r pexpire foo4 100000
r setex foo5 100 bar
r psetex foo6 100000 bar
r set foo7 bar EXAT [expr [clock seconds] + 100]
r set foo8 bar PXAT [expr [clock milliseconds] + 100000]
r set foo9 bar
r getex foo9 EX 100
r set foo10 bar
r getex foo10 PX 100000
r set foo11 bar
r getex foo11 EXAT [expr [clock seconds] + 100]
r set foo12 bar
r getex foo12 PXAT [expr [clock milliseconds] + 100000]
r set foo bar PX 100000
after 2000
r debug loadaof
set ttl [r ttl foo]
assert {$ttl <= 98 && $ttl > 90}
assert_range [r ttl foo1] 90 98
assert_range [r ttl foo2] 90 98
assert_range [r ttl foo3] 90 98
assert_range [r ttl foo4] 90 98
assert_range [r ttl foo5] 90 98
assert_range [r ttl foo6] 90 98
assert_range [r ttl foo7] 90 98
assert_range [r ttl foo8] 90 98
assert_range [r ttl foo9] 90 98
assert_range [r ttl foo10] 90 98
assert_range [r ttl foo11] 90 98
assert_range [r ttl foo12] 90 98
}
test {EXPIRE relative and absolute propagation to replicas} {
# Make sure that relative and absolute expire commands are propagated
# "as is" to replicas.
# We want replicas to honor the same high level contract of expires that
# the master has, that is, we want the time to be counted logically
# starting from the moment the write was received. This usually provides
# the most coherent behavior from the point of view of the external
# users, with TTLs that are similar from the POV of the external observer.
#
# This test is here to stop some innocent / eager optimization or cleanup
# from doing the wrong thing without proper discussion, see:
# https://github.com/redis/redis/pull/5171#issuecomment-409553266
set repl [attach_to_replication_stream]
r set foo1 bar ex 200
r set foo1 bar px 100000
r set foo1 bar exat [expr [clock seconds]+100]
r set foo1 bar pxat [expr [clock milliseconds]+10000]
r setex foo1 100 bar
r psetex foo1 100000 bar
r set foo2 bar
r expire foo2 100
r pexpire foo2 100000
r set foo3 bar
r expireat foo3 [expr [clock seconds]+100]
r pexpireat foo3 [expr [clock seconds]*1000+100000]
r expireat foo3 [expr [clock seconds]-100]
r set foo4 bar
r getex foo4 ex 200
r getex foo4 px 200000
r getex foo4 exat [expr [clock seconds]+100]
r getex foo4 pxat [expr [clock milliseconds]+10000]
assert_replication_stream $repl {
{select *}
{set foo1 bar PX 200000}
{set foo1 bar PX 100000}
{set foo1 bar PXAT *}
{set foo1 bar PXAT *}
{set foo1 bar PX 100000}
{set foo1 bar PX 100000}
{set foo2 bar}
{expire foo2 100}
{pexpire foo2 100000}
{set foo3 bar}
{expireat foo3 *}
{pexpireat foo3 *}
{del foo3}
{set foo4 bar}
{pexpire foo4 200000}
{pexpire foo4 200000}
{pexpireat foo4 *}
{pexpireat foo4 *}
}
}
test {EXPIREMEMBER works (set)} {
@@ -318,6 +452,7 @@ start_server {tags {"expire"}} {
assert_equal [r dbsize] 0
}
test {SET - use KEEPTTL option, TTL should not be removed after loadaof} {
r config set appendonly yes
r set foo bar EX 100
@@ -327,4 +462,32 @@ start_server {tags {"expire"}} {
set ttl [r ttl foo]
assert {$ttl <= 98 && $ttl > 90}
}
test {GETEX use of PERSIST option should remove TTL} {
r set foo bar EX 100
r getex foo PERSIST
r ttl foo
} {-1}
test {GETEX use of PERSIST option should remove TTL after loadaof} {
r set foo bar EX 100
r getex foo PERSIST
after 2000
r debug loadaof
r ttl foo
} {-1}
test {GETEX propagate as to replica as PERSIST, DEL, or nothing} {
set repl [attach_to_replication_stream]
r set foo bar EX 100
r getex foo PERSIST
r getex foo
r getex foo exat [expr [clock seconds]-100]
assert_replication_stream $repl {
{select *}
{set foo bar PX 100000}
{persist foo}
{del foo}
}
}
}
+323 -24
View File
@@ -1,6 +1,7 @@
# Helper functions to simulate search-in-radius in the Tcl side in order to
# verify the Redis implementation with a fuzzy test.
proc geo_degrad deg {expr {$deg*atan(1)*8/360}}
proc geo_degrad deg {expr {$deg*(atan(1)*8/360)}}
proc geo_raddeg rad {expr {$rad/(atan(1)*8/360)}}
proc geo_distance {lon1d lat1d lon2d lat2d} {
set lon1r [geo_degrad $lon1d]
@@ -42,6 +43,34 @@ proc compare_lists {List1 List2} {
return $DiffList
}
# return true If a point in circle.
# search_lon and search_lat define the center of the circle,
# and lon, lat define the point being searched.
proc pointInCircle {radius_km lon lat search_lon search_lat} {
set radius_m [expr {$radius_km*1000}]
set distance [geo_distance $lon $lat $search_lon $search_lat]
if {$distance < $radius_m} {
return true
}
return false
}
# return true If a point in rectangle.
# search_lon and search_lat define the center of the rectangle,
# and lon, lat define the point being searched.
# error: can adjust the width and height of the rectangle according to the error
proc pointInRectangle {width_km height_km lon lat search_lon search_lat error} {
set width_m [expr {$width_km*1000*$error/2}]
set height_m [expr {$height_km*1000*$error/2}]
set lon_distance [geo_distance $lon $lat $search_lon $lat]
set lat_distance [geo_distance $lon $lat $lon $search_lat]
if {$lon_distance > $width_m || $lat_distance > $height_m} {
return false
}
return true
}
# The following list represents sets of random seed, search position
# and radius that caused bugs in the past. It is used by the randomized
# test later as a starting point. When the regression vectors are scanned
@@ -74,6 +103,49 @@ start_server {tags {"geo"}} {
r geoadd nyc -73.9454966 40.747533 "lic market"
} {0}
test {GEOADD update with CH option} {
assert_equal 1 [r geoadd nyc CH 40.747533 -73.9454966 "lic market"]
lassign [lindex [r geopos nyc "lic market"] 0] x1 y1
assert {abs($x1) - 40.747 < 0.001}
assert {abs($y1) - 73.945 < 0.001}
} {}
test {GEOADD update with NX option} {
assert_equal 0 [r geoadd nyc NX -73.9454966 40.747533 "lic market"]
lassign [lindex [r geopos nyc "lic market"] 0] x1 y1
assert {abs($x1) - 40.747 < 0.001}
assert {abs($y1) - 73.945 < 0.001}
} {}
test {GEOADD update with XX option} {
assert_equal 0 [r geoadd nyc XX -83.9454966 40.747533 "lic market"]
lassign [lindex [r geopos nyc "lic market"] 0] x1 y1
assert {abs($x1) - 83.945 < 0.001}
assert {abs($y1) - 40.747 < 0.001}
} {}
test {GEOADD update with CH NX option} {
r geoadd nyc CH NX -73.9454966 40.747533 "lic market"
} {0}
test {GEOADD update with CH XX option} {
r geoadd nyc CH XX -73.9454966 40.747533 "lic market"
} {1}
test {GEOADD update with XX NX option will return syntax error} {
catch {
r geoadd nyc xx nx -73.9454966 40.747533 "lic market"
} err
set err
} {ERR*syntax*}
test {GEOADD update with invalid option} {
catch {
r geoadd nyc ch xx foo -73.9454966 40.747533 "lic market"
} err
set err
} {ERR*syntax*}
test {GEOADD invalid coordinates} {
catch {
r geoadd nyc -73.9454966 40.747533 "lic market" \
@@ -94,14 +166,60 @@ start_server {tags {"geo"}} {
r georadius nyc -73.9798091 40.7598464 3 km asc
} {{central park n/q/r} 4545 {union square}}
test {GEOSEARCH simple (sorted)} {
r geosearch nyc fromlonlat -73.9798091 40.7598464 bybox 6 6 km asc
} {{central park n/q/r} 4545 {union square} {lic market}}
test {GEOSEARCH FROMLONLAT and FROMMEMBER cannot exist at the same time} {
catch {r geosearch nyc fromlonlat -73.9798091 40.7598464 frommember xxx bybox 6 6 km asc} e
set e
} {ERR*syntax*}
test {GEOSEARCH FROMLONLAT and FROMMEMBER one must exist} {
catch {r geosearch nyc bybox 3 3 km asc desc withhash withdist withcoord} e
set e
} {ERR*exactly one of FROMMEMBER or FROMLONLAT*}
test {GEOSEARCH BYRADIUS and BYBOX cannot exist at the same time} {
catch {r geosearch nyc fromlonlat -73.9798091 40.7598464 byradius 3 km bybox 3 3 km asc} e
set e
} {ERR*syntax*}
test {GEOSEARCH BYRADIUS and BYBOX one must exist} {
catch {r geosearch nyc fromlonlat -73.9798091 40.7598464 asc desc withhash withdist withcoord} e
set e
} {ERR*exactly one of BYRADIUS and BYBOX*}
test {GEOSEARCH with STOREDIST option} {
catch {r geosearch nyc fromlonlat -73.9798091 40.7598464 bybox 6 6 km asc storedist} e
set e
} {ERR*syntax*}
test {GEORADIUS withdist (sorted)} {
r georadius nyc -73.9798091 40.7598464 3 km withdist asc
} {{{central park n/q/r} 0.7750} {4545 2.3651} {{union square} 2.7697}}
test {GEOSEARCH withdist (sorted)} {
r geosearch nyc fromlonlat -73.9798091 40.7598464 bybox 6 6 km withdist asc
} {{{central park n/q/r} 0.7750} {4545 2.3651} {{union square} 2.7697} {{lic market} 3.1991}}
test {GEORADIUS with COUNT} {
r georadius nyc -73.9798091 40.7598464 10 km COUNT 3
} {{central park n/q/r} 4545 {union square}}
test {GEORADIUS with ANY not sorted by default} {
r georadius nyc -73.9798091 40.7598464 10 km COUNT 3 ANY
} {{wtc one} {union square} {central park n/q/r}}
test {GEORADIUS with ANY sorted by ASC} {
r georadius nyc -73.9798091 40.7598464 10 km COUNT 3 ANY ASC
} {{central park n/q/r} {union square} {wtc one}}
test {GEORADIUS with ANY but no COUNT} {
catch {r georadius nyc -73.9798091 40.7598464 10 km ANY ASC} e
set e
} {ERR*ANY*requires*COUNT*}
test {GEORADIUS with COUNT but missing integer argument} {
catch {r georadius nyc -73.9798091 40.7598464 10 km COUNT} e
set e
@@ -120,6 +238,42 @@ start_server {tags {"geo"}} {
r georadiusbymember nyc "wtc one" 7 km
} {{wtc one} {union square} {central park n/q/r} 4545 {lic market}}
test {GEOSEARCH FROMMEMBER simple (sorted)} {
r geosearch nyc frommember "wtc one" bybox 14 14 km
} {{wtc one} {union square} {central park n/q/r} 4545 {lic market} q4}
test {GEOSEARCH vs GEORADIUS} {
r del Sicily
r geoadd Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania"
r geoadd Sicily 12.758489 38.788135 "edge1" 17.241510 38.788135 "eage2"
set ret1 [r georadius Sicily 15 37 200 km asc]
assert_equal $ret1 {Catania Palermo}
set ret2 [r geosearch Sicily fromlonlat 15 37 bybox 400 400 km asc]
assert_equal $ret2 {Catania Palermo eage2 edge1}
}
test {GEOSEARCH non square, long and narrow} {
r del Sicily
r geoadd Sicily 12.75 36.995 "test1"
r geoadd Sicily 12.75 36.50 "test2"
r geoadd Sicily 13.00 36.50 "test3"
# box height=2km width=400km
set ret1 [r geosearch Sicily fromlonlat 15 37 bybox 400 2 km]
assert_equal $ret1 {test1}
# Add a western Hemisphere point
r geoadd Sicily -1 37.00 "test3"
set ret2 [r geosearch Sicily fromlonlat 15 37 bybox 3000 2 km asc]
assert_equal $ret2 {test1 test3}
}
test {GEOSEARCH corner point test} {
r del Sicily
r geoadd Sicily 12.758489 38.788135 edge1 17.241510 38.788135 edge2 17.250000 35.202000 edge3 12.750000 35.202000 edge4 12.748489955781654 37 edge5 15 38.798135872540925 edge6 17.251510044218346 37 edge7 15 35.201864127459075 edge8 12.692799634687903 38.798135872540925 corner1 12.692799634687903 38.798135872540925 corner2 17.200560937451133 35.201864127459075 corner3 12.799439062548865 35.201864127459075 corner4
set ret [lsort [r geosearch Sicily fromlonlat 15 37 bybox 400 400 km asc]]
assert_equal $ret {edge1 edge2 edge5 edge7}
}
test {GEORADIUSBYMEMBER withdist (sorted)} {
r georadiusbymember nyc "wtc one" 7 km withdist
} {{{wtc one} 0.0000} {{union square} 3.2544} {{central park n/q/r} 6.7000} {4545 6.1975} {{lic market} 6.8969}}
@@ -178,6 +332,11 @@ start_server {tags {"geo"}} {
set e
} {*ERR*syntax*}
test {GEOSEARCHSTORE STORE option: syntax error} {
catch {r geosearchstore abc points fromlonlat 13.361389 38.115556 byradius 50 km store abc} e
set e
} {*ERR*syntax*}
test {GEORANGE STORE option: incompatible options} {
r del points
r geoadd points 13.361389 38.115556 "Palermo" \
@@ -198,6 +357,11 @@ start_server {tags {"geo"}} {
assert_equal [r zrange points 0 -1] [r zrange points2 0 -1]
}
test {GEOSEARCHSTORE STORE option: plain usage} {
r geosearchstore points2 points fromlonlat 13.361389 38.115556 byradius 500 km
assert_equal [r zrange points 0 -1] [r zrange points2 0 -1]
}
test {GEORANGE STOREDIST option: plain usage} {
r del points
r geoadd points 13.361389 38.115556 "Palermo" \
@@ -209,6 +373,14 @@ start_server {tags {"geo"}} {
assert {[lindex $res 3] < 167}
}
test {GEOSEARCHSTORE STOREDIST option: plain usage} {
r geosearchstore points2 points fromlonlat 13.361389 38.115556 byradius 500 km storedist
set res [r zrange points2 0 -1 withscores]
assert {[lindex $res 1] < 1}
assert {[lindex $res 3] > 166}
assert {[lindex $res 3] < 167}
}
test {GEORANGE STOREDIST option: COUNT ASC and DESC} {
r del points
r geoadd points 13.361389 38.115556 "Palermo" \
@@ -224,12 +396,22 @@ start_server {tags {"geo"}} {
assert {[lindex $res 0] eq "Catania"}
}
test {GEOADD + GEORANGE randomized test} {
set attempt 30
test {GEOSEARCH the box spans -180° or 180°} {
r del points
r geoadd points 179.5 36 point1
r geoadd points -179.5 36 point2
assert_equal {point1 point2} [r geosearch points fromlonlat 179 37 bybox 400 400 km asc]
assert_equal {point2 point1} [r geosearch points fromlonlat -179 37 bybox 400 400 km asc]
}
foreach {type} {byradius bybox} {
test "GEOSEARCH fuzzy test - $type" {
if {$::accurate} { set attempt 300 } else { set attempt 30 }
while {[incr attempt -1]} {
set rv [lindex $regression_vectors $rv_idx]
incr rv_idx
set radius_km 0; set width_km 0; set height_km 0
unset -nocomplain debuginfo
set srand_seed [clock milliseconds]
if {$rv ne {}} {set srand_seed [lindex $rv 0]}
@@ -239,33 +421,55 @@ start_server {tags {"geo"}} {
if {[randomInt 10] == 0} {
# From time to time use very big radiuses
set radius_km [expr {[randomInt 50000]+10}]
if {$type == "byradius"} {
set radius_km [expr {[randomInt 5000]+10}]
} elseif {$type == "bybox"} {
set width_km [expr {[randomInt 5000]+10}]
set height_km [expr {[randomInt 5000]+10}]
}
} else {
# Normally use a few - ~200km radiuses to stress
# test the code the most in edge cases.
set radius_km [expr {[randomInt 200]+10}]
if {$type == "byradius"} {
set radius_km [expr {[randomInt 200]+10}]
} elseif {$type == "bybox"} {
set width_km [expr {[randomInt 200]+10}]
set height_km [expr {[randomInt 200]+10}]
}
}
if {$rv ne {}} {
set radius_km [lindex $rv 1]
set width_km [lindex $rv 1]
set height_km [lindex $rv 1]
}
if {$rv ne {}} {set radius_km [lindex $rv 1]}
set radius_m [expr {$radius_km*1000}]
geo_random_point search_lon search_lat
if {$rv ne {}} {
set search_lon [lindex $rv 2]
set search_lat [lindex $rv 3]
}
lappend debuginfo "Search area: $search_lon,$search_lat $radius_km km"
lappend debuginfo "Search area: $search_lon,$search_lat $radius_km $width_km $height_km km"
set tcl_result {}
set argv {}
for {set j 0} {$j < 20000} {incr j} {
geo_random_point lon lat
lappend argv $lon $lat "place:$j"
set distance [geo_distance $lon $lat $search_lon $search_lat]
if {$distance < $radius_m} {
lappend tcl_result "place:$j"
if {$type == "byradius"} {
if {[pointInCircle $radius_km $lon $lat $search_lon $search_lat]} {
lappend tcl_result "place:$j"
}
} elseif {$type == "bybox"} {
if {[pointInRectangle $width_km $height_km $lon $lat $search_lon $search_lat 1]} {
lappend tcl_result "place:$j"
}
}
lappend debuginfo "place:$j $lon $lat [expr {$distance/1000}] km"
lappend debuginfo "place:$j $lon $lat"
}
r geoadd mypoints {*}$argv
set res [lsort [r georadius mypoints $search_lon $search_lat $radius_km km]]
if {$type == "byradius"} {
set res [lsort [r geosearch mypoints fromlonlat $search_lon $search_lat byradius $radius_km km]]
} elseif {$type == "bybox"} {
set res [lsort [r geosearch mypoints fromlonlat $search_lon $search_lat bybox $width_km $height_km km]]
}
set res2 [lsort $tcl_result]
set test_result OK
@@ -273,18 +477,27 @@ start_server {tags {"geo"}} {
set rounding_errors 0
set diff [compare_lists $res $res2]
foreach place $diff {
lassign [lindex [r geopos mypoints $place] 0] lon lat
set mydist [geo_distance $lon $lat $search_lon $search_lat]
set mydist [expr $mydist/1000]
if {($mydist / $radius_km) > 0.999} {
incr rounding_errors
continue
}
if {$mydist < $radius_m} {
# This is a false positive for redis since given the
# same points the higher precision calculation provided
# by TCL shows the point within range
incr rounding_errors
continue
if {$type == "byradius"} {
if {($mydist / $radius_km) > 0.999} {
incr rounding_errors
continue
}
if {$mydist < [expr {$radius_km*1000}]} {
# This is a false positive for redis since given the
# same points the higher precision calculation provided
# by TCL shows the point within range
incr rounding_errors
continue
}
} elseif {$type == "bybox"} {
# we add 0.1% error for floating point calculation error
if {[pointInRectangle $width_km $height_km $lon $lat $search_lon $search_lat 1.001]} {
incr rounding_errors
continue
}
}
}
@@ -311,7 +524,6 @@ start_server {tags {"geo"}} {
set mydist [geo_distance $lon $lat $search_lon $search_lat]
set mydist [expr $mydist/1000]
puts "$place -> [r geopos mypoints $place] $mydist $where"
if {($mydist / $radius_km) > 0.999} {incr rounding_errors}
}
set test_result FAIL
}
@@ -320,4 +532,91 @@ start_server {tags {"geo"}} {
}
set test_result
} {OK}
}
test {GEOSEARCH box edges fuzzy test} {
if {$::accurate} { set attempt 300 } else { set attempt 30 }
while {[incr attempt -1]} {
unset -nocomplain debuginfo
set srand_seed [clock milliseconds]
lappend debuginfo "srand_seed is $srand_seed"
expr {srand($srand_seed)} ; # If you need a reproducible run
r del mypoints
geo_random_point search_lon search_lat
set width_m [expr {[randomInt 10000]+10}]
set height_m [expr {[randomInt 10000]+10}]
set lat_delta [geo_raddeg [expr {$height_m/2/6372797.560856}]]
set long_delta_top [geo_raddeg [expr {$width_m/2/6372797.560856/cos([geo_degrad [expr {$search_lat+$lat_delta}]])}]]
set long_delta_middle [geo_raddeg [expr {$width_m/2/6372797.560856/cos([geo_degrad $search_lat])}]]
set long_delta_bottom [geo_raddeg [expr {$width_m/2/6372797.560856/cos([geo_degrad [expr {$search_lat-$lat_delta}]])}]]
# Total of 8 points are generated, which are located at each vertex and the center of each side
set points(north) [list $search_lon [expr {$search_lat+$lat_delta}]]
set points(south) [list $search_lon [expr {$search_lat-$lat_delta}]]
set points(east) [list [expr {$search_lon+$long_delta_middle}] $search_lat]
set points(west) [list [expr {$search_lon-$long_delta_middle}] $search_lat]
set points(north_east) [list [expr {$search_lon+$long_delta_top}] [expr {$search_lat+$lat_delta}]]
set points(north_west) [list [expr {$search_lon-$long_delta_top}] [expr {$search_lat+$lat_delta}]]
set points(south_east) [list [expr {$search_lon+$long_delta_bottom}] [expr {$search_lat-$lat_delta}]]
set points(south_west) [list [expr {$search_lon-$long_delta_bottom}] [expr {$search_lat-$lat_delta}]]
lappend debuginfo "Search area: geosearch mypoints fromlonlat $search_lon $search_lat bybox $width_m $height_m m"
set tcl_result {}
foreach name [array names points] {
set x [lindex $points($name) 0]
set y [lindex $points($name) 1]
# If longitude crosses -180° or 180°, we need to convert it.
# latitude doesn't have this problem, because it's scope is -70~70, see geo_random_point
if {$x > 180} {
set x [expr {$x-360}]
} elseif {$x < -180} {
set x [expr {$x+360}]
}
r geoadd mypoints $x $y place:$name
lappend tcl_result "place:$name"
lappend debuginfo "geoadd mypoints $x $y place:$name"
}
set res2 [lsort $tcl_result]
# make the box larger by two meter in each direction to put the coordinate slightly inside the box.
set height_new [expr {$height_m+4}]
set width_new [expr {$width_m+4}]
set res [lsort [r geosearch mypoints fromlonlat $search_lon $search_lat bybox $width_new $height_new m]]
if {$res != $res2} {
set diff [compare_lists $res $res2]
lappend debuginfo "res: $res, res2: $res2, diff: $diff"
fail "place should be found, debuginfo: $debuginfo, height_new: $height_new width_new: $width_new"
}
# The width decreases and the height increases. Only north and south are found
set width_new [expr {$width_m-4}]
set height_new [expr {$height_m+4}]
set res [lsort [r geosearch mypoints fromlonlat $search_lon $search_lat bybox $width_new $height_new m]]
if {$res != {place:north place:south}} {
lappend debuginfo "res: $res"
fail "place should not be found, debuginfo: $debuginfo, height_new: $height_new width_new: $width_new"
}
# The width increases and the height decreases. Only ease and west are found
set width_new [expr {$width_m+4}]
set height_new [expr {$height_m-4}]
set res [lsort [r geosearch mypoints fromlonlat $search_lon $search_lat bybox $width_new $height_new m]]
if {$res != {place:east place:west}} {
lappend debuginfo "res: $res"
fail "place should not be found, debuginfo: $debuginfo, height_new: $height_new width_new: $width_new"
}
# make the box smaller by two meter in each direction to put the coordinate slightly outside the box.
set height_new [expr {$height_m-4}]
set width_new [expr {$width_m-4}]
set res [r geosearch mypoints fromlonlat $search_lon $search_lat bybox $width_new $height_new m]
if {$res != ""} {
lappend debuginfo "res: $res"
fail "place should not be found, debuginfo: $debuginfo, height_new: $height_new width_new: $width_new"
}
unset -nocomplain debuginfo
}
}
}
+174
View File
@@ -0,0 +1,174 @@
proc cmdstat {cmd} {
return [cmdrstat $cmd r]
}
proc errorstat {cmd} {
return [errorrstat $cmd r]
}
start_server {tags {"info"}} {
start_server {} {
test {errorstats: failed call authentication error} {
r config resetstat
assert_match {} [errorstat ERR]
assert_equal [s total_error_replies] 0
catch {r auth k} e
assert_match {ERR AUTH*} $e
assert_match {*count=1*} [errorstat ERR]
assert_match {*calls=1,*,rejected_calls=0,failed_calls=1} [cmdstat auth]
assert_equal [s total_error_replies] 1
r config resetstat
assert_match {} [errorstat ERR]
}
test {errorstats: failed call within MULTI/EXEC} {
r config resetstat
assert_match {} [errorstat ERR]
assert_equal [s total_error_replies] 0
r multi
r set a b
r auth a
catch {r exec} e
assert_match {ERR AUTH*} $e
assert_match {*count=1*} [errorstat ERR]
assert_match {*calls=1,*,rejected_calls=0,failed_calls=0} [cmdstat set]
assert_match {*calls=1,*,rejected_calls=0,failed_calls=1} [cmdstat auth]
assert_match {*calls=1,*,rejected_calls=0,failed_calls=0} [cmdstat exec]
assert_equal [s total_error_replies] 1
# MULTI/EXEC command errors should still be pinpointed to him
catch {r exec} e
assert_match {ERR EXEC without MULTI} $e
assert_match {*calls=2,*,rejected_calls=0,failed_calls=1} [cmdstat exec]
assert_match {*count=2*} [errorstat ERR]
assert_equal [s total_error_replies] 2
}
test {errorstats: failed call within LUA} {
r config resetstat
assert_match {} [errorstat ERR]
assert_equal [s total_error_replies] 0
catch {r eval {redis.pcall('XGROUP', 'CREATECONSUMER', 's1', 'mygroup', 'consumer') return } 0} e
assert_match {*count=1*} [errorstat ERR]
assert_match {*calls=1,*,rejected_calls=0,failed_calls=1} [cmdstat xgroup]
assert_match {*calls=1,*,rejected_calls=0,failed_calls=0} [cmdstat eval]
# EVAL command errors should still be pinpointed to him
catch {r eval a} e
assert_match {ERR wrong*} $e
assert_match {*calls=1,*,rejected_calls=1,failed_calls=0} [cmdstat eval]
assert_match {*count=2*} [errorstat ERR]
assert_equal [s total_error_replies] 2
}
test {errorstats: failed call NOSCRIPT error} {
r config resetstat
assert_equal [s total_error_replies] 0
assert_match {} [errorstat NOSCRIPT]
catch {r evalsha NotValidShaSUM 0} e
assert_match {NOSCRIPT*} $e
assert_match {*count=1*} [errorstat NOSCRIPT]
assert_match {*calls=1,*,rejected_calls=0,failed_calls=1} [cmdstat evalsha]
assert_equal [s total_error_replies] 1
r config resetstat
assert_match {} [errorstat NOSCRIPT]
}
test {errorstats: failed call NOGROUP error} {
r config resetstat
assert_match {} [errorstat NOGROUP]
r del mystream
r XADD mystream * f v
catch {r XGROUP CREATECONSUMER mystream mygroup consumer} e
assert_match {NOGROUP*} $e
assert_match {*count=1*} [errorstat NOGROUP]
assert_match {*calls=1,*,rejected_calls=0,failed_calls=1} [cmdstat xgroup]
r config resetstat
assert_match {} [errorstat NOGROUP]
}
test {errorstats: rejected call unknown command} {
r config resetstat
assert_equal [s total_error_replies] 0
assert_match {} [errorstat ERR]
catch {r asdf} e
assert_match {ERR unknown*} $e
assert_match {*count=1*} [errorstat ERR]
assert_equal [s total_error_replies] 1
r config resetstat
assert_match {} [errorstat ERR]
}
test {errorstats: rejected call within MULTI/EXEC} {
r config resetstat
assert_equal [s total_error_replies] 0
assert_match {} [errorstat ERR]
r multi
catch {r set} e
assert_match {ERR wrong number of arguments*} $e
catch {r exec} e
assert_match {EXECABORT*} $e
assert_match {*count=1*} [errorstat ERR]
assert_equal [s total_error_replies] 1
assert_match {*calls=0,*,rejected_calls=1,failed_calls=0} [cmdstat set]
assert_match {*calls=1,*,rejected_calls=0,failed_calls=0} [cmdstat multi]
assert_match {*calls=1,*,rejected_calls=0,failed_calls=0} [cmdstat exec]
assert_equal [s total_error_replies] 1
r config resetstat
assert_match {} [errorstat ERR]
}
test {errorstats: rejected call due to wrong arity} {
r config resetstat
assert_equal [s total_error_replies] 0
assert_match {} [errorstat ERR]
catch {r set k} e
assert_match {ERR wrong number of arguments*} $e
assert_match {*count=1*} [errorstat ERR]
assert_match {*calls=0,*,rejected_calls=1,failed_calls=0} [cmdstat set]
# ensure that after a rejected command, valid ones are counted properly
r set k1 v1
r set k2 v2
assert_match {calls=2,*,rejected_calls=1,failed_calls=0} [cmdstat set]
assert_equal [s total_error_replies] 1
}
test {errorstats: rejected call by OOM error} {
r config resetstat
assert_equal [s total_error_replies] 0
assert_match {} [errorstat OOM]
r config set maxmemory 1
catch {r set a b} e
assert_match {OOM*} $e
assert_match {*count=1*} [errorstat OOM]
assert_match {*calls=0,*,rejected_calls=1,failed_calls=0} [cmdstat set]
assert_equal [s total_error_replies] 1
r config resetstat
assert_match {} [errorstat OOM]
}
test {errorstats: rejected call by authorization error} {
r config resetstat
assert_equal [s total_error_replies] 0
assert_match {} [errorstat NOPERM]
r ACL SETUSER alice on >p1pp0 ~cached:* +get +info +config
r auth alice p1pp0
catch {r set a b} e
assert_match {NOPERM*} $e
assert_match {*count=1*} [errorstat NOPERM]
assert_match {*calls=0,*,rejected_calls=1,failed_calls=0} [cmdstat set]
assert_equal [s total_error_replies] 1
r config resetstat
assert_match {} [errorstat NOPERM]
}
}
start_server {} {
test {Unsafe command names are sanitized in INFO output} {
catch {r host:} e
set info [r info commandstats]
assert_match {*cmdstat_host_:calls=1*} $info
}
}
}
+1 -3
View File
@@ -1,7 +1,5 @@
proc cmdstat {cmd} {
if {[regexp "\r\ncmdstat_$cmd:(.*?)\r\n" [r info commandstats] _ value]} {
set _ $value
}
return [cmdrstat $cmd r]
}
start_server {tags {"introspection"}} {
+31 -6
View File
@@ -3,6 +3,16 @@ start_server {tags {"introspection"}} {
r client list
} {*addr=*:* fd=* age=* idle=* flags=N db=9 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=* argv-mem=* obl=0 oll=0 omem=0 tot-mem=* events=r cmd=client*}
test {CLIENT LIST with IDs} {
set myid [r client id]
set cl [split [r client list id $myid] "\r\n"]
assert_match "id=$myid*" [lindex $cl 0]
}
test {CLIENT INFO} {
r client info
} {*addr=*:* fd=* age=* idle=* flags=N db=9 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=* argv-mem=* obl=0 oll=0 omem=0 tot-mem=* events=r cmd=client*}
test {MONITOR can log executed commands} {
set rd [redis_deferring_client]
$rd monitor
@@ -58,6 +68,19 @@ start_server {tags {"introspection"}} {
}
}
test {CONFIG save params special case handled properly} {
# No "save" keyword - defaults should apply
start_server {config "minimal.conf"} {
assert_match [r config get save] {save {3600 1 300 100 60 10000}}
}
# First "save" keyword overrides defaults
start_server {config "minimal.conf" overrides {save {100 100}}} {
# Defaults
assert_match [r config get save] {save {100 100}}
}
}
test {CONFIG sanity} {
# Do CONFIG GET, CONFIG SET and then CONFIG GET again
# Skip immutable configs, one with no get, and other complicated configs
@@ -78,20 +101,19 @@ start_server {tags {"introspection"}} {
supervised
syslog-facility
databases
port
tls-port
io-threads
logfile
unixsocketperm
slaveof
bind
requirepass
multi-master
server_cpulist
bio_cpulist
aof_rewrite_cpulist
bgsave_cpulist
multi-master
active-replica
bind
set-proc-title
}
if {!$::tls} {
@@ -102,12 +124,15 @@ start_server {tags {"introspection"}} {
tls-session-caching
tls-cert-file
tls-key-file
tls-client-cert-file
tls-client-key-file
tls-dh-params-file
tls-ca-cert-file
tls-ca-cert-dir
tls-protocols
tls-ciphers
tls-ciphersuites
tls-port
}
}
@@ -150,12 +175,12 @@ start_server {tags {"introspection"}} {
# Rewrite entire configuration, restart and confirm the
# server is able to parse it and start.
assert_equal [r debug config-rewrite-force-all] "OK"
restart_server 0 0
restart_server 0 true false
assert_equal [r ping] "PONG"
# Verify no changes were introduced
dict for {k v} $configs {
assert_equal $v [lindex [r config get $k] 1] $k
assert_equal $v [lindex [r config get $k] 1]
}
}
+208 -1
View File
@@ -169,6 +169,213 @@ start_server {tags {"keyspace"}} {
format $res
} {0}
test {COPY basic usage for string} {
r set mykey foobar
set res {}
r copy mykey mynewkey
lappend res [r get mynewkey]
lappend res [r dbsize]
r copy mykey mynewkey DB 10
r select 10
lappend res [r get mynewkey]
lappend res [r dbsize]
r select 9
format $res
} [list foobar 2 foobar 1]
test {COPY for string does not replace an existing key without REPLACE option} {
r set mykey2 hello
catch {r copy mykey2 mynewkey DB 10} e
set e
} {0}
test {COPY for string can replace an existing key with REPLACE option} {
r copy mykey2 mynewkey DB 10 REPLACE
r select 10
r get mynewkey
} {hello}
test {COPY for string ensures that copied data is independent of copying data} {
r flushdb
r select 9
r set mykey foobar
set res {}
r copy mykey mynewkey DB 10
r select 10
lappend res [r get mynewkey]
r set mynewkey hoge
lappend res [r get mynewkey]
r select 9
lappend res [r get mykey]
r select 10
r flushdb
r select 9
format $res
} [list foobar hoge foobar]
test {COPY for string does not copy data to no-integer DB} {
r set mykey foobar
catch {r copy mykey mynewkey DB notanumber} e
set e
} {ERR value is not an integer or out of range}
test {COPY can copy key expire metadata as well} {
r set mykey foobar ex 100
r copy mykey mynewkey REPLACE
assert {[r ttl mynewkey] > 0 && [r ttl mynewkey] <= 100}
assert {[r get mynewkey] eq "foobar"}
}
test {COPY does not create an expire if it does not exist} {
r set mykey foobar
assert {[r ttl mykey] == -1}
r copy mykey mynewkey REPLACE
assert {[r ttl mynewkey] == -1}
assert {[r get mynewkey] eq "foobar"}
}
test {COPY basic usage for list} {
r del mylist mynewlist
r lpush mylist a b c d
r copy mylist mynewlist
set digest [r debug digest-value mylist]
assert_equal $digest [r debug digest-value mynewlist]
assert_equal 1 [r object refcount mylist]
assert_equal 1 [r object refcount mynewlist]
r del mylist
assert_equal $digest [r debug digest-value mynewlist]
}
test {COPY basic usage for intset set} {
r del set1 newset1
r sadd set1 1 2 3
assert_encoding intset set1
r copy set1 newset1
set digest [r debug digest-value set1]
assert_equal $digest [r debug digest-value newset1]
assert_equal 1 [r object refcount set1]
assert_equal 1 [r object refcount newset1]
r del set1
assert_equal $digest [r debug digest-value newset1]
}
test {COPY basic usage for hashtable set} {
r del set2 newset2
r sadd set2 1 2 3 a
assert_encoding hashtable set2
r copy set2 newset2
set digest [r debug digest-value set2]
assert_equal $digest [r debug digest-value newset2]
assert_equal 1 [r object refcount set2]
assert_equal 1 [r object refcount newset2]
r del set2
assert_equal $digest [r debug digest-value newset2]
}
test {COPY basic usage for ziplist sorted set} {
r del zset1 newzset1
r zadd zset1 123 foobar
assert_encoding ziplist zset1
r copy zset1 newzset1
set digest [r debug digest-value zset1]
assert_equal $digest [r debug digest-value newzset1]
assert_equal 1 [r object refcount zset1]
assert_equal 1 [r object refcount newzset1]
r del zset1
assert_equal $digest [r debug digest-value newzset1]
}
test {COPY basic usage for skiplist sorted set} {
r del zset2 newzset2
set original_max [lindex [r config get zset-max-ziplist-entries] 1]
r config set zset-max-ziplist-entries 0
for {set j 0} {$j < 130} {incr j} {
r zadd zset2 [randomInt 50] ele-[randomInt 10]
}
assert_encoding skiplist zset2
r copy zset2 newzset2
set digest [r debug digest-value zset2]
assert_equal $digest [r debug digest-value newzset2]
assert_equal 1 [r object refcount zset2]
assert_equal 1 [r object refcount newzset2]
r del zset2
assert_equal $digest [r debug digest-value newzset2]
r config set zset-max-ziplist-entries $original_max
}
test {COPY basic usage for ziplist hash} {
r del hash1 newhash1
r hset hash1 tmp 17179869184
assert_encoding ziplist hash1
r copy hash1 newhash1
set digest [r debug digest-value hash1]
assert_equal $digest [r debug digest-value newhash1]
assert_equal 1 [r object refcount hash1]
assert_equal 1 [r object refcount newhash1]
r del hash1
assert_equal $digest [r debug digest-value newhash1]
}
test {COPY basic usage for hashtable hash} {
r del hash2 newhash2
set original_max [lindex [r config get hash-max-ziplist-entries] 1]
r config set hash-max-ziplist-entries 0
for {set i 0} {$i < 64} {incr i} {
r hset hash2 [randomValue] [randomValue]
}
assert_encoding hashtable hash2
r copy hash2 newhash2
set digest [r debug digest-value hash2]
assert_equal $digest [r debug digest-value newhash2]
assert_equal 1 [r object refcount hash2]
assert_equal 1 [r object refcount newhash2]
r del hash2
assert_equal $digest [r debug digest-value newhash2]
r config set hash-max-ziplist-entries $original_max
}
test {COPY basic usage for stream} {
r del mystream mynewstream
for {set i 0} {$i < 1000} {incr i} {
r XADD mystream * item 2 value b
}
r copy mystream mynewstream
set digest [r debug digest-value mystream]
assert_equal $digest [r debug digest-value mynewstream]
assert_equal 1 [r object refcount mystream]
assert_equal 1 [r object refcount mynewstream]
r del mystream
assert_equal $digest [r debug digest-value mynewstream]
}
test {COPY basic usage for stream-cgroups} {
r del x
r XADD x 100 a 1
set id [r XADD x 101 b 1]
r XADD x 102 c 1
r XADD x 103 e 1
r XADD x 104 f 1
r XADD x 105 g 1
r XGROUP CREATE x g1 0
r XGROUP CREATE x g2 0
r XREADGROUP GROUP g1 Alice COUNT 1 STREAMS x >
r XREADGROUP GROUP g1 Bob COUNT 1 STREAMS x >
r XREADGROUP GROUP g1 Bob NOACK COUNT 1 STREAMS x >
r XREADGROUP GROUP g2 Charlie COUNT 4 STREAMS x >
r XGROUP SETID x g1 $id
r XREADGROUP GROUP g1 Dave COUNT 3 STREAMS x >
r XDEL x 103
r copy x newx
set info [r xinfo stream x full]
assert_equal $info [r xinfo stream newx full]
assert_equal 1 [r object refcount x]
assert_equal 1 [r object refcount newx]
r del x
assert_equal $info [r xinfo stream newx full]
r flushdb
}
test {MOVE basic usage} {
r set mykey foobar
r move mykey 10
@@ -191,7 +398,7 @@ start_server {tags {"keyspace"}} {
r set mykey hello
catch {r move mykey notanumber} e
set e
} {*ERR*index out of range}
} {ERR value is not an integer or out of range}
test {MOVE can move key expire metadata as well} {
r select 10
+1 -1
View File
@@ -1,4 +1,4 @@
start_server {tags {"limits"} overrides {maxclients 10}} {
start_server {tags {"limits network"} overrides {maxclients 10}} {
if {$::tls} {
set expected_code "*I/O error*"
} else {
+22 -1
View File
@@ -246,10 +246,31 @@ test_slave_buffers {slave buffer are counted correctly} 1000000 10 0 1
# test again with fewer (and bigger) commands without pipeline, but with eviction
test_slave_buffers "replica buffer don't induce eviction" 100000 100 1 0
start_server {tags {"maxmemory"} overrides {server-threads 1}} {
test {Don't rehash if used memory exceeds maxmemory after rehash} {
r config set maxmemory 0
r config set maxmemory-policy allkeys-random
# Next rehash size is 8192, that will eat 64k memory
populate 4096 "" 1
set used [s used_memory]
set limit [expr {$used + 10*1024}]
r config set maxmemory $limit
r set k1 v1
# Next writing command will trigger evicting some keys if last
# command trigger DB dict rehash
r set k2 v2
# There must be 4098 keys because redis doesn't evict keys.
r dbsize
} {4098}
}
start_server {tags {"maxmemory"} overrides {server-threads 1}} {
test {client tracking don't cause eviction feedback loop} {
r config set maxmemory 0
r config set maxmemory-policy allkeys-lru
r config set maxmemory-eviction-tenacity 100
# 10 clients listening on tracking messages
set clients {}
@@ -308,4 +329,4 @@ start_server {tags {"maxmemory"} overrides {server-threads 1}} {
if {$::verbose} { puts "evicted: $evicted" }
}
}
}; #run_solo
}
+55 -105
View File
@@ -37,10 +37,9 @@ start_server {tags {"memefficiency"}} {
}
run_solo {defrag} {
start_server {tags {"defrag"} overrides {server-threads 1} } {
if {[string match {*jemalloc*} [s mem_allocator]]} {
start_server {tags {"defrag"} overrides {appendonly yes auto-aof-rewrite-percentage 0 save "" server-threads 1}} {
if {[string match {*jemalloc*} [s mem_allocator]] && [r debug mallctl arenas.page] <= 8192} {
test "Active defrag" {
r config set save "" ;# prevent bgsave from interfereing with save below
r config set hz 100
r config set activedefrag no
r config set active-defrag-threshold-lower 5
@@ -49,9 +48,9 @@ start_server {tags {"defrag"} overrides {server-threads 1} } {
r config set active-defrag-ignore-bytes 2mb
r config set maxmemory 100mb
r config set maxmemory-policy allkeys-lru
r debug populate 700000 asdf1 150
r debug populate 170000 asdf2 300
r ping ;# trigger eviction following the previous population
populate 700000 asdf1 150
populate 170000 asdf2 300
after 120 ;# serverCron only updates the info once in 100ms
set frag [s allocator_frag_ratio]
if {$::verbose} {
@@ -64,7 +63,7 @@ start_server {tags {"defrag"} overrides {server-threads 1} } {
r config set maxmemory 110mb ;# prevent further eviction (not to fail the digest test)
set digest [r debug digest]
catch {r config set activedefrag yes} e
if {![string match {DISABLED*} $e]} {
if {[r config get activedefrag] eq "activedefrag yes"} {
# Wait for the active defrag to start working (decision once a
# second).
wait_for_condition 50 100 {
@@ -109,19 +108,59 @@ start_server {tags {"defrag"} overrides {server-threads 1} } {
if {!$::no_latency} {
assert {$max_latency <= 30}
}
} else {
set _ ""
}
# verify the data isn't corrupted or changed
set newdigest [r debug digest]
assert {$digest eq $newdigest}
r save ;# saving an rdb iterates over all the data / pointers
} {OK}
# if defrag is supported, test AOF loading too
if {[r config get activedefrag] eq "activedefrag yes"} {
# reset stats and load the AOF file
r config resetstat
r config set key-load-delay -50 ;# sleep on average 1/50 usec
r debug loadaof
r config set activedefrag no
# measure hits and misses right after aof loading
set misses [s active_defrag_misses]
set hits [s active_defrag_hits]
after 120 ;# serverCron only updates the info once in 100ms
set frag [s allocator_frag_ratio]
set max_latency 0
foreach event [r latency latest] {
lassign $event eventname time latency max
if {$eventname == "loading-cron"} {
set max_latency $max
}
}
if {$::verbose} {
puts "AOF loading:"
puts "frag $frag"
puts "hits: $hits"
puts "misses: $misses"
puts "max latency $max_latency"
puts [r latency latest]
puts [r latency history loading-cron]
}
# make sure we had defrag hits during AOF loading
assert {$hits > 100000}
# make sure the defragger did enough work to keep the fragmentation low during loading.
# we cannot check that it went all the way down, since we don't wait for full defrag cycle to complete.
assert {$frag < 1.4}
# since the AOF contains simple (fast) SET commands (and the cron during loading runs every 1000 commands),
# it'll still not block the loading for long periods of time.
if {!$::no_latency} {
assert {$max_latency <= 30}
}
}
}
r config set appendonly no
r config set key-load-delay 0
test "Active defrag big keys" {
r flushdb
r config resetstat
r config set save "" ;# prevent bgsave from interfereing with save below
r config set hz 100
r config set activedefrag no
r config set active-defrag-max-scan-fields 1000
@@ -197,7 +236,7 @@ start_server {tags {"defrag"} overrides {server-threads 1} } {
set digest [r debug digest]
catch {r config set activedefrag yes} e
if {![string match {DISABLED*} $e]} {
if {[r config get activedefrag] eq "activedefrag yes"} {
# wait for the active defrag to start working (decision once a second)
wait_for_condition 50 100 {
[s active_defrag_running] ne 0
@@ -251,7 +290,6 @@ start_server {tags {"defrag"} overrides {server-threads 1} } {
test "Active defrag big list" {
r flushdb
r config resetstat
r config set save "" ;# prevent bgsave from interfereing with save below
r config set hz 100
r config set activedefrag no
r config set active-defrag-max-scan-fields 1000
@@ -294,7 +332,7 @@ start_server {tags {"defrag"} overrides {server-threads 1} } {
set digest [r debug digest]
catch {r config set activedefrag yes} e
if {![string match {DISABLED*} $e]} {
if {[r config get activedefrag] eq "activedefrag yes"} {
# wait for the active defrag to start working (decision once a second)
wait_for_condition 50 100 {
[s active_defrag_running] ne 0
@@ -357,10 +395,9 @@ start_server {tags {"defrag"} overrides {server-threads 1} } {
# if the current slab is lower in utilization the defragger would have ended up in stagnation,
# keept running and not move any allocation.
# this test is more consistent on a fresh server with no history
start_server {tags {"defrag"} overrides {server-threads 1}} {
start_server {tags {"defrag"} overrides {save ""}} {
r flushdb
r config resetstat
r config set save "" ;# prevent bgsave from interfereing with save below
r config set hz 100
r config set activedefrag no
r config set active-defrag-max-scan-fields 1000
@@ -415,7 +452,7 @@ start_server {tags {"defrag"} overrides {server-threads 1} } {
set digest [r debug digest]
catch {r config set activedefrag yes} e
if {![string match {DISABLED*} $e]} {
if {[r config get activedefrag] eq "activedefrag yes"} {
# wait for the active defrag to start working (decision once a second)
wait_for_condition 50 100 {
[s active_defrag_running] ne 0
@@ -456,91 +493,4 @@ start_server {tags {"defrag"} overrides {server-threads 1} } {
}
}
}
start_server {tags {"defrag"} overrides {server-threads 1 active-replica yes} } { ;#test defrag with active-replica enabled
if {[string match {*jemalloc*} [s mem_allocator]]} {
test "Active defrag with active replica" {
r config set save "" ;# prevent bgsave from interfereing with save below
r config set hz 100
r config set activedefrag no
r config set active-defrag-threshold-lower 5
r config set active-defrag-cycle-min 65
r config set active-defrag-cycle-max 75
r config set active-defrag-ignore-bytes 2mb
r config set maxmemory 100mb
r config set maxmemory-policy allkeys-lru
r debug populate 700000 asdf1 150
r debug populate 170000 asdf2 300
r ping ;# trigger eviction following the previous population
after 120 ;# serverCron only updates the info once in 100ms
set frag [s allocator_frag_ratio]
if {$::verbose} {
puts "frag $frag"
}
assert {$frag >= 1.4}
r config set latency-monitor-threshold 5
r latency reset
r config set maxmemory 110mb ;# prevent further eviction (not to fail the digest test)
set digest [r debug digest]
catch {r config set activedefrag yes} e
if {![string match {DISABLED*} $e]} {
# Wait for the active defrag to start working (decision once a
# second).
wait_for_condition 50 100 {
[s active_defrag_running] ne 0
} else {
fail "defrag not started."
}
# Wait for the active defrag to stop working.
catch {
wait_for_condition 150 100 {
[s active_defrag_running] eq 0
} else {
after 120 ;# serverCron only updates the info once in 100ms
puts [r info memory]
puts [r memory malloc-stats]
fail "defrag didn't stop."
}
} e
if {[string match *error* $e]} {
after 120
fail "defrag accessed invalid address."
}
# Test the the fragmentation is lower.
after 120 ;# serverCron only updates the info once in 100ms
set frag [s allocator_frag_ratio]
set max_latency 0
foreach event [r latency latest] {
lassign $event eventname time latency max
if {$eventname == "active-defrag-cycle"} {
set max_latency $max
}
}
if {$::verbose} {
puts "frag $frag"
set misses [s active_defrag_misses]
set hits [s active_defrag_hits]
puts "hits: $hits"
puts "misses: $misses"
puts "max latency $max_latency"
puts [r latency latest]
puts [r latency history active-defrag-cycle]
}
assert {$frag < 1.1}
# due to high fragmentation, 100hz, and active-defrag-cycle-max set to 75,
# we expect max latency to be not much higher than 7.5ms but due to rare slowness threshold is set higher
assert {$max_latency <= 30}
} else {
set _ ""
}
# verify the data isn't corrupted or changed
set newdigest [r debug digest]
assert {$digest eq $newdigest}
r save ;# saving an rdb iterates over all the data / pointers
} {OK}
}
}
} ;# run solo
} ;# run_solo
+63
View File
@@ -15,6 +15,69 @@ start_server {tags {"modules"}} {
assert_equal {{Blocked client is not supported inside multi}} [r exec]
}
test {Locked GIL acquisition from RM_Call} {
assert_equal {Blocked client is not allowed} [r do_rm_call acquire_gil]
}
test {Blocking command are not block the client on RM_Call} {
r lpush l test
assert_equal [r do_rm_call blpop l 0] {l test}
r lpush l test
assert_equal [r do_rm_call brpop l 0] {l test}
r lpush l1 test
assert_equal [r do_rm_call brpoplpush l1 l2 0] {test}
assert_equal [r do_rm_call brpop l2 0] {l2 test}
r lpush l1 test
assert_equal [r do_rm_call blmove l1 l2 LEFT LEFT 0] {test}
assert_equal [r do_rm_call brpop l2 0] {l2 test}
r ZADD zset1 0 a 1 b 2 c
assert_equal [r do_rm_call bzpopmin zset1 0] {zset1 a 0}
assert_equal [r do_rm_call bzpopmax zset1 0] {zset1 c 2}
r xgroup create s g $ MKSTREAM
r xadd s * foo bar
assert {[r do_rm_call xread BLOCK 0 STREAMS s 0-0] ne {}}
assert {[r do_rm_call xreadgroup group g c BLOCK 0 STREAMS s >] ne {}}
assert {[r do_rm_call blpop empty_list 0] eq {}}
assert {[r do_rm_call brpop empty_list 0] eq {}}
assert {[r do_rm_call brpoplpush empty_list1 empty_list2 0] eq {}}
assert {[r do_rm_call blmove empty_list1 empty_list2 LEFT LEFT 0] eq {}}
assert {[r do_rm_call bzpopmin empty_zset 0] eq {}}
assert {[r do_rm_call bzpopmax empty_zset 0] eq {}}
r xgroup create empty_stream g $ MKSTREAM
assert {[r do_rm_call xread BLOCK 0 STREAMS empty_stream $] eq {}}
assert {[r do_rm_call xreadgroup group g c BLOCK 0 STREAMS empty_stream >] eq {}}
}
test {Monitor disallow inside RM_Call} {
set e {}
catch {
r do_rm_call monitor
} e
set e
} {*ERR*DENY BLOCKING*}
test {subscribe disallow inside RM_Call} {
set e {}
catch {
r do_rm_call subscribe x
} e
set e
} {*ERR*DENY BLOCKING*}
test {RM_Call from blocked client} {
r hset hash foo bar
r do_bg_rm_call hgetall hash
} {foo bar}
test {blocked client reaches client output buffer limit} {
r hset hash big [string repeat x 50000]
r hset hash bada [string repeat x 50000]
@@ -0,0 +1,88 @@
set testmodule [file normalize tests/modules/blockonbackground.so]
source tests/support/util.tcl
start_server {tags {"modules"}} {
r module load $testmodule
test { blocked clients time tracking - check blocked command that uses RedisModule_BlockedClientMeasureTimeStart() is tracking background time} {
r slowlog reset
r config set slowlog-log-slower-than 200000
if {!$::no_latency} {
assert_equal [r slowlog len] 0
}
r block.debug 0 10000
if {!$::no_latency} {
assert_equal [r slowlog len] 0
}
r config resetstat
r block.debug 200 10000
if {!$::no_latency} {
assert_equal [r slowlog len] 1
}
set cmdstatline [cmdrstat block.debug r]
regexp "calls=1,usec=(.*?),usec_per_call=(.*?),rejected_calls=0,failed_calls=0" $cmdstatline usec usec_per_call
assert {$usec >= 100000}
assert {$usec_per_call >= 100000}
}
test { blocked clients time tracking - check blocked command that uses RedisModule_BlockedClientMeasureTimeStart() is tracking background time even in timeout } {
r slowlog reset
r config set slowlog-log-slower-than 200000
if {!$::no_latency} {
assert_equal [r slowlog len] 0
}
r block.debug 0 20000
if {!$::no_latency} {
assert_equal [r slowlog len] 0
}
r config resetstat
r block.debug 20000 500
if {!$::no_latency} {
assert_equal [r slowlog len] 1
}
set cmdstatline [cmdrstat block.debug r]
regexp "calls=1,usec=(.*?),usec_per_call=(.*?),rejected_calls=0,failed_calls=0" $cmdstatline usec usec_per_call
assert {$usec >= 250000}
assert {$usec_per_call >= 250000}
}
test { blocked clients time tracking - check blocked command with multiple calls RedisModule_BlockedClientMeasureTimeStart() is tracking the total background time } {
r slowlog reset
r config set slowlog-log-slower-than 200000
if {!$::no_latency} {
assert_equal [r slowlog len] 0
}
r block.double_debug 0
if {!$::no_latency} {
assert_equal [r slowlog len] 0
}
r config resetstat
r block.double_debug 100
if {!$::no_latency} {
assert_equal [r slowlog len] 1
}
set cmdstatline [cmdrstat block.double_debug r]
regexp "calls=1,usec=(.*?),usec_per_call=(.*?),rejected_calls=0,failed_calls=0" $cmdstatline usec usec_per_call
assert {$usec >= 60000}
assert {$usec_per_call >= 60000}
}
test { blocked clients time tracking - check blocked command without calling RedisModule_BlockedClientMeasureTimeStart() is not reporting background time } {
r slowlog reset
r config set slowlog-log-slower-than 200000
if {!$::no_latency} {
assert_equal [r slowlog len] 0
}
r block.debug_no_track 200 1000
# ensure slowlog is still empty
if {!$::no_latency} {
assert_equal [r slowlog len] 0
}
}
}
+52 -1
View File
@@ -168,7 +168,7 @@ start_server {tags {"modules"}} {
assert_error "*unblocked*" {$rd read}
}
test {Module client blocked on keys does not wake up on wrong type} {
test {Module client re-blocked on keys after woke up on wrong type} {
r del k
set rd [redis_deferring_client]
$rd fsl.bpop k 0
@@ -184,5 +184,56 @@ start_server {tags {"modules"}} {
r del k
r fsl.push k 34
assert_equal {34} [$rd read]
assert_equal {1} [r get fsl_wrong_type] ;# first lpush caused one wrong-type wake-up
}
test {Module client blocked on keys woken up by LPUSH} {
r del k
set rd [redis_deferring_client]
$rd blockonkeys.popall k
# wait until client is actually blocked
wait_for_condition 50 100 {
[s 0 blocked_clients] eq {1}
} else {
fail "Client is not blocked"
}
r lpush k 42 squirrel banana
assert_equal {banana squirrel 42} [$rd read]
$rd close
}
test {Module client unblocks BLPOP} {
r del k
set rd [redis_deferring_client]
$rd blpop k 3
# wait until client is actually blocked
wait_for_condition 50 100 {
[s 0 blocked_clients] eq {1}
} else {
fail "Client is not blocked"
}
r blockonkeys.lpush k 42
assert_equal {k 42} [$rd read]
$rd close
}
test {Module unblocks module blocked on non-empty list} {
r del k
r lpush k aa
# Module client blocks to pop 5 elements from list
set rd [redis_deferring_client]
$rd blockonkeys.blpopn k 5
# Wait until client is actually blocked
wait_for_condition 50 100 {
[s 0 blocked_clients] eq {1}
} else {
fail "Client is not blocked"
}
# Check that RM_SignalKeyAsReady() can wake up BLPOPN
r blockonkeys.lpush_unblock k bb cc ;# Not enough elements for BLPOPN
r lpush k dd ee ff ;# Doesn't unblock module
r blockonkeys.lpush_unblock k gg ;# Unblocks module
assert_equal {gg ff ee dd cc} [$rd read]
$rd close
}
}
+14
View File
@@ -41,4 +41,18 @@ start_server {tags {"modules"}} {
catch {r datatype.swap key-a key-b} e
set e
} {*ERR*}
test {DataType: Copy command works for modules} {
# Test failed copies
r datatype.set answer-to-universe 42 AAA
catch {r copy answer-to-universe answer2} e
assert_match {*module key failed to copy*} $e
# Our module's data type copy function copies the int value as-is
# but appends /<from-key>/<to-key> to the string value so we can
# track passed arguments.
r datatype.set sourcekey 1234 AAA
r copy sourcekey targetkey
r datatype.get targetkey
} {1234 AAA/sourcekey/targetkey}
}
+46
View File
@@ -0,0 +1,46 @@
set testmodule [file normalize tests/modules/defragtest.so]
start_server {tags {"modules"} overrides {{save ""}}} {
r module load $testmodule 10000
r config set hz 100
r config set active-defrag-ignore-bytes 1
r config set active-defrag-threshold-lower 0
r config set active-defrag-cycle-min 99
# try to enable active defrag, it will fail if redis was compiled without it
catch {r config set activedefrag yes} e
if {[r config get activedefrag] eq "activedefrag yes"} {
test {Module defrag: simple key defrag works} {
r frag.create key1 1 1000 0
after 2000
set info [r info defragtest_stats]
assert {[getInfoProperty $info defragtest_datatype_attempts] > 0}
assert_equal 0 [getInfoProperty $info defragtest_datatype_resumes]
}
test {Module defrag: late defrag with cursor works} {
r flushdb
r frag.resetstats
# key can only be defragged in no less than 10 iterations
# due to maxstep
r frag.create key2 10000 100 1000
after 2000
set info [r info defragtest_stats]
assert {[getInfoProperty $info defragtest_datatype_resumes] > 10}
assert_equal 0 [getInfoProperty $info defragtest_datatype_wrong_cursor]
}
test {Module defrag: global defrag works} {
r flushdb
r frag.resetstats
after 2000
set info [r info defragtest_stats]
assert {[getInfoProperty $info defragtest_global_attempts] > 0}
}
}
}
+23
View File
@@ -0,0 +1,23 @@
set testmodule [file normalize tests/modules/hash.so]
start_server {tags {"modules"}} {
r module load $testmodule
test {Module hash set} {
r set k mystring
assert_error "WRONGTYPE*" {r hash.set k "" hello world}
r del k
# "" = count updates and deletes of existing fields only
assert_equal 0 [r hash.set k "" squirrel yes]
# "a" = COUNT_ALL = count inserted, modified and deleted fields
assert_equal 2 [r hash.set k "a" banana no sushi whynot]
# "n" = NX = only add fields not already existing in the hash
# "x" = XX = only replace the value for existing fields
assert_equal 0 [r hash.set k "n" squirrel hoho what nothing]
assert_equal 1 [r hash.set k "na" squirrel hoho something nice]
assert_equal 0 [r hash.set k "xa" new stuff not inserted]
assert_equal 1 [r hash.set k "x" squirrel ofcourse]
assert_equal 1 [r hash.set k "" sushi :delete: none :delete:]
r hgetall k
} {squirrel ofcourse banana no what nothing something nice}
}
+5
View File
@@ -85,5 +85,10 @@ start_server {tags {"modules"}} {
set keys [scan [regexp -inline {keys\=([\d]*)} $keyspace] keys=%d]
} {3}
test {module info unsafe fields} {
set info [r info infotest_unsafe]
assert_match {*infotest_unsafe_field:value=1*} $info
}
# TODO: test crash report.
}
+50 -1
View File
@@ -18,5 +18,54 @@ tags "modules" {
assert_equal {1 t} [r keyspace.is_key_loaded t]
assert_equal {1 s} [r keyspace.is_key_loaded s]
}
test {Nested multi due to RM_Call} {
r del multi
r del lua
r set x 1
r set x_copy 1
r keyspace.del_key_copy x
r keyspace.incr_case1 x
r keyspace.incr_case2 x
r keyspace.incr_case3 x
assert_equal {} [r get multi]
assert_equal {} [r get lua]
r get x
} {3}
test {Nested multi due to RM_Call, with client MULTI} {
r del multi
r del lua
r set x 1
r set x_copy 1
r multi
r keyspace.del_key_copy x
r keyspace.incr_case1 x
r keyspace.incr_case2 x
r keyspace.incr_case3 x
r exec
assert_equal {1} [r get multi]
assert_equal {} [r get lua]
r get x
} {3}
test {Nested multi due to RM_Call, with EVAL} {
r del multi
r del lua
r set x 1
r set x_copy 1
r eval {
redis.pcall('keyspace.del_key_copy', KEYS[1])
redis.pcall('keyspace.incr_case1', KEYS[1])
redis.pcall('keyspace.incr_case2', KEYS[1])
redis.pcall('keyspace.incr_case3', KEYS[1])
} 1 x
assert_equal {} [r get multi]
assert_equal {1} [r get lua]
r get x
} {3}
}
}
}
+9
View File
@@ -16,6 +16,11 @@ start_server {tags {"modules"}} {
assert { [string match "*cmdstat_module*" $info] }
}
test {test RM_Call recursive} {
set info [r test.call_generic test.call_generic info commandstats]
assert { [string match "*cmdstat_module*" $info] }
}
test {test redis version} {
set version [s redis_version]
assert_equal $version [r test.redisversion]
@@ -106,4 +111,8 @@ start_server {tags {"modules"}} {
r test.log_tsctx "info" "Test message"
verify_log_message 0 "*<misc> Test message*" 0
}
test {test RM_Call CLIENT INFO} {
assert_match "*fd=-1*" [r test.call_generic client info]
}
}
+96 -18
View File
@@ -14,25 +14,103 @@ tags "modules" {
# Start the replication process...
$replica replicaof $master_host $master_port
wait_for_sync $replica
after 1000
$master propagate-test
wait_for_condition 5000 10 {
([$replica get timer] eq "10") && \
([$replica get a-from-thread] eq "10")
} else {
fail "The two counters don't match the expected value."
test {module propagates from timer} {
set repl [attach_to_replication_stream]
$master propagate-test.timer
wait_for_condition 5000 10 {
[$replica get timer] eq "3"
} else {
fail "The two counters don't match the expected value."
}
assert_replication_stream $repl {
{select *}
{multi}
{incr timer}
{exec}
{multi}
{incr timer}
{exec}
{multi}
{incr timer}
{exec}
}
close_replication_stream $repl
}
$master propagate-test-2
$master propagate-test-3
$master multi
$master propagate-test-2
$master propagate-test-3
$master exec
wait_for_ofs_sync $master $replica
test {module propagates from thread} {
set repl [attach_to_replication_stream]
$master propagate-test.thread
wait_for_condition 5000 10 {
[$replica get a-from-thread] eq "3"
} else {
fail "The two counters don't match the expected value."
}
assert_replication_stream $repl {
{select *}
{incr a-from-thread}
{incr b-from-thread}
{incr a-from-thread}
{incr b-from-thread}
{incr a-from-thread}
{incr b-from-thread}
}
close_replication_stream $repl
}
test {module propagates from from command} {
set repl [attach_to_replication_stream]
$master propagate-test.simple
$master propagate-test.mixed
# Note the 'after-call' propagation below is out of order (known limitation)
assert_replication_stream $repl {
{select *}
{multi}
{incr counter-1}
{incr counter-2}
{exec}
{multi}
{incr using-call}
{incr after-call}
{incr counter-1}
{incr counter-2}
{exec}
}
close_replication_stream $repl
}
test {module propagates from from multi-exec} {
set repl [attach_to_replication_stream]
$master multi
$master propagate-test.simple
$master propagate-test.mixed
$master exec
wait_for_ofs_sync $master $replica
# Note the 'after-call' propagation below is out of order (known limitation)
assert_replication_stream $repl {
{select *}
{multi}
{incr counter-1}
{incr counter-2}
{incr using-call}
{incr after-call}
{incr counter-1}
{incr counter-2}
{exec}
}
close_replication_stream $repl
}
assert_equal [s -1 unexpected_error_replies] 0
}
}
@@ -47,11 +125,11 @@ tags "modules aof" {
r config set auto-aof-rewrite-percentage 0 ; # Disable auto-rewrite.
waitForBgrewriteaof r
r propagate-test-2
r propagate-test-3
r propagate-test.simple
r propagate-test.mixed
r multi
r propagate-test-2
r propagate-test-3
r propagate-test.simple
r propagate-test.mixed
r exec
# Load the AOF
+155
View File
@@ -0,0 +1,155 @@
set testmodule [file normalize tests/modules/stream.so]
start_server {tags {"modules"}} {
r module load $testmodule
test {Module stream add and delete} {
r del mystream
# add to empty key
set streamid1 [r stream.add mystream item 1 value a]
# add to existing stream
set streamid2 [r stream.add mystream item 2 value b]
# check result
assert { [string match "*-*" $streamid1] }
set items [r XRANGE mystream - +]
assert_equal $items \
"{$streamid1 {item 1 value a}} {$streamid2 {item 2 value b}}"
# delete one of them and try deleting non-existing ID
assert_equal OK [r stream.delete mystream $streamid1]
assert_error "ERR StreamDelete*" {r stream.delete mystream 123-456}
assert_error "Invalid stream ID*" {r stream.delete mystream foo}
assert_equal "{$streamid2 {item 2 value b}}" [r XRANGE mystream - +]
# check error condition: wrong type
r del mystream
r set mystream mystring
assert_error "ERR StreamAdd*" {r stream.add mystream item 1 value a}
assert_error "ERR StreamDelete*" {r stream.delete mystream 123-456}
}
test {Module stream add unblocks blocking xread} {
r del mystream
# Blocking XREAD on an empty key
set rd1 [redis_deferring_client]
$rd1 XREAD BLOCK 3000 STREAMS mystream $
# wait until client is actually blocked
wait_for_condition 50 100 {
[s 0 blocked_clients] eq {1}
} else {
fail "Client is not blocked"
}
set id [r stream.add mystream field 1 value a]
assert_equal "{mystream {{$id {field 1 value a}}}}" [$rd1 read]
# Blocking XREAD on an existing stream
set rd2 [redis_deferring_client]
$rd2 XREAD BLOCK 3000 STREAMS mystream $
# wait until client is actually blocked
wait_for_condition 50 100 {
[s 0 blocked_clients] eq {1}
} else {
fail "Client is not blocked"
}
set id [r stream.add mystream field 2 value b]
assert_equal "{mystream {{$id {field 2 value b}}}}" [$rd2 read]
}
test {Module stream add benchmark (1M stream add)} {
set n 1000000
r del mystream
set result [r stream.addn mystream $n field value]
assert_equal $result $n
}
test {Module stream iterator} {
r del mystream
set streamid1 [r xadd mystream * item 1 value a]
set streamid2 [r xadd mystream * item 2 value b]
# range result
set result1 [r stream.range mystream "-" "+"]
set expect1 [r xrange mystream "-" "+"]
assert_equal $result1 $expect1
# reverse range
set result_rev [r stream.range mystream "+" "-"]
set expect_rev [r xrevrange mystream "+" "-"]
assert_equal $result_rev $expect_rev
# only one item: range with startid = endid
set result2 [r stream.range mystream "-" $streamid1]
assert_equal $result2 "{$streamid1 {item 1 value a}}"
assert_equal $result2 [list [list $streamid1 {item 1 value a}]]
# only one item: range with startid = endid
set result3 [r stream.range mystream $streamid2 $streamid2]
assert_equal $result3 "{$streamid2 {item 2 value b}}"
assert_equal $result3 [list [list $streamid2 {item 2 value b}]]
}
test {Module stream iterator delete} {
r del mystream
set id1 [r xadd mystream * normal item]
set id2 [r xadd mystream * selfdestruct yes]
set id3 [r xadd mystream * another item]
# stream.range deletes the "selfdestruct" item after returning it
assert_equal \
"{$id1 {normal item}} {$id2 {selfdestruct yes}} {$id3 {another item}}" \
[r stream.range mystream - +]
# now, the "selfdestruct" item is gone
assert_equal \
"{$id1 {normal item}} {$id3 {another item}}" \
[r stream.range mystream - +]
}
test {Module stream trim by length} {
r del mystream
# exact maxlen
r xadd mystream * item 1 value a
r xadd mystream * item 2 value b
r xadd mystream * item 3 value c
assert_equal 3 [r xlen mystream]
assert_equal 0 [r stream.trim mystream maxlen = 5]
assert_equal 3 [r xlen mystream]
assert_equal 2 [r stream.trim mystream maxlen = 1]
assert_equal 1 [r xlen mystream]
assert_equal 1 [r stream.trim mystream maxlen = 0]
# check that there is no limit for exact maxlen
r stream.addn mystream 20000 item x value y
assert_equal 20000 [r stream.trim mystream maxlen = 0]
# approx maxlen (100 items per node implies default limit 10K items)
r stream.addn mystream 20000 item x value y
assert_equal 20000 [r xlen mystream]
assert_equal 10000 [r stream.trim mystream maxlen ~ 2]
assert_equal 9900 [r stream.trim mystream maxlen ~ 2]
assert_equal 0 [r stream.trim mystream maxlen ~ 2]
assert_equal 100 [r xlen mystream]
assert_equal 100 [r stream.trim mystream maxlen ~ 0]
assert_equal 0 [r xlen mystream]
}
test {Module stream trim by ID} {
r del mystream
# exact minid
r xadd mystream * item 1 value a
r xadd mystream * item 2 value b
set minid [r xadd mystream * item 3 value c]
assert_equal 3 [r xlen mystream]
assert_equal 0 [r stream.trim mystream minid = -]
assert_equal 3 [r xlen mystream]
assert_equal 2 [r stream.trim mystream minid = $minid]
assert_equal 1 [r xlen mystream]
assert_equal 1 [r stream.trim mystream minid = +]
# check that there is no limit for exact minid
r stream.addn mystream 20000 item x value y
assert_equal 20000 [r stream.trim mystream minid = +]
# approx minid (100 items per node implies default limit 10K items)
r stream.addn mystream 19980 item x value y
set minid [r xadd mystream * item x value y]
r stream.addn mystream 19 item x value y
assert_equal 20000 [r xlen mystream]
assert_equal 10000 [r stream.trim mystream minid ~ $minid]
assert_equal 9900 [r stream.trim mystream minid ~ $minid]
assert_equal 0 [r stream.trim mystream minid ~ $minid]
assert_equal 100 [r xlen mystream]
assert_equal 100 [r stream.trim mystream minid ~ +]
assert_equal 0 [r xlen mystream]
}
}
+32
View File
@@ -0,0 +1,32 @@
set testmodule [file normalize tests/modules/test_lazyfree.so]
start_server {tags {"modules"}} {
r module load $testmodule
test "modules allocated memory can be reclaimed in the background" {
set orig_mem [s used_memory]
set rd [redis_deferring_client]
# LAZYFREE_THRESHOLD is 64
for {set i 0} {$i < 10000} {incr i} {
$rd lazyfreelink.insert lazykey $i
}
for {set j 0} {$j < 10000} {incr j} {
$rd read
}
assert {[r lazyfreelink.len lazykey] == 10000}
set peak_mem [s used_memory]
assert {[r unlink lazykey] == 1}
assert {$peak_mem > $orig_mem+10000}
wait_for_condition 50 100 {
[s used_memory] < $peak_mem &&
[s used_memory] < $orig_mem*2 &&
[string match {*lazyfreed_objects:1*} [r info Memory]]
} else {
fail "Module memory is not reclaimed by UNLINK"
}
}
}
+19 -2
View File
@@ -62,18 +62,30 @@ tags "modules" {
$master config set repl-diskless-sync yes
$master config set rdbcompression no
$replica config set repl-diskless-load swapdb
$master config set hz 500
$replica config set hz 500
$master config set dynamic-hz no
$replica config set dynamic-hz no
set start [clock clicks -milliseconds]
for {set k 0} {$k < 30} {incr k} {
r testrdb.set.key key$k [string repeat A [expr {int(rand()*1000000)}]]
}
if {$::verbose} {
set end [clock clicks -milliseconds]
set duration [expr $end - $start]
puts "filling took $duration ms (TODO: use pipeline)"
set start [clock clicks -milliseconds]
}
# Start the replication process...
set loglines [count_log_lines -1]
$master config set repl-diskless-sync-delay 0
$replica replicaof $master_host $master_port
# kill the replication at various points
set attempts 3
if {$::accurate} { set attempts 10 }
set attempts 100
if {$::accurate} { set attempts 500 }
for {set i 0} {$i < $attempts} {incr i} {
# wait for the replica to start reading the rdb
# using the log file since the replica only responds to INFO once in 2mb
@@ -106,6 +118,11 @@ tags "modules" {
fail "Replica didn't disconnect"
}
}
if {$::verbose} {
set end [clock clicks -milliseconds]
set duration [expr $end - $start]
puts "test took $duration ms"
}
# enable fast shutdown
$master config set rdb-key-save-delay 0
}
+57
View File
@@ -0,0 +1,57 @@
set testmodule [file normalize tests/modules/timer.so]
start_server {tags {"modules"}} {
r module load $testmodule
test {RM_CreateTimer: a sequence of timers work} {
# We can't guarantee same-ms but we try using MULTI/EXEC
r multi
for {set i 0} {$i < 20} {incr i} {
r test.createtimer 10 timer-incr-key
}
r exec
after 500
assert_equal 20 [r get timer-incr-key]
}
test {RM_GetTimer: basic sanity} {
# Getting non-existing timer
assert_equal {} [r test.gettimer 0]
# Getting a real timer
set id [r test.createtimer 10000 timer-incr-key]
set info [r test.gettimer $id]
assert_equal "timer-incr-key" [lindex $info 0]
set remaining [lindex $info 1]
assert {$remaining < 10000 && $remaining > 1}
}
test {RM_StopTimer: basic sanity} {
r set "timer-incr-key" 0
set id [r test.createtimer 1000 timer-incr-key]
assert_equal 1 [r test.stoptimer $id]
# Wait to be sure timer doesn't execute
after 2000
assert_equal 0 [r get timer-incr-key]
# Stop non-existing timer
assert_equal 0 [r test.stoptimer $id]
}
test {Timer appears non-existing after it fires} {
r set "timer-incr-key" 0
set id [r test.createtimer 10 timer-incr-key]
# verify timer fired
after 500
assert_equal 1 [r get timer-incr-key]
# verify id does not exist
assert_equal {} [r test.gettimer $id]
}
}
+16
View File
@@ -0,0 +1,16 @@
set testmodule [file normalize tests/modules/zset.so]
start_server {tags {"modules"}} {
r module load $testmodule
test {Module zset rem} {
r del k
r zadd k 100 hello 200 world
assert_equal 1 [r zset.rem k hello]
assert_equal 0 [r zset.rem k hello]
assert_equal 1 [r exists k]
# Check that removing the last element deletes the key
assert_equal 1 [r zset.rem k world]
assert_equal 0 [r exists k]
}
}
+102 -2
View File
@@ -322,10 +322,14 @@ start_server {tags {"multi"}} {
r multi
r del foo
r exec
# add another command so that when we see it we know multi-exec wasn't
# propagated
r incr foo
assert_replication_stream $repl {
{select *}
{multi}
{exec}
{incr foo}
}
close_replication_stream $repl
}
@@ -527,4 +531,100 @@ start_server {tags {"multi"}} {
$r2 config set maxmemory 0
$r2 close
}
test {Blocking commands ignores the timeout} {
r xgroup create s g $ MKSTREAM
set m [r multi]
r blpop empty_list 0
r brpop empty_list 0
r brpoplpush empty_list1 empty_list2 0
r blmove empty_list1 empty_list2 LEFT LEFT 0
r bzpopmin empty_zset 0
r bzpopmax empty_zset 0
r xread BLOCK 0 STREAMS s $
r xreadgroup group g c BLOCK 0 STREAMS s >
set res [r exec]
list $m $res
} {OK {{} {} {} {} {} {} {} {}}}
test {MULTI propagation of PUBLISH} {
set repl [attach_to_replication_stream]
# make sure that PUBLISH inside MULTI is propagated in a transaction
r multi
r publish bla bla
r exec
assert_replication_stream $repl {
{select *}
{multi}
{publish bla bla}
{exec}
}
close_replication_stream $repl
}
test {MULTI propagation of SCRIPT LOAD} {
set repl [attach_to_replication_stream]
# make sure that SCRIPT LOAD inside MULTI is propagated in a transaction
r multi
r script load {redis.call('set', KEYS[1], 'foo')}
set res [r exec]
set sha [lindex $res 0]
assert_replication_stream $repl {
{select *}
{multi}
{script load *}
{exec}
}
close_replication_stream $repl
}
test {MULTI propagation of SCRIPT LOAD} {
set repl [attach_to_replication_stream]
# make sure that EVAL inside MULTI is propagated in a transaction
r config set lua-replicate-commands no
r multi
r eval {redis.call('set', KEYS[1], 'bar')} 1 bar
r exec
assert_replication_stream $repl {
{select *}
{multi}
{eval *}
{exec}
}
close_replication_stream $repl
}
tags {"stream"} {
test {MULTI propagation of XREADGROUP} {
# stream is a special case because it calls propagate() directly for XREADGROUP
set repl [attach_to_replication_stream]
r XADD mystream * foo bar
r XGROUP CREATE mystream mygroup 0
# make sure the XCALIM (propagated by XREADGROUP) is indeed inside MULTI/EXEC
r multi
r XREADGROUP GROUP mygroup consumer1 STREAMS mystream ">"
r exec
assert_replication_stream $repl {
{select *}
{xadd *}
{xgroup CREATE *}
{multi}
{xclaim *}
{exec}
}
close_replication_stream $repl
}
}
}
+36
View File
@@ -0,0 +1,36 @@
test {CONFIG SET port number} {
start_server {} {
if {$::tls} { set port_cfg tls-port} else { set port_cfg port }
# available port
set avail_port [find_available_port $::baseport $::portcount]
set rd [redis [srv 0 host] [srv 0 port] 0 $::tls]
$rd CONFIG SET $port_cfg $avail_port
$rd close
set rd [redis [srv 0 host] $avail_port 0 $::tls]
$rd PING
# already inuse port
catch {$rd CONFIG SET $port_cfg $::test_server_port} e
assert_match {*Unable to listen on this port*} $e
$rd close
# make sure server still listening on the previous port
set rd [redis [srv 0 host] $avail_port 0 $::tls]
$rd PING
$rd close
}
}
test {CONFIG SET bind address} {
start_server {} {
# non-valid address
catch {r CONFIG SET bind "some.wrong.bind.address"} e
assert_match {*Failed to bind to specified addresses*} $e
# make sure server still bound to the previous address
set rd [redis [srv 0 host] [srv 0 port] 0 $::tls]
$rd PING
$rd close
}
}
+10 -5
View File
@@ -21,17 +21,17 @@ if {$system_name eq {linux}} {
r config set oom-score-adj-values "10 20 30"
r config set oom-score-adj yes
assert_equal [get_oom_score_adj] [expr $base + 10] case1
assert {[get_oom_score_adj] == [expr $base + 10]}
# Modify current class
r config set oom-score-adj-values "15 20 30"
assert_equal [get_oom_score_adj] [expr $base + 15] case2
assert {[get_oom_score_adj] == [expr $base + 15]}
# Check replica class
r replicaof localhost 1
assert_equal [get_oom_score_adj] [expr $base + 20] case3
assert {[get_oom_score_adj] == [expr $base + 20]}
r replicaof no one
assert_equal [get_oom_score_adj] [expr $base + 15] case4
assert {[get_oom_score_adj] == [expr $base + 15]}
# Check child process
r set key-a value-a
@@ -39,7 +39,12 @@ if {$system_name eq {linux}} {
r bgsave
set child_pid [get_child_pid 0]
assert {[get_oom_score_adj $child_pid] == [expr $base + 30]}
# Wait until background child process to setOOMScoreAdj success.
wait_for_condition 100 10 {
[get_oom_score_adj $child_pid] == [expr $base + 30]
} else {
fail "Set oom-score-adj of background child process is not ok"
}
}
# Failed oom-score-adj tests can only run unprivileged
+97 -3
View File
@@ -62,7 +62,7 @@ start_server {tags {"other"}} {
} {*index is out of range*}
tags {consistency} {
if {![catch {package require sha1}]} {
if {true} {
if {$::accurate} {set numops 10000} else {set numops 1000}
test {Check consistency of different data types after a reload} {
r flushdb
@@ -256,6 +256,57 @@ start_server {tags {"other"}} {
waitForBgsave r
r save
} {OK}
test {RESET clears client state} {
r client setname test-client
r client tracking on
assert_equal [r reset] "RESET"
set client [r client list]
assert_match {*name= *} $client
assert_match {*flags=N *} $client
}
test {RESET clears MONITOR state} {
set rd [redis_deferring_client]
$rd monitor
assert_equal [$rd read] "OK"
$rd reset
# skip reset ouptut
$rd read
assert_equal [$rd read] "RESET"
assert_no_match {*flags=O*} [r client list]
}
test {RESET clears and discards MULTI state} {
r multi
r set key-a a
r reset
catch {r exec} err
assert_match {*EXEC without MULTI*} $err
}
test {RESET clears Pub/Sub state} {
r subscribe channel-1
r reset
# confirm we're not subscribed by executing another command
r set key val
}
test {RESET clears authenticated state} {
r acl setuser user1 on >secret +@all
r auth user1 secret
assert_equal [r acl whoami] user1
r reset
assert_equal [r acl whoami] default
}
}
start_server {tags {"other"}} {
@@ -272,8 +323,51 @@ start_server {tags {"other"}} {
after 200
# Hash table should rehash since there is no child process,
# size is power of two and over 4098, so it is 16384
# size is power of two and over 4098, so it is 8192
r set k3 v3
assert_match "*table size: 16384*" [r debug HTSTATS 9]
assert_match "*table size: 8192*" [r debug HTSTATS 9]
}
}
proc read_proc_title {pid} {
set fd [open "/proc/$pid/cmdline" "r"]
set cmdline [read $fd 1024]
close $fd
return $cmdline
}
start_server {tags {"other"}} {
test {Process title set as expected} {
# Test only on Linux where it's easy to get cmdline without relying on tools.
# Skip valgrind as it messes up the arguments.
set os [exec uname]
if {$os == "Linux" && !$::valgrind} {
# Set a custom template
r config set "proc-title-template" "TEST {title} {listen-addr} {port} {tls-port} {unixsocket} {config-file}"
set cmdline [read_proc_title [srv 0 pid]]
assert_equal "TEST" [lindex $cmdline 0]
assert_match "*/keydb-server" [lindex $cmdline 1]
if {$::tls} {
set expect_port 0
set expect_tls_port [srv 0 port]
} else {
set expect_port [srv 0 port]
set expect_tls_port 0
}
set port [srv 0 port]
assert_equal "$::host:$port" [lindex $cmdline 2]
assert_equal $expect_port [lindex $cmdline 3]
assert_equal $expect_tls_port [lindex $cmdline 4]
assert_match "*/tests/tmp/server.*/socket" [lindex $cmdline 5]
assert_match "*/tests/tmp/redis.conf.*" [lindex $cmdline 6]
# Try setting a bad template
catch {r config set "proc-title-template" "{invalid-var}"} err
assert_match {*template format is invalid*} $err
}
}
}
+200
View File
@@ -0,0 +1,200 @@
start_server {tags {"pause network"}} {
test "Test read commands are not blocked by client pause" {
r client PAUSE 100000000 WRITE
set rd [redis_deferring_client]
$rd GET FOO
$rd PING
$rd INFO
assert_equal [s 0 blocked_clients] 0
r client unpause
$rd close
}
test "Test write commands are paused by RO" {
r client PAUSE 100000000 WRITE
set rd [redis_deferring_client]
$rd SET FOO BAR
wait_for_condition 50 100 {
[s 0 blocked_clients] eq {1}
} else {
fail "Clients are not blocked"
}
r client unpause
assert_match "OK" [$rd read]
$rd close
}
test "Test special commands are paused by RO" {
r PFADD pause-hll test
r client PAUSE 100000000 WRITE
# Test that pfcount, which can replicate, is also blocked
set rd [redis_deferring_client]
$rd PFCOUNT pause-hll
wait_for_condition 50 100 {
[s 0 blocked_clients] eq {1}
} else {
fail "Clients are not blocked"
}
# Test that publish, which adds the message to the replication
# stream is blocked.
set rd2 [redis_deferring_client]
$rd2 publish foo bar
wait_for_condition 50 100 {
[s 0 blocked_clients] eq {2}
} else {
fail "Clients are not blocked"
}
# Test that SCRIPT LOAD, which is replicated.
set rd3 [redis_deferring_client]
$rd3 script load "return 1"
wait_for_condition 50 100 {
[s 0 blocked_clients] eq {3}
} else {
fail "Clients are not blocked"
}
r client unpause
assert_match "1" [$rd read]
assert_match "0" [$rd2 read]
assert_match "*" [$rd3 read]
$rd close
$rd2 close
$rd3 close
}
test "Test read/admin mutli-execs are not blocked by pause RO" {
r SET FOO BAR
r client PAUSE 100000000 WRITE
set rd [redis_deferring_client]
$rd MULTI
assert_equal [$rd read] "OK"
$rd PING
assert_equal [$rd read] "QUEUED"
$rd GET FOO
assert_equal [$rd read] "QUEUED"
$rd EXEC
assert_equal [s 0 blocked_clients] 0
r client unpause
assert_match "PONG BAR" [$rd read]
$rd close
}
test "Test write mutli-execs are blocked by pause RO" {
set rd [redis_deferring_client]
$rd MULTI
assert_equal [$rd read] "OK"
$rd SET FOO BAR
r client PAUSE 100000000 WRITE
assert_equal [$rd read] "QUEUED"
$rd EXEC
wait_for_condition 50 100 {
[s 0 blocked_clients] eq {1}
} else {
fail "Clients are not blocked"
}
r client unpause
assert_match "OK" [$rd read]
$rd close
}
test "Test scripts are blocked by pause RO" {
r client PAUSE 100000000 WRITE
set rd [redis_deferring_client]
$rd EVAL "return 1" 0
wait_for_condition 50 100 {
[s 0 blocked_clients] eq {1}
} else {
fail "Clients are not blocked"
}
r client unpause
assert_match "1" [$rd read]
$rd close
}
test "Test multiple clients can be queued up and unblocked" {
r client PAUSE 100000000 WRITE
set clients [list [redis_deferring_client] [redis_deferring_client] [redis_deferring_client]]
foreach client $clients {
$client SET FOO BAR
}
wait_for_condition 50 100 {
[s 0 blocked_clients] eq {3}
} else {
fail "Clients are not blocked"
}
r client unpause
foreach client $clients {
assert_match "OK" [$client read]
$client close
}
}
test "Test clients with syntax errors will get responses immediately" {
r client PAUSE 100000000 WRITE
catch {r set FOO} err
assert_match "ERR wrong number of arguments for *" $err
r client unpause
}
test "Test both active and passive expiries are skipped during client pause" {
set expired_keys [s 0 expired_keys]
r multi
r set foo bar PX 10
r set bar foo PX 10
r client PAUSE 100000000 WRITE
r exec
wait_for_condition 10 100 {
[r get foo] == {} && [r get bar] == {}
} else {
fail "Keys were never logically expired"
}
# No keys should actually have been expired
assert_match $expired_keys [s 0 expired_keys]
r client unpause
# Force the keys to expire
r get foo
r get bar
# Now that clients have been unpaused, expires should go through
assert_match [expr $expired_keys + 2] [s 0 expired_keys]
}
test "Test that client pause starts at the end of a transaction" {
r MULTI
r SET FOO1 BAR
r client PAUSE 100000000 WRITE
r SET FOO2 BAR
r exec
set rd [redis_deferring_client]
$rd SET FOO3 BAR
wait_for_condition 50 100 {
[s 0 blocked_clients] eq {1}
} else {
fail "Clients are not blocked"
}
assert_match "BAR" [r GET FOO1]
assert_match "BAR" [r GET FOO2]
assert_match "" [r GET FOO3]
r client unpause
assert_match "OK" [$rd read]
$rd close
}
# Make sure we unpause at the end
r client unpause
}
+1 -1
View File
@@ -1,4 +1,4 @@
start_server {tags {"protocol"}} {
start_server {tags {"protocol network"}} {
test "Handle an empty query" {
reconnect
r write "\r\n"
+1 -1
View File
@@ -1,4 +1,4 @@
start_server {tags {"pubsub"}} {
start_server {tags {"pubsub network"}} {
proc __consume_subscribe_messages {client type channels} {
set numsub -1
set counts {}
+1 -1
View File
@@ -1,4 +1,4 @@
start_server {tags {"scan"}} {
start_server {tags {"scan network"}} {
test "SCAN basic" {
r flushdb
r debug populate 1000
+41 -1
View File
@@ -140,12 +140,42 @@ start_server {tags {"scripting"}} {
} {*execution time*}
}
test {EVAL - Scripts can't run certain commands} {
test {EVAL - Scripts can't run blpop command} {
set e {}
catch {r eval {return redis.pcall('blpop','x',0)} 0} e
set e
} {*not allowed*}
test {EVAL - Scripts can't run brpop command} {
set e {}
catch {r eval {return redis.pcall('brpop','empty_list',0)} 0} e
set e
} {*not allowed*}
test {EVAL - Scripts can't run brpoplpush command} {
set e {}
catch {r eval {return redis.pcall('brpoplpush','empty_list1', 'empty_list2',0)} 0} e
set e
} {*not allowed*}
test {EVAL - Scripts can't run blmove command} {
set e {}
catch {r eval {return redis.pcall('blmove','empty_list1', 'empty_list2', 'LEFT', 'LEFT', 0)} 0} e
set e
} {*not allowed*}
test {EVAL - Scripts can't run bzpopmin command} {
set e {}
catch {r eval {return redis.pcall('bzpopmin','empty_zset', 0)} 0} e
set e
} {*not allowed*}
test {EVAL - Scripts can't run bzpopmax command} {
set e {}
catch {r eval {return redis.pcall('bzpopmax','empty_zset', 0)} 0} e
set e
} {*not allowed*}
test {EVAL - Scripts can't run XREAD and XREADGROUP with BLOCK option} {
r del s
r xgroup create s g $ MKSTREAM
@@ -300,6 +330,15 @@ start_server {tags {"scripting"}} {
set e
} {NOSCRIPT*}
test {SCRIPTING FLUSH ASYNC} {
for {set j 0} {$j < 100} {incr j} {
r script load "return $j"
}
assert { [string match "*number_of_cached_scripts:100*" [r info Memory]] }
r script flush async
assert { [string match "*number_of_cached_scripts:0*" [r info Memory]] }
}
test {SCRIPT EXISTS - can detect already defined scripts?} {
r eval "return 1+1" 0
r script exists a27e7e8a43702b7046d4f6a7ccf5b60cef6b9bd9 a27e7e8a43702b7046d4f6a7ccf5b60cef6b9bda
@@ -429,6 +468,7 @@ start_server {tags {"scripting"}} {
r slaveof no one
set res
} {102}
r config set aof-use-rdb-preamble yes
test {EVAL with pipelined command (No crash)} {
r flushall
+36 -1
View File
@@ -41,6 +41,41 @@ start_server {tags {"slowlog"} overrides {slowlog-log-slower-than 1000000}} {
assert_equal {foobar} [lindex $e 5]
}
test {SLOWLOG - Rewritten commands are logged as their original command} {
r config set slowlog-log-slower-than 0
# Test rewriting client arguments
r sadd set a b c d e
r slowlog reset
# SPOP is rewritten as DEL when all keys are removed
r spop set 10
assert_equal {spop set 10} [lindex [lindex [r slowlog get] 0] 3]
# Test replacing client arguments
r slowlog reset
# GEOADD is replicated as ZADD
r geoadd cool-cities -122.33207 47.60621 Seattle
assert_equal {geoadd cool-cities -122.33207 47.60621 Seattle} [lindex [lindex [r slowlog get] 0] 3]
# Test replacing a single command argument
r set A 5
r slowlog reset
# GETSET is replicated as SET
r getset a 5
assert_equal {getset a 5} [lindex [lindex [r slowlog get] 0] 3]
# INCRBYFLOAT calls rewrite multiple times, so it's a special case
r set A 0
r slowlog reset
# INCRBYFLOAT is replicated as SET
r INCRBYFLOAT A 1.0
assert_equal {INCRBYFLOAT A 1.0} [lindex [lindex [r slowlog get] 0] 3]
}
test {SLOWLOG - commands with too many arguments are trimmed} {
r config set slowlog-log-slower-than 0
r slowlog reset
@@ -70,7 +105,7 @@ start_server {tags {"slowlog"} overrides {slowlog-log-slower-than 1000000}} {
assert_equal [lindex $e 3] {debug sleep 0.2}
}
test {SLOWLOG - can clean older entires} {
test {SLOWLOG - can clean older entries} {
r client setname lastentry_client
r config set slowlog-max-len 1
r debug sleep 0.2
+46
View File
@@ -93,5 +93,51 @@ start_server {tags {"tls"}} {
r CONFIG SET tls-protocols ""
r CONFIG SET tls-ciphers "DEFAULT"
}
test {TLS: Verify tls-cert-file is also used as a client cert if none specified} {
set master [srv 0 client]
set master_host [srv 0 host]
set master_port [srv 0 port]
# Use a non-restricted client/server cert for the replica
set redis_crt [format "%s/tests/tls/redis.crt" [pwd]]
set redis_key [format "%s/tests/tls/redis.key" [pwd]]
start_server [list overrides [list tls-cert-file $redis_crt tls-key-file $redis_key] \
omit [list tls-client-cert-file tls-client-key-file]] {
set replica [srv 0 client]
$replica replicaof $master_host $master_port
wait_for_condition 30 100 {
[string match {*master_link_status:up*} [$replica info replication]]
} else {
fail "Can't authenticate to master using just tls-cert-file!"
}
}
}
test {TLS: switch between tcp and tls ports} {
set srv_port [srv 0 port]
# TLS
set rd [redis [srv 0 host] $srv_port 0 1]
$rd PING
# TCP
$rd CONFIG SET tls-port 0
$rd CONFIG SET port $srv_port
$rd close
set rd [redis [srv 0 host] $srv_port 0 0]
$rd PING
# TLS
$rd CONFIG SET port 0
$rd CONFIG SET tls-port $srv_port
$rd close
set rd [redis [srv 0 host] $srv_port 0 1]
$rd PING
$rd close
}
}
}
+472 -42
View File
@@ -1,26 +1,51 @@
start_server {tags {"tracking"}} {
start_server {tags {"tracking network"}} {
# Create a deferred client we'll use to redirect invalidation
# messages to.
set rd1 [redis_deferring_client]
$rd1 client id
set redir [$rd1 read]
$rd1 subscribe __redis__:invalidate
$rd1 read ; # Consume the SUBSCRIBE reply.
set rd_redirection [redis_deferring_client]
$rd_redirection client id
set redir_id [$rd_redirection read]
$rd_redirection subscribe __redis__:invalidate
$rd_redirection read ; # Consume the SUBSCRIBE reply.
# Create another client as well in order to test NOLOOP
set rd2 [redis_deferring_client]
# Create another client that's not used as a redirection client
# We should always keep this client's buffer clean
set rd [redis_deferring_client]
# Client to be used for SET and GET commands
# We don't read this client's buffer
set rd_sg [redis_client]
proc clean_all {} {
uplevel {
# We should make r TRACKING off first. If r is in RESP3,
# r FLUSH ALL will send us tracking-redir-broken or other
# info which will not be consumed.
r CLIENT TRACKING off
$rd QUIT
$rd_redirection QUIT
set rd [redis_deferring_client]
set rd_redirection [redis_deferring_client]
$rd_redirection client id
set redir_id [$rd_redirection read]
$rd_redirection subscribe __redis__:invalidate
$rd_redirection read ; # Consume the SUBSCRIBE reply.
r FLUSHALL
r HELLO 2
r config set tracking-table-max-keys 1000000
}
}
test {Clients are able to enable tracking and redirect it} {
r CLIENT TRACKING on REDIRECT $redir
r CLIENT TRACKING on REDIRECT $redir_id
} {*OK}
test {The other connection is able to get invalidations} {
r SET a 1
r SET b 1
r GET a
r INCR b ; # This key should not be notified, since it wasn't fetched.
r INCR a
set keys [lindex [$rd1 read] 2]
r INCR b ; # This key should not be notified, since it wasn't fetched.
r INCR a
set keys [lindex [$rd_redirection read] 2]
assert {[llength $keys] == 1}
assert {[lindex $keys 0] eq {a}}
}
@@ -30,87 +55,307 @@ start_server {tags {"tracking"}} {
# so that we can check for leaks, as a side effect.
r MGET a b c d e f g
r CLIENT TRACKING off
}
} {*OK}
test {Clients can enable the BCAST mode with the empty prefix} {
r CLIENT TRACKING on BCAST REDIRECT $redir
r CLIENT TRACKING on BCAST REDIRECT $redir_id
} {*OK*}
test {The connection gets invalidation messages about all the keys} {
r MSET a 1 b 2 c 3
set keys [lsort [lindex [$rd1 read] 2]]
set keys [lsort [lindex [$rd_redirection read] 2]]
assert {$keys eq {a b c}}
}
test {Clients can enable the BCAST mode with prefixes} {
r CLIENT TRACKING off
r CLIENT TRACKING on BCAST REDIRECT $redir PREFIX a: PREFIX b:
r CLIENT TRACKING on BCAST REDIRECT $redir_id PREFIX a: PREFIX b:
r MULTI
r INCR a:1
r INCR a:2
r INCR b:1
r INCR b:2
# we should not get this key
r INCR c:1
r EXEC
# Because of the internals, we know we are going to receive
# two separated notifications for the two different prefixes.
set keys1 [lsort [lindex [$rd1 read] 2]]
set keys2 [lsort [lindex [$rd1 read] 2]]
set keys1 [lsort [lindex [$rd_redirection read] 2]]
set keys2 [lsort [lindex [$rd_redirection read] 2]]
set keys [lsort [list {*}$keys1 {*}$keys2]]
assert {$keys eq {a:1 a:2 b:1 b:2}}
}
test {Adding prefixes to BCAST mode works} {
r CLIENT TRACKING on BCAST REDIRECT $redir PREFIX c:
r CLIENT TRACKING on BCAST REDIRECT $redir_id PREFIX c:
r INCR c:1234
set keys [lsort [lindex [$rd1 read] 2]]
set keys [lsort [lindex [$rd_redirection read] 2]]
assert {$keys eq {c:1234}}
}
test {Tracking NOLOOP mode in standard mode works} {
r CLIENT TRACKING off
r CLIENT TRACKING on REDIRECT $redir NOLOOP
r CLIENT TRACKING on REDIRECT $redir_id NOLOOP
r MGET otherkey1 loopkey otherkey2
$rd2 SET otherkey1 1; # We should get this
$rd_sg SET otherkey1 1; # We should get this
r SET loopkey 1 ; # We should not get this
$rd2 SET otherkey2 1; # We should get this
$rd_sg SET otherkey2 1; # We should get this
# Because of the internals, we know we are going to receive
# two separated notifications for the two different prefixes.
set keys1 [lsort [lindex [$rd1 read] 2]]
set keys2 [lsort [lindex [$rd1 read] 2]]
# two separated notifications for the two different keys.
set keys1 [lsort [lindex [$rd_redirection read] 2]]
set keys2 [lsort [lindex [$rd_redirection read] 2]]
set keys [lsort [list {*}$keys1 {*}$keys2]]
assert {$keys eq {otherkey1 otherkey2}}
}
test {Tracking NOLOOP mode in BCAST mode works} {
r CLIENT TRACKING off
r CLIENT TRACKING on BCAST REDIRECT $redir NOLOOP
$rd2 SET otherkey1 1; # We should get this
r CLIENT TRACKING on BCAST REDIRECT $redir_id NOLOOP
$rd_sg SET otherkey1 1; # We should get this
r SET loopkey 1 ; # We should not get this
$rd2 SET otherkey2 1; # We should get this
# Because of the internals, we know we are going to receive
# two separated notifications for the two different prefixes.
set keys1 [lsort [lindex [$rd1 read] 2]]
set keys2 [lsort [lindex [$rd1 read] 2]]
$rd_sg SET otherkey2 1; # We should get this
# Because $rd_sg send command synchronously, we know we are
# going to receive two separated notifications.
set keys1 [lsort [lindex [$rd_redirection read] 2]]
set keys2 [lsort [lindex [$rd_redirection read] 2]]
set keys [lsort [list {*}$keys1 {*}$keys2]]
assert {$keys eq {otherkey1 otherkey2}}
}
test {Tracking gets notification of expired keys} {
r CLIENT TRACKING off
r CLIENT TRACKING on BCAST REDIRECT $redir NOLOOP
r CLIENT TRACKING on BCAST REDIRECT $redir_id NOLOOP
r SET mykey myval px 1
r SET mykeyotherkey myval ; # We should not get it
after 1000
# Because of the internals, we know we are going to receive
# two separated notifications for the two different prefixes.
set keys1 [lsort [lindex [$rd1 read] 2]]
set keys [lsort [list {*}$keys1]]
set keys [lsort [lindex [$rd_redirection read] 2]]
assert {$keys eq {mykey}}
}
test {HELLO 3 reply is correct} {
set reply [r HELLO 3]
assert_equal [dict get $reply proto] 3
}
test {HELLO without protover} {
set reply [r HELLO 3]
assert_equal [dict get $reply proto] 3
set reply [r HELLO]
assert_equal [dict get $reply proto] 3
set reply [r HELLO 2]
assert_equal [dict get $reply proto] 2
set reply [r HELLO]
assert_equal [dict get $reply proto] 2
# restore RESP3 for next test
r HELLO 3
}
test {RESP3 based basic invalidation} {
r CLIENT TRACKING off
r CLIENT TRACKING on
$rd_sg SET key1 1
r GET key1
$rd_sg SET key1 2
r read
} {invalidate key1}
test {RESP3 tracking redirection} {
r CLIENT TRACKING off
r CLIENT TRACKING on REDIRECT $redir_id
$rd_sg SET key1 1
r GET key1
$rd_sg SET key1 2
set res [lindex [$rd_redirection read] 2]
assert {$res eq {key1}}
}
test {Invalidations of previous keys can be redirected after switching to RESP3} {
r HELLO 2
$rd_sg SET key1 1
r GET key1
r HELLO 3
$rd_sg SET key1 2
set res [lindex [$rd_redirection read] 2]
assert {$res eq {key1}}
}
test {Invalidations of new keys can be redirected after switching to RESP3} {
r HELLO 3
$rd_sg SET key1 1
r GET key1
$rd_sg SET key1 2
set res [lindex [$rd_redirection read] 2]
assert {$res eq {key1}}
}
test {RESP3 Client gets tracking-redir-broken push message after cached key changed when rediretion client is terminated} {
r CLIENT TRACKING on REDIRECT $redir_id
$rd_sg SET key1 1
r GET key1
$rd_redirection QUIT
assert_equal OK [$rd_redirection read]
$rd_sg SET key1 2
set MAX_TRIES 100
set res -1
for {set i 0} {$i <= $MAX_TRIES && $res < 0} {incr i} {
set res [lsearch -exact [r PING] "tracking-redir-broken"]
}
assert {$res >= 0}
# Consume PING reply
assert_equal PONG [r read]
# Reinstantiating after QUIT
set rd_redirection [redis_deferring_client]
$rd_redirection CLIENT ID
set redir_id [$rd_redirection read]
$rd_redirection SUBSCRIBE __redis__:invalidate
$rd_redirection read ; # Consume the SUBSCRIBE reply
}
test {Different clients can redirect to the same connection} {
r CLIENT TRACKING on REDIRECT $redir_id
$rd CLIENT TRACKING on REDIRECT $redir_id
assert_equal OK [$rd read] ; # Consume the TRACKING reply
$rd_sg MSET key1 1 key2 1
r GET key1
$rd GET key2
assert_equal 1 [$rd read] ; # Consume the GET reply
$rd_sg INCR key1
$rd_sg INCR key2
set res1 [lindex [$rd_redirection read] 2]
set res2 [lindex [$rd_redirection read] 2]
assert {$res1 eq {key1}}
assert {$res2 eq {key2}}
}
test {Different clients using different protocols can track the same key} {
$rd HELLO 3
set reply [$rd read] ; # Consume the HELLO reply
assert_equal 3 [dict get $reply proto]
$rd CLIENT TRACKING on
assert_equal OK [$rd read] ; # Consume the TRACKING reply
$rd_sg set key1 1
r GET key1
$rd GET key1
assert_equal 1 [$rd read] ; # Consume the GET reply
$rd_sg INCR key1
set res1 [lindex [$rd_redirection read] 2]
$rd PING ; # Non redirecting client has to talk to the server in order to get invalidation message
set res2 [lindex [split [$rd read] " "] 1]
assert_equal PONG [$rd read] ; # Consume the PING reply, which comes together with the invalidation message
assert {$res1 eq {key1}}
assert {$res2 eq {key1}}
}
test {No invalidation message when using OPTIN option} {
r CLIENT TRACKING on OPTIN REDIRECT $redir_id
$rd_sg SET key1 1
r GET key1 ; # This key should not be notified, since OPTIN is on and CLIENT CACHING yes wasn't called
$rd_sg SET key1 2
# Preparing some message to consume on $rd_redirection so we don't get blocked
r CLIENT TRACKING off
r CLIENT TRACKING on REDIRECT $redir_id
$rd_sg SET key2 1
r GET key2 ; # This key should be notified
$rd_sg SET key2 2
set res [lindex [$rd_redirection read] 2]
assert {$res eq {key2}}
}
test {Invalidation message sent when using OPTIN option with CLIENT CACHING yes} {
r CLIENT TRACKING on OPTIN REDIRECT $redir_id
$rd_sg SET key1 3
r CLIENT CACHING yes
r GET key1
$rd_sg SET key1 4
set res [lindex [$rd_redirection read] 2]
assert {$res eq {key1}}
}
test {Invalidation message sent when using OPTOUT option} {
r CLIENT TRACKING off
r CLIENT TRACKING on OPTOUT REDIRECT $redir_id
$rd_sg SET key1 1
r GET key1
$rd_sg SET key1 2
set res [lindex [$rd_redirection read] 2]
assert {$res eq {key1}}
}
test {No invalidation message when using OPTOUT option with CLIENT CACHING no} {
$rd_sg SET key1 1
r CLIENT CACHING no
r GET key1 ; # This key should not be notified, since OPTOUT is on and CLIENT CACHING no was called
$rd_sg SET key1 2
# Preparing some message to consume on $rd_redirection so we don't get blocked
$rd_sg SET key2 1
r GET key2 ; # This key should be notified
$rd_sg SET key2 2
set res [lindex [$rd_redirection read] 2]
assert {$res eq {key2}}
}
test {Able to redirect to a RESP3 client} {
$rd_redirection UNSUBSCRIBE __redis__:invalidate ; # Need to unsub first before we can do HELLO 3
set res [$rd_redirection read] ; # Consume the UNSUBSCRIBE reply
assert_equal {__redis__:invalidate} [lindex $res 1]
$rd_redirection HELLO 3
set res [$rd_redirection read] ; # Consume the HELLO reply
assert_equal [dict get $reply proto] 3
$rd_redirection SUBSCRIBE __redis__:invalidate
set res [$rd_redirection read] ; # Consume the SUBSCRIBE reply
assert_equal {__redis__:invalidate} [lindex $res 1]
r CLIENT TRACKING on REDIRECT $redir_id
$rd_sg SET key1 1
r GET key1
$rd_sg INCR key1
set res [lindex [$rd_redirection read] 1]
assert {$res eq {key1}}
$rd_redirection HELLO 2
set res [$rd_redirection read] ; # Consume the HELLO reply
assert_equal [dict get $res proto] 2
}
test {After switching from normal tracking to BCAST mode, no invalidation message is produced for pre-BCAST keys} {
r CLIENT TRACKING off
r HELLO 3
r CLIENT TRACKING on
$rd_sg SET key1 1
r GET key1
r CLIENT TRACKING off
r CLIENT TRACKING on BCAST
$rd_sg INCR key1
set inv_msg [r PING]
set ping_reply [r read]
assert {$inv_msg eq {invalidate key1}}
assert {$ping_reply eq {PONG}}
}
test {BCAST with prefix collisions throw errors} {
set r [redis_client]
catch {$r CLIENT TRACKING ON BCAST PREFIX FOOBAR PREFIX FOO} output
assert_match {ERR Prefix 'FOOBAR'*'FOO'*} $output
catch {$r CLIENT TRACKING ON BCAST PREFIX FOO PREFIX FOOBAR} output
assert_match {ERR Prefix 'FOO'*'FOOBAR'*} $output
$r CLIENT TRACKING ON BCAST PREFIX FOO PREFIX BAR
catch {$r CLIENT TRACKING ON BCAST PREFIX FO} output
assert_match {ERR Prefix 'FO'*'FOO'*} $output
catch {$r CLIENT TRACKING ON BCAST PREFIX BARB} output
assert_match {ERR Prefix 'BARB'*'BAR'*} $output
$r CLIENT TRACKING OFF
}
test {Tracking gets notification on tracking table key eviction} {
r CLIENT TRACKING off
r CLIENT TRACKING on REDIRECT $redir NOLOOP
r CLIENT TRACKING on REDIRECT $redir_id NOLOOP
r MSET key1 1 key2 2
# Let the server track the two keys for us
r MGET key1 key2
@@ -122,7 +367,7 @@ start_server {tags {"tracking"}} {
# So we check that eventually we'll receive one or the other key,
# otherwise the test will die for timeout.
while 1 {
set keys [lindex [$rd1 read] 2]
set keys [lindex [$rd_redirection read] 2]
if {$keys eq {key1} || $keys eq {key2}} break
}
# We should receive an expire notification for one of
@@ -130,5 +375,190 @@ start_server {tags {"tracking"}} {
assert {$keys eq {key1} || $keys eq {key2}}
}
$rd1 close
test {Invalidation message received for flushall} {
clean_all
r CLIENT TRACKING on REDIRECT $redir_id
$rd_sg SET key1 1
r GET key1
$rd_sg FLUSHALL
set msg [$rd_redirection read]
assert {[lindex msg 2] eq {} }
}
test {Invalidation message received for flushdb} {
clean_all
r CLIENT TRACKING on REDIRECT $redir_id
$rd_sg SET key1 1
r GET key1
$rd_sg FLUSHDB
set msg [$rd_redirection read]
assert {[lindex msg 2] eq {} }
}
# Keys are defined to be evicted 100 at a time by default.
# If after eviction the number of keys still surpasses the limit
# defined in tracking-table-max-keys, we increases eviction
# effort to 200, and then 300, etc.
# This test tests this effort incrementation.
test {Server is able to evacuate enough keys when num of keys surpasses limit by more than defined initial effort} {
clean_all
set NUM_OF_KEYS_TO_TEST 250
set TRACKING_TABLE_MAX_KEYS 1
r CLIENT TRACKING on REDIRECT $redir_id
for {set i 0} {$i < $NUM_OF_KEYS_TO_TEST} {incr i} {
$rd_sg SET key$i $i
r GET key$i
}
r config set tracking-table-max-keys $TRACKING_TABLE_MAX_KEYS
# If not enough keys are evicted, we won't get enough invalidation
# messages, and "$rd_redirection read" will block.
# If too many keys are evicted, we will get too many invalidation
# messages, and the assert will fail.
for {set i 0} {$i < $NUM_OF_KEYS_TO_TEST - $TRACKING_TABLE_MAX_KEYS} {incr i} {
$rd_redirection read
}
$rd_redirection PING
assert {[$rd_redirection read] eq {pong {}}}
}
test {Tracking info is correct} {
clean_all
r CLIENT TRACKING on REDIRECT $redir_id
$rd_sg SET key1 1
$rd_sg SET key2 2
r GET key1
r GET key2
$rd CLIENT TRACKING on BCAST PREFIX prefix:
assert [string match *OK* [$rd read]]
$rd_sg SET prefix:key1 1
$rd_sg SET prefix:key2 2
set info [r info]
regexp "\r\ntracking_total_items:(.*?)\r\n" $info _ total_items
regexp "\r\ntracking_total_keys:(.*?)\r\n" $info _ total_keys
regexp "\r\ntracking_total_prefixes:(.*?)\r\n" $info _ total_prefixes
regexp "\r\ntracking_clients:(.*?)\r\n" $info _ tracking_clients
assert {$total_items == 2}
assert {$total_keys == 2}
assert {$total_prefixes == 1}
assert {$tracking_clients == 2}
}
test {CLIENT GETREDIR provides correct client id} {
set res [r CLIENT GETREDIR]
assert_equal $redir_id $res
r CLIENT TRACKING off
set res [r CLIENT GETREDIR]
assert_equal -1 $res
r CLIENT TRACKING on
set res [r CLIENT GETREDIR]
assert_equal 0 $res
}
test {CLIENT TRACKINGINFO provides reasonable results when tracking off} {
r CLIENT TRACKING off
set res [r client trackinginfo]
set flags [dict get $res flags]
assert_equal {off} $flags
set redirect [dict get $res redirect]
assert_equal {-1} $redirect
set prefixes [dict get $res prefixes]
assert_equal {} $prefixes
}
test {CLIENT TRACKINGINFO provides reasonable results when tracking on} {
r CLIENT TRACKING on
set res [r client trackinginfo]
set flags [dict get $res flags]
assert_equal {on} $flags
set redirect [dict get $res redirect]
assert_equal {0} $redirect
set prefixes [dict get $res prefixes]
assert_equal {} $prefixes
}
test {CLIENT TRACKINGINFO provides reasonable results when tracking on with options} {
r CLIENT TRACKING on REDIRECT $redir_id noloop
set res [r client trackinginfo]
set flags [dict get $res flags]
assert_equal {on noloop} $flags
set redirect [dict get $res redirect]
assert_equal $redir_id $redirect
set prefixes [dict get $res prefixes]
assert_equal {} $prefixes
}
test {CLIENT TRACKINGINFO provides reasonable results when tracking optin} {
r CLIENT TRACKING off
r CLIENT TRACKING on optin
set res [r client trackinginfo]
set flags [dict get $res flags]
assert_equal {on optin} $flags
set redirect [dict get $res redirect]
assert_equal {0} $redirect
set prefixes [dict get $res prefixes]
assert_equal {} $prefixes
r CLIENT CACHING yes
set res [r client trackinginfo]
set flags [dict get $res flags]
assert_equal {on optin caching-yes} $flags
}
test {CLIENT TRACKINGINFO provides reasonable results when tracking optout} {
r CLIENT TRACKING off
r CLIENT TRACKING on optout
set res [r client trackinginfo]
set flags [dict get $res flags]
assert_equal {on optout} $flags
set redirect [dict get $res redirect]
assert_equal {0} $redirect
set prefixes [dict get $res prefixes]
assert_equal {} $prefixes
r CLIENT CACHING no
set res [r client trackinginfo]
set flags [dict get $res flags]
assert_equal {on optout caching-no} $flags
}
test {CLIENT TRACKINGINFO provides reasonable results when tracking bcast mode} {
r CLIENT TRACKING off
r CLIENT TRACKING on BCAST PREFIX foo PREFIX bar
set res [r client trackinginfo]
set flags [dict get $res flags]
assert_equal {on bcast} $flags
set redirect [dict get $res redirect]
assert_equal {0} $redirect
set prefixes [lsort [dict get $res prefixes]]
assert_equal {bar foo} $prefixes
r CLIENT TRACKING off
r CLIENT TRACKING on BCAST
set res [r client trackinginfo]
set prefixes [dict get $res prefixes]
assert_equal {{}} $prefixes
}
test {CLIENT TRACKINGINFO provides reasonable results when tracking redir broken} {
clean_all
r HELLO 3
r CLIENT TRACKING on REDIRECT $redir_id
$rd_sg SET key1 1
r GET key1
$rd_redirection QUIT
assert_equal OK [$rd_redirection read]
$rd_sg SET key1 2
set res [lsearch -exact [r read] "tracking-redir-broken"]
assert {$res >= 0}
set res [r client trackinginfo]
set flags [dict get $res flags]
assert_equal {on broken_redirect} $flags
set redirect [dict get $res redirect]
assert_equal $redir_id $redirect
set prefixes [dict get $res prefixes]
assert_equal {} $prefixes
}
$rd_redirection close
$rd close
}
+243 -4
View File
@@ -18,6 +18,194 @@ start_server {tags {"hash"}} {
assert_encoding ziplist smallhash
}
proc create_hash {key entries} {
r del $key
foreach entry $entries {
r hset $key [lindex $entry 0] [lindex $entry 1]
}
}
proc get_keys {l} {
set res {}
foreach entry $l {
set key [lindex $entry 0]
lappend res $key
}
return $res
}
foreach {type contents} "ziplist {{a 1} {b 2} {c 3}} hashtable {{a 1} {b 2} {[randstring 70 90 alpha] 3}}" {
set original_max_value [lindex [r config get hash-max-ziplist-value] 1]
r config set hash-max-ziplist-value 10
create_hash myhash $contents
assert_encoding $type myhash
test "HRANDFIELD - $type" {
unset -nocomplain myhash
array set myhash {}
for {set i 0} {$i < 100} {incr i} {
set key [r hrandfield myhash]
set myhash($key) 1
}
assert_equal [lsort [get_keys $contents]] [lsort [array names myhash]]
}
r config set hash-max-ziplist-value $original_max_value
}
test "HRANDFIELD with RESP3" {
r hello 3
set res [r hrandfield myhash 3 withvalues]
assert_equal [llength $res] 3
assert_equal [llength [lindex $res 1]] 2
set res [r hrandfield myhash 3]
assert_equal [llength $res] 3
assert_equal [llength [lindex $res 1]] 1
}
r hello 2
test "HRANDFIELD count of 0 is handled correctly" {
r hrandfield myhash 0
} {}
test "HRANDFIELD with <count> against non existing key" {
r hrandfield nonexisting_key 100
} {}
foreach {type contents} "
hashtable {{a 1} {b 2} {c 3} {d 4} {e 5} {6 f} {7 g} {8 h} {9 i} {[randstring 70 90 alpha] 10}}
ziplist {{a 1} {b 2} {c 3} {d 4} {e 5} {6 f} {7 g} {8 h} {9 i} {10 j}} " {
test "HRANDFIELD with <count> - $type" {
set original_max_value [lindex [r config get hash-max-ziplist-value] 1]
r config set hash-max-ziplist-value 10
create_hash myhash $contents
assert_encoding $type myhash
# create a dict for easy lookup
unset -nocomplain mydict
foreach {k v} [r hgetall myhash] {
dict append mydict $k $v
}
# We'll stress different parts of the code, see the implementation
# of HRANDFIELD for more information, but basically there are
# four different code paths.
# PATH 1: Use negative count.
# 1) Check that it returns repeated elements with and without values.
set res [r hrandfield myhash -20]
assert_equal [llength $res] 20
set res [r hrandfield myhash -1001]
assert_equal [llength $res] 1001
# again with WITHVALUES
set res [r hrandfield myhash -20 withvalues]
assert_equal [llength $res] 40
set res [r hrandfield myhash -1001 withvalues]
assert_equal [llength $res] 2002
# Test random uniform distribution
set res [r hrandfield myhash -1000]
assert_equal [check_histogram_distribution $res 0.05 0.15] true
# 2) Check that all the elements actually belong to the original hash.
foreach {key val} $res {
assert {[dict exists $mydict $key]}
}
# 3) Check that eventually all the elements are returned.
# Use both WITHVALUES and without
unset -nocomplain auxset
set iterations 1000
while {$iterations != 0} {
incr iterations -1
if {[expr {$iterations % 2}] == 0} {
set res [r hrandfield myhash -3 withvalues]
foreach {key val} $res {
dict append auxset $key $val
}
} else {
set res [r hrandfield myhash -3]
foreach key $res {
dict append auxset $key $val
}
}
if {[lsort [dict keys $mydict]] eq
[lsort [dict keys $auxset]]} {
break;
}
}
assert {$iterations != 0}
# PATH 2: positive count (unique behavior) with requested size
# equal or greater than set size.
foreach size {10 20} {
set res [r hrandfield myhash $size]
assert_equal [llength $res] 10
assert_equal [lsort $res] [lsort [dict keys $mydict]]
# again with WITHVALUES
set res [r hrandfield myhash $size withvalues]
assert_equal [llength $res] 20
assert_equal [lsort $res] [lsort $mydict]
}
# PATH 3: Ask almost as elements as there are in the set.
# In this case the implementation will duplicate the original
# set and will remove random elements up to the requested size.
#
# PATH 4: Ask a number of elements definitely smaller than
# the set size.
#
# We can test both the code paths just changing the size but
# using the same code.
foreach size {8 2} {
set res [r hrandfield myhash $size]
assert_equal [llength $res] $size
# again with WITHVALUES
set res [r hrandfield myhash $size withvalues]
assert_equal [llength $res] [expr {$size * 2}]
# 1) Check that all the elements actually belong to the
# original set.
foreach ele [dict keys $res] {
assert {[dict exists $mydict $ele]}
}
# 2) Check that eventually all the elements are returned.
# Use both WITHVALUES and without
unset -nocomplain auxset
unset -nocomplain allkey
set iterations [expr {1000 / $size}]
set all_ele_return false
while {$iterations != 0} {
incr iterations -1
if {[expr {$iterations % 2}] == 0} {
set res [r hrandfield myhash $size withvalues]
foreach {key value} $res {
dict append auxset $key $value
lappend allkey $key
}
} else {
set res [r hrandfield myhash $size]
foreach key $res {
dict append auxset $key
lappend allkey $key
}
}
if {[lsort [dict keys $mydict]] eq
[lsort [dict keys $auxset]]} {
set all_ele_return true
}
}
assert_equal $all_ele_return true
assert_equal [check_histogram_distribution $allkey 0.05 0.15] true
}
}
r config set hash-max-ziplist-value $original_max_value
}
test {HSET/HLEN - Big hash creation} {
array set bighash {}
for {set i 0} {$i < 1024} {incr i} {
@@ -302,7 +490,7 @@ start_server {tags {"hash"}} {
r hset smallhash str " 11"
r hset bighash str " 11"
catch {r hincrby smallhash str 1} smallerr
catch {r hincrby smallhash str 1} bigerr
catch {r hincrby bighash str 1} bigerr
set rv {}
lappend rv [string match "ERR*not an integer*" $smallerr]
lappend rv [string match "ERR*not an integer*" $bigerr]
@@ -312,7 +500,7 @@ start_server {tags {"hash"}} {
r hset smallhash str "11 "
r hset bighash str "11 "
catch {r hincrby smallhash str 1} smallerr
catch {r hincrby smallhash str 1} bigerr
catch {r hincrby bighash str 1} bigerr
set rv {}
lappend rv [string match "ERR*not an integer*" $smallerr]
lappend rv [string match "ERR*not an integer*" $bigerr]
@@ -374,7 +562,7 @@ start_server {tags {"hash"}} {
r hset smallhash str " 11"
r hset bighash str " 11"
catch {r hincrbyfloat smallhash str 1} smallerr
catch {r hincrbyfloat smallhash str 1} bigerr
catch {r hincrbyfloat bighash str 1} bigerr
set rv {}
lappend rv [string match "ERR*not*float*" $smallerr]
lappend rv [string match "ERR*not*float*" $bigerr]
@@ -384,7 +572,7 @@ start_server {tags {"hash"}} {
r hset smallhash str "11 "
r hset bighash str "11 "
catch {r hincrbyfloat smallhash str 1} smallerr
catch {r hincrbyfloat smallhash str 1} bigerr
catch {r hincrbyfloat bighash str 1} bigerr
set rv {}
lappend rv [string match "ERR*not*float*" $smallerr]
lappend rv [string match "ERR*not*float*" $bigerr]
@@ -572,4 +760,55 @@ start_server {tags {"hash"}} {
assert {[r hincrbyfloat myhash float -0.1] eq {1.9}}
}
}
test {Hash ziplist of various encodings} {
r del k
r config set hash-max-ziplist-entries 1000000000
r config set hash-max-ziplist-value 1000000000
r hset k ZIP_INT_8B 127
r hset k ZIP_INT_16B 32767
r hset k ZIP_INT_32B 2147483647
r hset k ZIP_INT_64B 9223372036854775808
r hset k ZIP_INT_IMM_MIN 0
r hset k ZIP_INT_IMM_MAX 12
r hset k ZIP_STR_06B [string repeat x 31]
r hset k ZIP_STR_14B [string repeat x 8191]
r hset k ZIP_STR_32B [string repeat x 65535]
set k [r hgetall k]
set dump [r dump k]
# will be converted to dict at RESTORE
r config set hash-max-ziplist-entries 2
r config set sanitize-dump-payload no
r restore kk 0 $dump
set kk [r hgetall kk]
# make sure the values are right
assert_equal [lsort $k] [lsort $kk]
assert_equal [dict get $k ZIP_STR_06B] [string repeat x 31]
set k [dict remove $k ZIP_STR_06B]
assert_equal [dict get $k ZIP_STR_14B] [string repeat x 8191]
set k [dict remove $k ZIP_STR_14B]
assert_equal [dict get $k ZIP_STR_32B] [string repeat x 65535]
set k [dict remove $k ZIP_STR_32B]
set _ $k
} {ZIP_INT_8B 127 ZIP_INT_16B 32767 ZIP_INT_32B 2147483647 ZIP_INT_64B 9223372036854775808 ZIP_INT_IMM_MIN 0 ZIP_INT_IMM_MAX 12}
test {Hash ziplist of various encodings - sanitize dump} {
r config set sanitize-dump-payload yes
r restore kk 0 $dump replace
set k [r hgetall k]
set kk [r hgetall kk]
# make sure the values are right
assert_equal [lsort $k] [lsort $kk]
assert_equal [dict get $k ZIP_STR_06B] [string repeat x 31]
set k [dict remove $k ZIP_STR_06B]
assert_equal [dict get $k ZIP_STR_14B] [string repeat x 8191]
set k [dict remove $k ZIP_STR_14B]
assert_equal [dict get $k ZIP_STR_32B] [string repeat x 65535]
set k [dict remove $k ZIP_STR_32B]
set _ $k
} {ZIP_INT_8B 127 ZIP_INT_16B 32767 ZIP_INT_32B 2147483647 ZIP_INT_64B 9223372036854775808 ZIP_INT_IMM_MIN 0 ZIP_INT_IMM_MAX 12}
}
+1 -1
View File
@@ -29,11 +29,11 @@ start_server {
set max [expr {$min+int(rand()*$startlen)}]
set before_len [llength $mylist]
set before_len_r [r llen mylist]
assert_equal $before_len $before_len_r
set mylist [lrange $mylist $min $max]
r ltrim mylist $min $max
assert_equal $mylist [r lrange mylist 0 -1] "failed trim"
set starting [r llen mylist]
for {set j [r llen mylist]} {$j < $startlen} {incr j} {
set str [randomInt 9223372036854775807]
r rpush mylist $str
+287 -20
View File
@@ -1,3 +1,11 @@
proc wait_for_blocked_client {} {
wait_for_condition 50 100 {
[s blocked_clients] ne 0
} else {
fail "no blocked clients"
}
}
# Setting server-threads to 2 is really single threaded because test mode is enabled (no client allocated to thread 1)
# We do this because of the large numbers of nonblocking clients in this tests and the client races that causes
start_server {
@@ -55,7 +63,7 @@ start_server {
test {LPOS when RANK is greater than matches} {
r DEL mylist
r LPUSH l a
r LPUSH mylist a
assert {[r LPOS mylist b COUNT 10 RANK 5] eq {}}
}
@@ -118,6 +126,17 @@ start_server {
test {R/LPOP against empty list} {
r lpop non-existing-list
} {}
test {R/LPOP with the optional count argument} {
assert_equal 7 [r lpush listcount aa bb cc dd ee ff gg]
assert_equal {} [r lpop listcount 0]
assert_equal {gg} [r lpop listcount 1]
assert_equal {ff ee} [r lpop listcount 2]
assert_equal {aa bb} [r rpop listcount 2]
assert_equal {cc} [r rpop listcount 1]
assert_equal {dd} [r rpop listcount 123]
assert_error "*ERR*range*" {r lpop forbarqaz -123}
}
test {Variadic RPUSH/LPUSH} {
r del mylist
@@ -189,6 +208,7 @@ start_server {
test "BRPOPLPUSH - $type" {
r del target
r rpush target bar
set rd [redis_deferring_client]
create_list blist "a b $large c d"
@@ -196,9 +216,38 @@ start_server {
$rd brpoplpush blist target 1
assert_equal d [$rd read]
assert_equal d [r rpop target]
assert_equal d [r lpop target]
assert_equal "a b $large c" [r lrange blist 0 -1]
}
foreach wherefrom {left right} {
foreach whereto {left right} {
test "BLMOVE $wherefrom $whereto - $type" {
r del target
r rpush target bar
set rd [redis_deferring_client]
create_list blist "a b $large c d"
$rd blmove blist target $wherefrom $whereto 1
set poppedelement [$rd read]
if {$wherefrom eq "right"} {
assert_equal d $poppedelement
assert_equal "a b $large c" [r lrange blist 0 -1]
} else {
assert_equal a $poppedelement
assert_equal "b $large c d" [r lrange blist 0 -1]
}
if {$whereto eq "right"} {
assert_equal $poppedelement [r rpop target]
} else {
assert_equal $poppedelement [r lpop target]
}
}
}
}
}
test "BLPOP, LPUSH + DEL should not awake blocked client" {
@@ -220,6 +269,8 @@ start_server {
r del list
$rd blpop list 0
after 100 ;# Make sure rd is blocked before MULTI
r multi
r lpush list a
r del list
@@ -278,24 +329,60 @@ start_server {
test "BRPOPLPUSH with zero timeout should block indefinitely" {
set rd [redis_deferring_client]
r del blist target
r rpush target bar
$rd brpoplpush blist target 0
after 1000
wait_for_condition 100 10 {
[s blocked_clients] == 1
} else {
fail "Timeout waiting for blocked clients"
}
r rpush blist foo
assert_equal foo [$rd read]
assert_equal {foo} [r lrange target 0 -1]
assert_equal {foo bar} [r lrange target 0 -1]
}
test "BRPOPLPUSH with a client BLPOPing the target list" {
set rd [redis_deferring_client]
set rd2 [redis_deferring_client]
r del blist target
$rd2 blpop target 0
$rd brpoplpush blist target 0
after 1000
r rpush blist foo
assert_equal foo [$rd read]
assert_equal {target foo} [$rd2 read]
assert_equal 0 [r exists target]
foreach wherefrom {left right} {
foreach whereto {left right} {
test "BLMOVE $wherefrom $whereto with zero timeout should block indefinitely" {
set rd [redis_deferring_client]
r del blist target
r rpush target bar
$rd blmove blist target $wherefrom $whereto 0
wait_for_condition 100 10 {
[s blocked_clients] == 1
} else {
fail "Timeout waiting for blocked clients"
}
r rpush blist foo
assert_equal foo [$rd read]
if {$whereto eq "right"} {
assert_equal {bar foo} [r lrange target 0 -1]
} else {
assert_equal {foo bar} [r lrange target 0 -1]
}
}
}
}
foreach wherefrom {left right} {
foreach whereto {left right} {
test "BLMOVE ($wherefrom, $whereto) with a client BLPOPing the target list" {
set rd [redis_deferring_client]
set rd2 [redis_deferring_client]
r del blist target
$rd2 blpop target 0
$rd blmove blist target $wherefrom $whereto 0
wait_for_condition 100 10 {
[s blocked_clients] == 2
} else {
fail "Timeout waiting for blocked clients"
}
r rpush blist foo
assert_equal foo [$rd read]
assert_equal {target foo} [$rd2 read]
assert_equal 0 [r exists target]
}
}
}
test "BRPOPLPUSH with wrong source type" {
@@ -318,7 +405,11 @@ start_server {
r del blist target
r set target nolist
$rd brpoplpush blist target 0
after 1000
wait_for_condition 100 10 {
[s blocked_clients] == 1
} else {
fail "Timeout waiting for blocked clients"
}
r rpush blist foo
assert_error "WRONGTYPE*" {$rd read}
assert_equal {foo} [r lrange blist 0 -1]
@@ -348,14 +439,14 @@ start_server {
assert_equal {foo} [r lrange target2 0 -1]
}
test "Linked BRPOPLPUSH" {
test "Linked LMOVEs" {
set rd1 [redis_deferring_client]
set rd2 [redis_deferring_client]
r del list1 list2 list3
$rd1 brpoplpush list1 list2 0
$rd2 brpoplpush list2 list3 0
$rd1 blmove list1 list2 right left 0
$rd2 blmove list2 list3 left right 0
r rpush list1 foo
@@ -444,7 +535,16 @@ start_server {
set rd [redis_deferring_client]
$rd brpoplpush foo_list bar_list 1
after 2000
wait_for_condition 100 10 {
[s blocked_clients] == 1
} else {
fail "Timeout waiting for blocked client"
}
wait_for_condition 500 10 {
[s blocked_clients] == 0
} else {
fail "Timeout waiting for client to unblock"
}
$rd read
} {}
@@ -669,6 +769,29 @@ start_server {
assert_encoding quicklist mylist2
}
foreach wherefrom {left right} {
foreach whereto {left right} {
test "LMOVE $wherefrom $whereto base case - $type" {
r del mylist1 mylist2
if {$wherefrom eq "right"} {
create_list mylist1 "c d $large a"
} else {
create_list mylist1 "a $large c d"
}
assert_equal a [r lmove mylist1 mylist2 $wherefrom $whereto]
assert_equal $large [r lmove mylist1 mylist2 $wherefrom $whereto]
assert_equal "c d" [r lrange mylist1 0 -1]
if {$whereto eq "right"} {
assert_equal "a $large" [r lrange mylist2 0 -1]
} else {
assert_equal "$large a" [r lrange mylist2 0 -1]
}
assert_encoding quicklist mylist2
}
}
}
test "RPOPLPUSH with the same list as src and dst - $type" {
create_list mylist "a $large c"
assert_equal "a $large c" [r lrange mylist 0 -1]
@@ -676,6 +799,26 @@ start_server {
assert_equal "c a $large" [r lrange mylist 0 -1]
}
foreach wherefrom {left right} {
foreach whereto {left right} {
test "LMOVE $wherefrom $whereto with the same list as src and dst - $type" {
if {$wherefrom eq "right"} {
create_list mylist "a $large c"
assert_equal "a $large c" [r lrange mylist 0 -1]
} else {
create_list mylist "c a $large"
assert_equal "c a $large" [r lrange mylist 0 -1]
}
assert_equal c [r lmove mylist mylist $wherefrom $whereto]
if {$whereto eq "right"} {
assert_equal "a $large c" [r lrange mylist 0 -1]
} else {
assert_equal "c a $large" [r lrange mylist 0 -1]
}
}
}
}
foreach {othertype otherlarge} [array get largevalue] {
test "RPOPLPUSH with $type source and existing target $othertype" {
create_list srclist "a b c $large"
@@ -691,6 +834,35 @@ start_server {
assert_encoding quicklist dstlist
}
}
foreach wherefrom {left right} {
foreach whereto {left right} {
test "LMOVE $wherefrom $whereto with $type source and existing target $othertype" {
create_list dstlist "$otherlarge"
if {$wherefrom eq "right"} {
create_list srclist "a b c $large"
} else {
create_list srclist "$large c a b"
}
assert_equal $large [r lmove srclist dstlist $wherefrom $whereto]
assert_equal c [r lmove srclist dstlist $wherefrom $whereto]
assert_equal "a b" [r lrange srclist 0 -1]
if {$whereto eq "right"} {
assert_equal "$otherlarge $large c" [r lrange dstlist 0 -1]
} else {
assert_equal "c $large $otherlarge" [r lrange dstlist 0 -1]
}
# When we lmoved a large value, dstlist should be
# converted to the same encoding as srclist.
if {$type eq "linkedlist"} {
assert_encoding quicklist dstlist
}
}
}
}
}
}
@@ -789,6 +961,12 @@ start_server {
assert_equal {} [r lrange nosuchkey 0 1]
}
test {LRANGE with start > end yields an empty array for backward compatibility} {
create_list mylist "1 2 3"
assert_equal {} [r lrange mylist 1 0]
assert_equal {} [r lrange mylist -1 -2]
}
foreach {type large} [array get largevalue] {
proc trim_list {type min max} {
upvar 1 large large
@@ -890,4 +1068,93 @@ start_server {
$rd2 close
r ping
} {PONG}
test "client unblock tests" {
r del l
set rd [redis_deferring_client]
$rd client id
set id [$rd read]
# test default args
$rd blpop l 0
wait_for_blocked_client
r client unblock $id
assert_equal {} [$rd read]
# test with timeout
$rd blpop l 0
wait_for_blocked_client
r client unblock $id TIMEOUT
assert_equal {} [$rd read]
# test with error
$rd blpop l 0
wait_for_blocked_client
r client unblock $id ERROR
catch {[$rd read]} e
assert_equal $e "UNBLOCKED client unblocked via CLIENT UNBLOCK"
# test with invalid client id
catch {[r client unblock asd]} e
assert_equal $e "ERR value is not an integer or out of range"
# test with non blocked client
set myid [r client id]
catch {[r client unblock $myid]} e
assert_equal $e {invalid command name "0"}
# finally, see the this client and list are still functional
$rd blpop l 0
wait_for_blocked_client
r lpush l foo
assert_equal {l foo} [$rd read]
} {}
test {List ziplist of various encodings} {
r del k
r lpush k 127 ;# ZIP_INT_8B
r lpush k 32767 ;# ZIP_INT_16B
r lpush k 2147483647 ;# ZIP_INT_32B
r lpush k 9223372036854775808 ;# ZIP_INT_64B
r lpush k 0 ;# ZIP_INT_IMM_MIN
r lpush k 12 ;# ZIP_INT_IMM_MAX
r lpush k [string repeat x 31] ;# ZIP_STR_06B
r lpush k [string repeat x 8191] ;# ZIP_STR_14B
r lpush k [string repeat x 65535] ;# ZIP_STR_32B
set k [r lrange k 0 -1]
set dump [r dump k]
r config set sanitize-dump-payload no
r restore kk 0 $dump
set kk [r lrange kk 0 -1]
# try some forward and backward searches to make sure all encodings
# can be traversed
assert_equal [r lindex kk 5] {9223372036854775808}
assert_equal [r lindex kk -5] {0}
assert_equal [r lpos kk foo rank 1] {}
assert_equal [r lpos kk foo rank -1] {}
# make sure the values are right
assert_equal $k $kk
assert_equal [lpop k] [string repeat x 65535]
assert_equal [lpop k] [string repeat x 8191]
assert_equal [lpop k] [string repeat x 31]
set _ $k
} {12 0 9223372036854775808 2147483647 32767 127}
test {List ziplist of various encodings - sanitize dump} {
r config set sanitize-dump-payload yes
r restore kk 0 $dump replace
set k [r lrange k 0 -1]
set kk [r lrange kk 0 -1]
# make sure the values are right
assert_equal $k $kk
assert_equal [lpop k] [string repeat x 65535]
assert_equal [lpop k] [string repeat x 8191]
assert_equal [lpop k] [string repeat x 31]
set _ $k
} {12 0 9223372036854775808 2147483647 32767 127}
}
+70 -3
View File
@@ -9,7 +9,7 @@ start_server {
foreach entry $entries { r sadd $key $entry }
}
test {SADD, SCARD, SISMEMBER, SMEMBERS basics - regular set} {
test {SADD, SCARD, SISMEMBER, SMISMEMBER, SMEMBERS basics - regular set} {
create_set myset {foo}
assert_encoding hashtable myset
assert_equal 1 [r sadd myset bar]
@@ -18,10 +18,15 @@ start_server {
assert_equal 1 [r sismember myset foo]
assert_equal 1 [r sismember myset bar]
assert_equal 0 [r sismember myset bla]
assert_equal {1} [r smismember myset foo]
assert_equal {1 1} [r smismember myset foo bar]
assert_equal {1 0} [r smismember myset foo bla]
assert_equal {0 1} [r smismember myset bla foo]
assert_equal {0} [r smismember myset bla]
assert_equal {bar foo} [lsort [r smembers myset]]
}
test {SADD, SCARD, SISMEMBER, SMEMBERS basics - intset} {
test {SADD, SCARD, SISMEMBER, SMISMEMBER, SMEMBERS basics - intset} {
create_set myset {17}
assert_encoding intset myset
assert_equal 1 [r sadd myset 16]
@@ -30,9 +35,33 @@ start_server {
assert_equal 1 [r sismember myset 16]
assert_equal 1 [r sismember myset 17]
assert_equal 0 [r sismember myset 18]
assert_equal {1} [r smismember myset 16]
assert_equal {1 1} [r smismember myset 16 17]
assert_equal {1 0} [r smismember myset 16 18]
assert_equal {0 1} [r smismember myset 18 16]
assert_equal {0} [r smismember myset 18]
assert_equal {16 17} [lsort [r smembers myset]]
}
test {SMISMEMBER against non set} {
r lpush mylist foo
assert_error WRONGTYPE* {r smismember mylist bar}
}
test {SMISMEMBER non existing key} {
assert_equal {0} [r smismember myset1 foo]
assert_equal {0 0} [r smismember myset1 foo bar]
}
test {SMISMEMBER requires one or more members} {
r del zmscoretest
r zadd zmscoretest 10 x
r zadd zmscoretest 20 y
catch {r smismember zmscoretest} e
assert_match {*ERR*wrong*number*arg*} $e
}
test {SADD against non set} {
r lpush mylist foo
assert_error WRONGTYPE* {r sadd mylist bar}
@@ -49,6 +78,7 @@ start_server {
create_set myset {213244124402402314402033402}
assert_encoding hashtable myset
assert_equal 1 [r sismember myset 213244124402402314402033402]
assert_equal {1} [r smismember myset 213244124402402314402033402]
}
test "SADD overflows the maximum allowed integers in an intset" {
@@ -471,7 +501,7 @@ start_server {
set iterations 1000
while {$iterations != 0} {
incr iterations -1
set res [r srandmember myset -10]
set res [r srandmember myset $size]
foreach ele $res {
set auxset($ele) 1
}
@@ -485,6 +515,43 @@ start_server {
}
}
foreach {type contents} {
hashtable {
1 5 10 50 125
MARY PATRICIA LINDA BARBARA ELIZABETH
}
intset {
0 1 2 3 4 5 6 7 8 9
}
} {
test "SRANDMEMBER histogram distribution - $type" {
create_set myset $contents
unset -nocomplain myset
array set myset {}
foreach ele [r smembers myset] {
set myset($ele) 1
}
# Use negative count (PATH 1).
set res [r srandmember myset -1000]
assert_equal [check_histogram_distribution $res 0.05 0.15] true
# Use positive count (both PATH 3 and PATH 4).
foreach size {8 2} {
unset -nocomplain allkey
set iterations [expr {1000 / $size}]
while {$iterations != 0} {
incr iterations -1
set res [r srandmember myset $size]
foreach ele $res {
lappend allkey $ele
}
}
assert_equal [check_histogram_distribution $allkey 0.05 0.15] true
}
}
}
proc setup_move {} {
r del myset3 myset4
create_set myset1 {1 a b}
+299 -35
View File
@@ -27,7 +27,7 @@ start_server {
# and not the element "foo bar" which was pre existing in the
# stream (see previous test)
set reply [
r XREADGROUP GROUP mygroup client-1 STREAMS mystream ">"
r XREADGROUP GROUP mygroup consumer-1 STREAMS mystream ">"
]
assert {[llength [lindex $reply 0 1]] == 2}
lindex $reply 0 1 0 1
@@ -39,13 +39,13 @@ start_server {
r XADD mystream * d 4
# Read a few elements using a different consumer name
set reply [
r XREADGROUP GROUP mygroup client-2 STREAMS mystream ">"
r XREADGROUP GROUP mygroup consumer-2 STREAMS mystream ">"
]
assert {[llength [lindex $reply 0 1]] == 2}
assert {[lindex $reply 0 1 0 1] eq {c 3}}
set r1 [r XREADGROUP GROUP mygroup client-1 COUNT 10 STREAMS mystream 0]
set r2 [r XREADGROUP GROUP mygroup client-2 COUNT 10 STREAMS mystream 0]
set r1 [r XREADGROUP GROUP mygroup consumer-1 COUNT 10 STREAMS mystream 0]
set r2 [r XREADGROUP GROUP mygroup consumer-2 COUNT 10 STREAMS mystream 0]
assert {[lindex $r1 0 1 0 1] eq {a 1}}
assert {[lindex $r2 0 1 0 1] eq {c 3}}
}
@@ -56,9 +56,9 @@ start_server {
for {set j 0} {$j < 4} {incr j} {
set item [lindex $pending $j]
if {$j < 2} {
set owner client-1
set owner consumer-1
} else {
set owner client-2
set owner consumer-2
}
assert {[lindex $item 1] eq $owner}
assert {[lindex $item 1] eq $owner}
@@ -66,16 +66,47 @@ start_server {
}
test {XPENDING can return single consumer items} {
set pending [r XPENDING mystream mygroup - + 10 client-1]
set pending [r XPENDING mystream mygroup - + 10 consumer-1]
assert {[llength $pending] == 2}
}
test {XACK is able to remove items from the client/group PEL} {
set pending [r XPENDING mystream mygroup - + 10 client-1]
test {XPENDING only group} {
set pending [r XPENDING mystream mygroup]
assert {[llength $pending] == 4}
}
test {XPENDING with IDLE} {
after 20
set pending [r XPENDING mystream mygroup IDLE 99999999 - + 10 consumer-1]
assert {[llength $pending] == 0}
set pending [r XPENDING mystream mygroup IDLE 1 - + 10 consumer-1]
assert {[llength $pending] == 2}
set pending [r XPENDING mystream mygroup IDLE 99999999 - + 10]
assert {[llength $pending] == 0}
set pending [r XPENDING mystream mygroup IDLE 1 - + 10]
assert {[llength $pending] == 4}
}
test {XPENDING with exclusive range intervals works as expected} {
set pending [r XPENDING mystream mygroup - + 10]
assert {[llength $pending] == 4}
set startid [lindex [lindex $pending 0] 0]
set endid [lindex [lindex $pending 3] 0]
set expending [r XPENDING mystream mygroup ($startid ($endid 10]
assert {[llength $expending] == 2}
for {set j 0} {$j < 2} {incr j} {
set itemid [lindex [lindex $expending $j] 0]
assert {$itemid ne $startid}
assert {$itemid ne $endid}
}
}
test {XACK is able to remove items from the consumer/group PEL} {
set pending [r XPENDING mystream mygroup - + 10 consumer-1]
set id1 [lindex $pending 0 0]
set id2 [lindex $pending 1 0]
assert {[r XACK mystream mygroup $id1] eq 1}
set pending [r XPENDING mystream mygroup - + 10 client-1]
set pending [r XPENDING mystream mygroup - + 10 consumer-1]
assert {[llength $pending] == 1}
set id [lindex $pending 0 0]
assert {$id eq $id2}
@@ -211,41 +242,52 @@ start_server {
set id3 [r XADD mystream * c 3]
r XGROUP CREATE mystream mygroup 0
# Client 1 reads item 1 from the stream without acknowledgements.
# Client 2 then claims pending item 1 from the PEL of client 1
# Consumer 1 reads item 1 from the stream without acknowledgements.
# Consumer 2 then claims pending item 1 from the PEL of consumer 1
set reply [
r XREADGROUP GROUP mygroup client1 count 1 STREAMS mystream >
r XREADGROUP GROUP mygroup consumer1 count 1 STREAMS mystream >
]
assert {[llength [lindex $reply 0 1 0 1]] == 2}
assert {[lindex $reply 0 1 0 1] eq {a 1}}
r debug sleep 0.2
# make sure the entry is present in both the gorup, and the right consumer
assert {[llength [r XPENDING mystream mygroup - + 10]] == 1}
assert {[llength [r XPENDING mystream mygroup - + 10 consumer1]] == 1}
assert {[llength [r XPENDING mystream mygroup - + 10 consumer2]] == 0}
after 200
set reply [
r XCLAIM mystream mygroup client2 10 $id1
r XCLAIM mystream mygroup consumer2 10 $id1
]
assert {[llength [lindex $reply 0 1]] == 2}
assert {[lindex $reply 0 1] eq {a 1}}
# Client 1 reads another 2 items from stream
r XREADGROUP GROUP mygroup client1 count 2 STREAMS mystream >
r debug sleep 0.2
# make sure the entry is present in both the gorup, and the right consumer
assert {[llength [r XPENDING mystream mygroup - + 10]] == 1}
assert {[llength [r XPENDING mystream mygroup - + 10 consumer1]] == 0}
assert {[llength [r XPENDING mystream mygroup - + 10 consumer2]] == 1}
# Delete item 2 from the stream. Now client 1 has PEL that contains
# only item 3. Try to use client 2 to claim the deleted item 2
# from the PEL of client 1, this should return nil
# Consumer 1 reads another 2 items from stream
r XREADGROUP GROUP mygroup consumer1 count 2 STREAMS mystream >
after 200
# Delete item 2 from the stream. Now consumer 1 has PEL that contains
# only item 3. Try to use consumer 2 to claim the deleted item 2
# from the PEL of consumer 1, this should return nil
r XDEL mystream $id2
set reply [
r XCLAIM mystream mygroup client2 10 $id2
r XCLAIM mystream mygroup consumer2 10 $id2
]
assert {[llength $reply] == 1}
assert_equal "" [lindex $reply 0]
# Delete item 3 from the stream. Now client 1 has PEL that is empty.
# Try to use client 2 to claim the deleted item 3 from the PEL
# of client 1, this should return nil
r debug sleep 0.2
# Delete item 3 from the stream. Now consumer 1 has PEL that is empty.
# Try to use consumer 2 to claim the deleted item 3 from the PEL
# of consumer 1, this should return nil
after 200
r XDEL mystream $id3
set reply [
r XCLAIM mystream mygroup client2 10 $id3
r XCLAIM mystream mygroup consumer2 10 $id3
]
assert {[llength $reply] == 1}
assert_equal "" [lindex $reply 0]
@@ -259,16 +301,16 @@ start_server {
set id3 [r XADD mystream * c 3]
r XGROUP CREATE mystream mygroup 0
# Client 1 reads item 1 from the stream without acknowledgements.
# Client 2 then claims pending item 1 from the PEL of client 1
# Consumer 1 reads item 1 from the stream without acknowledgements.
# Consumer 2 then claims pending item 1 from the PEL of consumer 1
set reply [
r XREADGROUP GROUP mygroup client1 count 1 STREAMS mystream >
r XREADGROUP GROUP mygroup consumer1 count 1 STREAMS mystream >
]
assert {[llength [lindex $reply 0 1 0 1]] == 2}
assert {[lindex $reply 0 1 0 1] eq {a 1}}
r debug sleep 0.2
after 200
set reply [
r XCLAIM mystream mygroup client2 10 $id1
r XCLAIM mystream mygroup consumer2 10 $id1
]
assert {[llength [lindex $reply 0 1]] == 2}
assert {[lindex $reply 0 1] eq {a 1}}
@@ -279,10 +321,10 @@ start_server {
assert {[llength [lindex $reply 0]] == 4}
assert {[lindex $reply 0 3] == 2}
# Client 3 then claims pending item 1 from the PEL of client 2 using JUSTID
r debug sleep 0.2
# Consumer 3 then claims pending item 1 from the PEL of consumer 2 using JUSTID
after 200
set reply [
r XCLAIM mystream mygroup client3 10 $id1 JUSTID
r XCLAIM mystream mygroup consumer3 10 $id1 JUSTID
]
assert {[llength $reply] == 1}
assert {[lindex $reply 0] eq $id1}
@@ -294,6 +336,132 @@ start_server {
assert {[lindex $reply 0 3] == 2}
}
test {XCLAIM same consumer} {
# Add 3 items into the stream, and create a consumer group
r del mystream
set id1 [r XADD mystream * a 1]
set id2 [r XADD mystream * b 2]
set id3 [r XADD mystream * c 3]
r XGROUP CREATE mystream mygroup 0
set reply [r XREADGROUP GROUP mygroup consumer1 count 1 STREAMS mystream >]
assert {[llength [lindex $reply 0 1 0 1]] == 2}
assert {[lindex $reply 0 1 0 1] eq {a 1}}
after 200
# re-claim with the same consumer that already has it
assert {[llength [r XCLAIM mystream mygroup consumer1 10 $id1]] == 1}
# make sure the entry is still in the PEL
set reply [r XPENDING mystream mygroup - + 10]
assert {[llength $reply] == 1}
assert {[lindex $reply 0 1] eq {consumer1}}
}
test {XAUTOCLAIM can claim PEL items from another consumer} {
# Add 3 items into the stream, and create a consumer group
r del mystream
set id1 [r XADD mystream * a 1]
set id2 [r XADD mystream * b 2]
set id3 [r XADD mystream * c 3]
r XGROUP CREATE mystream mygroup 0
# Consumer 1 reads item 1 from the stream without acknowledgements.
# Consumer 2 then claims pending item 1 from the PEL of consumer 1
set reply [r XREADGROUP GROUP mygroup consumer1 count 1 STREAMS mystream >]
assert_equal [llength [lindex $reply 0 1 0 1]] 2
assert_equal [lindex $reply 0 1 0 1] {a 1}
after 200
set reply [r XAUTOCLAIM mystream mygroup consumer2 10 - COUNT 1]
assert_equal [llength $reply] 2
assert_equal [lindex $reply 0] $id1
assert_equal [llength [lindex $reply 1]] 1
assert_equal [llength [lindex $reply 1 0]] 2
assert_equal [llength [lindex $reply 1 0 1]] 2
assert_equal [lindex $reply 1 0 1] {a 1}
# Consumer 1 reads another 2 items from stream
r XREADGROUP GROUP mygroup consumer1 count 2 STREAMS mystream >
# For min-idle-time
after 200
# Delete item 2 from the stream. Now consumer 1 has PEL that contains
# only item 3. Try to use consumer 2 to claim the deleted item 2
# from the PEL of consumer 1, this should return nil
r XDEL mystream $id2
set reply [r XAUTOCLAIM mystream mygroup consumer2 10 - COUNT 2]
# id1 is self-claimed here but not id2 ('count' was set to 2)
assert_equal [llength $reply] 2
assert_equal [lindex $reply 0] $id2
assert_equal [llength [lindex $reply 1]] 2
assert_equal [llength [lindex $reply 1 0]] 2
assert_equal [llength [lindex $reply 1 0 1]] 2
assert_equal [lindex $reply 1 0 1] {a 1}
assert_equal [lindex $reply 1 1] ""
# Delete item 3 from the stream. Now consumer 1 has PEL that is empty.
# Try to use consumer 2 to claim the deleted item 3 from the PEL
# of consumer 1, this should return nil
after 200
r XDEL mystream $id3
set reply [r XAUTOCLAIM mystream mygroup consumer2 10 - JUSTID]
# id1 is self-claimed here but not id2 and id3 ('count' is default 100)
# we also test the JUSTID modifier here. note that, when using JUSTID,
# deleted entries are returned in reply (consistent with XCLAIM).
assert_equal [llength $reply] 2
assert_equal [lindex $reply 0] "0-0"
assert_equal [llength [lindex $reply 1]] 3
assert_equal [lindex $reply 1 0] $id1
assert_equal [lindex $reply 1 1] $id2
assert_equal [lindex $reply 1 2] $id3
}
test {XAUTOCLAIM as an iterator} {
# Add 5 items into the stream, and create a consumer group
r del mystream
set id1 [r XADD mystream * a 1]
set id2 [r XADD mystream * b 2]
set id3 [r XADD mystream * c 3]
set id4 [r XADD mystream * d 4]
set id5 [r XADD mystream * e 5]
r XGROUP CREATE mystream mygroup 0
# Read 5 messages into consumer1
r XREADGROUP GROUP mygroup consumer1 count 90 STREAMS mystream >
# For min-idle-time
after 200
# Claim 2 entries
set reply [r XAUTOCLAIM mystream mygroup consumer2 10 - COUNT 2]
assert_equal [llength $reply] 2
set cursor [lindex $reply 0]
assert_equal $cursor $id2
assert_equal [llength [lindex $reply 1]] 2
assert_equal [llength [lindex $reply 1 0 1]] 2
assert_equal [lindex $reply 1 0 1] {a 1}
# Claim 2 more entries
set reply [r XAUTOCLAIM mystream mygroup consumer2 10 ($cursor COUNT 2]
assert_equal [llength $reply] 2
set cursor [lindex $reply 0]
assert_equal $cursor $id4
assert_equal [llength [lindex $reply 1]] 2
assert_equal [llength [lindex $reply 1 0 1]] 2
assert_equal [lindex $reply 1 0 1] {c 3}
# Claim last entry
set reply [r XAUTOCLAIM mystream mygroup consumer2 10 ($cursor COUNT 2]
assert_equal [llength $reply] 2
set cursor [lindex $reply 0]
assert_equal $cursor {0-0}
assert_equal [llength [lindex $reply 1]] 1
assert_equal [llength [lindex $reply 1 0 1]] 2
assert_equal [lindex $reply 1 0 1] {e 5}
}
test {XINFO FULL output} {
r del x
r XADD x 100 a 1
@@ -328,6 +496,102 @@ start_server {
assert_equal [lindex $reply 9] "{100-0 {a 1}}"
}
test {XGROUP CREATECONSUMER: create consumer if does not exist} {
r del mystream
r XGROUP CREATE mystream mygroup $ MKSTREAM
r XADD mystream * f v
set reply [r xinfo groups mystream]
set group_info [lindex $reply 0]
set n_consumers [lindex $group_info 3]
assert_equal $n_consumers 0 ;# consumers number in cg
# create consumer using XREADGROUP
r XREADGROUP GROUP mygroup Alice COUNT 1 STREAMS mystream >
set reply [r xinfo groups mystream]
set group_info [lindex $reply 0]
set n_consumers [lindex $group_info 3]
assert_equal $n_consumers 1 ;# consumers number in cg
set reply [r xinfo consumers mystream mygroup]
set consumer_info [lindex $reply 0]
assert_equal [lindex $consumer_info 1] "Alice" ;# consumer name
# create group using XGROUP CREATECONSUMER when Alice already exists
set created [r XGROUP CREATECONSUMER mystream mygroup Alice]
assert_equal $created 0
# create group using XGROUP CREATECONSUMER when Bob does not exist
set created [r XGROUP CREATECONSUMER mystream mygroup Bob]
assert_equal $created 1
set reply [r xinfo groups mystream]
set group_info [lindex $reply 0]
set n_consumers [lindex $group_info 3]
assert_equal $n_consumers 2 ;# consumers number in cg
set reply [r xinfo consumers mystream mygroup]
set consumer_info [lindex $reply 0]
assert_equal [lindex $consumer_info 1] "Alice" ;# consumer name
set consumer_info [lindex $reply 1]
assert_equal [lindex $consumer_info 1] "Bob" ;# consumer name
}
test {XGROUP CREATECONSUMER: group must exist} {
r del mystream
r XADD mystream * f v
assert_error "*NOGROUP*" {r XGROUP CREATECONSUMER mystream mygroup consumer}
}
start_server {tags {"stream"} overrides {appendonly yes aof-use-rdb-preamble no appendfsync always}} {
test {XREADGROUP with NOACK creates consumer} {
r del mystream
r XGROUP CREATE mystream mygroup $ MKSTREAM
r XADD mystream * f1 v1
r XREADGROUP GROUP mygroup Alice NOACK STREAMS mystream ">"
set rd [redis_deferring_client]
$rd XREADGROUP GROUP mygroup Bob BLOCK 0 NOACK STREAMS mystream ">"
r XADD mystream * f2 v2
set grpinfo [r xinfo groups mystream]
r debug loadaof
assert {[r xinfo groups mystream] == $grpinfo}
set reply [r xinfo consumers mystream mygroup]
set consumer_info [lindex $reply 0]
assert_equal [lindex $consumer_info 1] "Alice" ;# consumer name
set consumer_info [lindex $reply 1]
assert_equal [lindex $consumer_info 1] "Bob" ;# consumer name
}
test {Consumer without PEL is present in AOF after AOFRW} {
r del mystream
r XGROUP CREATE mystream mygroup $ MKSTREAM
r XADD mystream * f v
r XREADGROUP GROUP mygroup Alice NOACK STREAMS mystream ">"
set rd [redis_deferring_client]
$rd XREADGROUP GROUP mygroup Bob BLOCK 0 NOACK STREAMS mystream ">"
r XGROUP CREATECONSUMER mystream mygroup Charlie
set grpinfo [lindex [r xinfo groups mystream] 0]
r bgrewriteaof
waitForBgrewriteaof r
r debug loadaof
set curr_grpinfo [lindex [r xinfo groups mystream] 0]
assert {$curr_grpinfo == $grpinfo}
set n_consumers [lindex $grpinfo 3]
# Bob should be created only when there will be new data for this consumer
assert_equal $n_consumers 2
set reply [r xinfo consumers mystream mygroup]
set consumer_info [lindex $reply 0]
assert_equal [lindex $consumer_info 1] "Alice"
set consumer_info [lindex $reply 1]
assert_equal [lindex $consumer_info 1] "Charlie"
}
}
start_server {} {
set master [srv -1 client]
set master_host [srv -1 host]
+221 -1
View File
@@ -94,6 +94,7 @@ start_server {
r XADD mystream MAXLEN 5 * yitem $j
}
}
assert {[r xlen mystream] == 5}
set res [r xrange mystream - +]
set expected 995
foreach r $res {
@@ -102,6 +103,75 @@ start_server {
}
}
test {XADD with MAXLEN option and the '=' argument} {
r DEL mystream
for {set j 0} {$j < 1000} {incr j} {
if {rand() < 0.9} {
r XADD mystream MAXLEN = 5 * xitem $j
} else {
r XADD mystream MAXLEN = 5 * yitem $j
}
}
assert {[r XLEN mystream] == 5}
}
test {XADD with MAXLEN option and the '~' argument} {
r DEL mystream
for {set j 0} {$j < 1000} {incr j} {
if {rand() < 0.9} {
r XADD mystream MAXLEN ~ 555 * xitem $j
} else {
r XADD mystream MAXLEN ~ 555 * yitem $j
}
}
assert {[r XLEN mystream] == 600}
}
test {XADD with NOMKSTREAM option} {
r DEL mystream
assert_equal "" [r XADD mystream NOMKSTREAM * item 1 value a]
assert_equal 0 [r EXISTS mystream]
r XADD mystream * item 1 value a
r XADD mystream NOMKSTREAM * item 2 value b
assert_equal 2 [r XLEN mystream]
set items [r XRANGE mystream - +]
assert_equal [lindex $items 0 1] {item 1 value a}
assert_equal [lindex $items 1 1] {item 2 value b}
}
test {XADD with MINID option} {
r DEL mystream
for {set j 1} {$j < 1001} {incr j} {
set minid 1000
if {$j >= 5} {
set minid [expr {$j-5}]
}
if {rand() < 0.9} {
r XADD mystream MINID $minid $j xitem $j
} else {
r XADD mystream MINID $minid $j yitem $j
}
}
assert {[r xlen mystream] == 6}
set res [r xrange mystream - +]
set expected 995
foreach r $res {
assert {[lindex $r 1 1] == $expected}
incr expected
}
}
test {XTRIM with MINID option} {
r DEL mystream
r XADD mystream 1-0 f v
r XADD mystream 2-0 f v
r XADD mystream 3-0 f v
r XADD mystream 4-0 f v
r XADD mystream 5-0 f v
r XTRIM mystream MINID = 3-0
assert_equal [r XRANGE mystream - +] {{3-0 {f v}} {4-0 {f v}} {5-0 {f v}}}
}
test {XADD mass insertion and XLEN} {
r DEL mystream
r multi
@@ -156,6 +226,32 @@ start_server {
assert {[r xrange mystream - +] == [lreverse [r xrevrange mystream + -]]}
}
test {XRANGE exclusive ranges} {
set ids {0-1 0-18446744073709551615 1-0 42-0 42-42
18446744073709551615-18446744073709551614
18446744073709551615-18446744073709551615}
set total [llength $ids]
r multi
r DEL vipstream
foreach id $ids {
r XADD vipstream $id foo bar
}
r exec
assert {[llength [r xrange vipstream - +]] == $total}
assert {[llength [r xrange vipstream ([lindex $ids 0] +]] == $total-1}
assert {[llength [r xrange vipstream - ([lindex $ids $total-1]]] == $total-1}
assert {[llength [r xrange vipstream (0-1 (1-0]] == 1}
assert {[llength [r xrange vipstream (1-0 (42-42]] == 1}
catch {r xrange vipstream (- +} e
assert_match {ERR*} $e
catch {r xrange vipstream - (+} e
assert_match {ERR*} $e
catch {r xrange vipstream (18446744073709551615-18446744073709551615 +} e
assert_match {ERR*} $e
catch {r xrange vipstream - (0-0} e
assert_match {ERR*} $e
}
test {XREAD with non empty stream} {
set res [r XREAD COUNT 1 STREAMS mystream 0-0]
assert {[lrange [lindex $res 0 1 0 1] 0 1] eq {item 0}}
@@ -360,7 +456,6 @@ start_server {
r del x
set rd [redis_deferring_client]
$rd XREAD BLOCK 0 STREAMS x 1-18446744073709551615
after 100
r XADD x 1-1 f v
r XADD x 1-18446744073709551615 f v
r XADD x 2-1 f v
@@ -374,6 +469,69 @@ start_server {
r XADD x * f2 v2
assert_equal [r XRANGE x - +] {{2577343934890-18446744073709551615 {f v}} {2577343934891-0 {f2 v2}}}
}
test {XTRIM with MAXLEN option basic test} {
r DEL mystream
for {set j 0} {$j < 1000} {incr j} {
if {rand() < 0.9} {
r XADD mystream * xitem $j
} else {
r XADD mystream * yitem $j
}
}
r XTRIM mystream MAXLEN 666
assert {[r XLEN mystream] == 666}
r XTRIM mystream MAXLEN = 555
assert {[r XLEN mystream] == 555}
r XTRIM mystream MAXLEN ~ 444
assert {[r XLEN mystream] == 500}
r XTRIM mystream MAXLEN ~ 400
assert {[r XLEN mystream] == 400}
}
test {XADD with LIMIT consecutive calls} {
r del mystream
r config set stream-node-max-entries 10
for {set j 0} {$j < 100} {incr j} {
r XADD mystream * xitem v
}
r XADD mystream MAXLEN ~ 55 LIMIT 30 * xitem v
assert {[r xlen mystream] == 71}
r XADD mystream MAXLEN ~ 55 LIMIT 30 * xitem v
assert {[r xlen mystream] == 62}
r config set stream-node-max-entries 100
}
test {XTRIM with ~ is limited} {
r del mystream
r config set stream-node-max-entries 1
for {set j 0} {$j < 102} {incr j} {
r XADD mystream * xitem v
}
r XTRIM mystream MAXLEN ~ 1
assert {[r xlen mystream] == 2}
r config set stream-node-max-entries 100
}
test {XTRIM without ~ is not limited} {
r del mystream
r config set stream-node-max-entries 1
for {set j 0} {$j < 102} {incr j} {
r XADD mystream * xitem v
}
r XTRIM mystream MAXLEN 1
assert {[r xlen mystream] == 1}
r config set stream-node-max-entries 100
}
test {XTRIM without ~ and with LIMIT} {
r del mystream
r config set stream-node-max-entries 1
for {set j 0} {$j < 102} {incr j} {
r XADD mystream * xitem v
}
assert_error ERR* {r XTRIM mystream MAXLEN 1 LIMIT 30}
}
}
start_server {tags {"stream"} overrides {appendonly yes}} {
@@ -391,6 +549,22 @@ start_server {tags {"stream"} overrides {appendonly yes}} {
}
}
start_server {tags {"stream"} overrides {appendonly yes}} {
test {XADD with MINID > lastid can propagate correctly} {
for {set j 0} {$j < 100} {incr j} {
set id [expr {$j+1}]
r XADD mystream $id xitem v
}
r XADD mystream MINID 1 * xitem v
incr j
assert {[r xlen mystream] == $j}
r debug loadaof
r XADD mystream * xitem v
incr j
assert {[r xlen mystream] == $j}
}
}
start_server {tags {"stream"} overrides {appendonly yes}} {
test {XADD with ~ MAXLEN can propagate correctly} {
for {set j 0} {$j < 100} {incr j} {
@@ -407,6 +581,52 @@ start_server {tags {"stream"} overrides {appendonly yes}} {
}
}
start_server {tags {"stream"} overrides {appendonly yes stream-node-max-entries 10}} {
test {XADD with ~ MAXLEN and LIMIT can propagate correctly} {
for {set j 0} {$j < 100} {incr j} {
r XADD mystream * xitem v
}
r XADD mystream MAXLEN ~ 55 LIMIT 30 * xitem v
assert {[r xlen mystream] == 71}
r config set stream-node-max-entries 1
r debug loadaof
r XADD mystream * xitem v
assert {[r xlen mystream] == 72}
}
}
start_server {tags {"stream"} overrides {appendonly yes}} {
test {XADD with ~ MINID can propagate correctly} {
for {set j 0} {$j < 100} {incr j} {
set id [expr {$j+1}]
r XADD mystream $id xitem v
}
r XADD mystream MINID ~ $j * xitem v
incr j
assert {[r xlen mystream] == $j}
r config set stream-node-max-entries 1
r debug loadaof
r XADD mystream * xitem v
incr j
assert {[r xlen mystream] == $j}
}
}
start_server {tags {"stream"} overrides {appendonly yes stream-node-max-entries 10}} {
test {XADD with ~ MINID and LIMIT can propagate correctly} {
for {set j 0} {$j < 100} {incr j} {
set id [expr {$j+1}]
r XADD mystream $id xitem v
}
r XADD mystream MINID ~ 55 LIMIT 30 * xitem v
assert {[r xlen mystream] == 71}
r config set stream-node-max-entries 1
r debug loadaof
r XADD mystream * xitem v
assert {[r xlen mystream] == 72}
}
}
start_server {tags {"stream"} overrides {appendonly yes stream-node-max-entries 10}} {
test {XTRIM with ~ MAXLEN can propagate correctly} {
for {set j 0} {$j < 100} {incr j} {
+125
View File
@@ -102,6 +102,91 @@ start_server {tags {"string"}} {
assert_equal 20 [r get x]
}
test "GETEX EX option" {
r del foo
r set foo bar
r getex foo ex 10
assert_range [r ttl foo] 5 10
}
test "GETEX PX option" {
r del foo
r set foo bar
r getex foo px 10000
assert_range [r pttl foo] 5000 10000
}
test "GETEX EXAT option" {
r del foo
r set foo bar
r getex foo exat [expr [clock seconds] + 10]
assert_range [r ttl foo] 5 10
}
test "GETEX PXAT option" {
r del foo
r set foo bar
r getex foo pxat [expr [clock milliseconds] + 10000]
assert_range [r pttl foo] 5000 10000
}
test "GETEX PERSIST option" {
r del foo
r set foo bar ex 10
assert_range [r ttl foo] 5 10
r getex foo persist
assert_equal -1 [r ttl foo]
}
test "GETEX no option" {
r del foo
r set foo bar
r getex foo
assert_equal bar [r getex foo]
}
test "GETEX syntax errors" {
set ex {}
catch {r getex foo non-existent-option} ex
set ex
} {*syntax*}
test "GETEX no arguments" {
set ex {}
catch {r getex} ex
set ex
} {*wrong number of arguments*}
test "GETDEL command" {
r del foo
r set foo bar
assert_equal bar [r getdel foo ]
assert_equal {} [r getdel foo ]
}
test {GETDEL propagate as DEL command to replica} {
set repl [attach_to_replication_stream]
r set foo bar
r getdel foo
assert_replication_stream $repl {
{select *}
{set foo bar}
{del foo}
}
}
test {GETEX without argument does not propagate to replica} {
set repl [attach_to_replication_stream]
r set foo bar
r getex foo
r del foo
assert_replication_stream $repl {
{select *}
{set foo bar}
{del foo}
}
}
test {MGET} {
r flushdb
r set foo BAR
@@ -394,6 +479,35 @@ start_server {tags {"string"}} {
list $v1 $v2 [r get foo]
} {{} OK 2}
test {Extended SET GET option} {
r del foo
r set foo bar
set old_value [r set foo bar2 GET]
set new_value [r get foo]
list $old_value $new_value
} {bar bar2}
test {Extended SET GET option with no previous value} {
r del foo
set old_value [r set foo bar GET]
set new_value [r get foo]
list $old_value $new_value
} {{} bar}
test {Extended SET GET with NX option should result in syntax err} {
catch {r set foo bar NX GET} err1
catch {r set foo bar NX GET} err2
list $err1 $err2
} {*syntax err* *syntax err*}
test {Extended SET GET with incorrect type should result in wrong type error} {
r del foo
r rpush foo waffle
catch {r set foo bar GET} err1
assert_equal "waffle" [r rpop foo]
set err1
} {*WRONGTYPE*}
test {Extended SET EX option} {
r del foo
r set foo bar ex 10
@@ -408,6 +522,17 @@ start_server {tags {"string"}} {
assert {$ttl <= 10 && $ttl > 5}
}
test "Extended SET EXAT option" {
r del foo
r set foo bar exat [expr [clock seconds] + 10]
assert_range [r ttl foo] 5 10
}
test "Extended SET PXAT option" {
r del foo
r set foo bar pxat [expr [clock milliseconds] + 10000]
assert_range [r ttl foo] 5 10
}
test {Extended SET using multiple options at once} {
r set foo val
assert {[r set foo bar xx px 10000] eq {OK}}
+528
View File
@@ -7,6 +7,8 @@ start_server {tags {"zset"}} {
}
proc basics {encoding} {
set original_max_entries [lindex [r config get zset-max-ziplist-entries] 1]
set original_max_value [lindex [r config get zset-max-ziplist-value] 1]
if {$encoding == "ziplist"} {
r config set zset-max-ziplist-entries 128
r config set zset-max-ziplist-value 64
@@ -78,6 +80,46 @@ start_server {tags {"zset"}} {
assert {[r zscore ztmp y] == 21}
}
test "ZADD GT updates existing elements when new scores are greater" {
r del ztmp
r zadd ztmp 10 x 20 y 30 z
assert {[r zadd ztmp gt ch 5 foo 11 x 21 y 29 z] == 3}
assert {[r zcard ztmp] == 4}
assert {[r zscore ztmp x] == 11}
assert {[r zscore ztmp y] == 21}
assert {[r zscore ztmp z] == 30}
}
test "ZADD LT updates existing elements when new scores are lower" {
r del ztmp
r zadd ztmp 10 x 20 y 30 z
assert {[r zadd ztmp lt ch 5 foo 11 x 21 y 29 z] == 2}
assert {[r zcard ztmp] == 4}
assert {[r zscore ztmp x] == 10}
assert {[r zscore ztmp y] == 20}
assert {[r zscore ztmp z] == 29}
}
test "ZADD GT XX updates existing elements when new scores are greater and skips new elements" {
r del ztmp
r zadd ztmp 10 x 20 y 30 z
assert {[r zadd ztmp gt xx ch 5 foo 11 x 21 y 29 z] == 2}
assert {[r zcard ztmp] == 3}
assert {[r zscore ztmp x] == 11}
assert {[r zscore ztmp y] == 21}
assert {[r zscore ztmp z] == 30}
}
test "ZADD LT XX updates existing elements when new scores are lower and skips new elements" {
r del ztmp
r zadd ztmp 10 x 20 y 30 z
assert {[r zadd ztmp lt xx ch 5 foo 11 x 21 y 29 z] == 1}
assert {[r zcard ztmp] == 3}
assert {[r zscore ztmp x] == 10}
assert {[r zscore ztmp y] == 20}
assert {[r zscore ztmp z] == 29}
}
test "ZADD XX and NX are not compatible" {
r del ztmp
catch {r zadd ztmp xx nx 10 x} err
@@ -100,6 +142,24 @@ start_server {tags {"zset"}} {
assert {[r zscore ztmp b] == 200}
}
test "ZADD GT and NX are not compatible" {
r del ztmp
catch {r zadd ztmp gt nx 10 x} err
set err
} {ERR*}
test "ZADD LT and NX are not compatible" {
r del ztmp
catch {r zadd ztmp lt nx 10 x} err
set err
} {ERR*}
test "ZADD LT and GT are not compatible" {
r del ztmp
catch {r zadd ztmp lt gt 10 x} err
set err
} {ERR*}
test "ZADD INCR works like ZINCRBY" {
r del ztmp
r zadd ztmp 10 x 20 y 30 z
@@ -374,6 +434,7 @@ start_server {tags {"zset"}} {
create_default_zset
assert_equal {e 4 f 5} [r zrangebyscore zset 2 5 LIMIT 2 3 WITHSCORES]
assert_equal {d 3 c 2} [r zrevrangebyscore zset 5 2 LIMIT 2 3 WITHSCORES]
assert_equal {} [r zrangebyscore zset 2 5 LIMIT 12 13 WITHSCORES]
}
test "ZRANGEBYSCORE with non-value min or max" {
@@ -554,6 +615,13 @@ start_server {tags {"zset"}} {
assert_equal 0 [r exists dst_key]
}
test "ZUNION/ZINTER/ZDIFF against non-existing key - $encoding" {
r del zseta
assert_equal {} [r zunion 1 zseta]
assert_equal {} [r zinter 1 zseta]
assert_equal {} [r zdiff 1 zseta]
}
test "ZUNIONSTORE with empty set - $encoding" {
r del zseta zsetb
r zadd zseta 1 a
@@ -562,6 +630,15 @@ start_server {tags {"zset"}} {
r zrange zsetc 0 -1 withscores
} {a 1 b 2}
test "ZUNION/ZINTER/ZDIFF with empty set - $encoding" {
r del zseta zsetb
r zadd zseta 1 a
r zadd zseta 2 b
assert_equal {a 1 b 2} [r zunion 2 zseta zsetb withscores]
assert_equal {} [r zinter 2 zseta zsetb withscores]
assert_equal {a 1 b 2} [r zdiff 2 zseta zsetb withscores]
}
test "ZUNIONSTORE basics - $encoding" {
r del zseta zsetb zsetc
r zadd zseta 1 a
@@ -575,11 +652,30 @@ start_server {tags {"zset"}} {
assert_equal {a 1 b 3 d 3 c 5} [r zrange zsetc 0 -1 withscores]
}
test "ZUNION/ZINTER/ZDIFF with integer members - $encoding" {
r del zsetd zsetf
r zadd zsetd 1 1
r zadd zsetd 2 2
r zadd zsetd 3 3
r zadd zsetf 1 1
r zadd zsetf 3 3
r zadd zsetf 4 4
assert_equal {1 2 2 2 4 4 3 6} [r zunion 2 zsetd zsetf withscores]
assert_equal {1 2 3 6} [r zinter 2 zsetd zsetf withscores]
assert_equal {2 2} [r zdiff 2 zsetd zsetf withscores]
}
test "ZUNIONSTORE with weights - $encoding" {
assert_equal 4 [r zunionstore zsetc 2 zseta zsetb weights 2 3]
assert_equal {a 2 b 7 d 9 c 12} [r zrange zsetc 0 -1 withscores]
}
test "ZUNION with weights - $encoding" {
assert_equal {a 2 b 7 d 9 c 12} [r zunion 2 zseta zsetb weights 2 3 withscores]
assert_equal {b 7 c 12} [r zinter 2 zseta zsetb weights 2 3 withscores]
}
test "ZUNIONSTORE with a regular set and weights - $encoding" {
r del seta
r sadd seta a
@@ -595,21 +691,45 @@ start_server {tags {"zset"}} {
assert_equal {a 1 b 1 c 2 d 3} [r zrange zsetc 0 -1 withscores]
}
test "ZUNION/ZINTER with AGGREGATE MIN - $encoding" {
assert_equal {a 1 b 1 c 2 d 3} [r zunion 2 zseta zsetb aggregate min withscores]
assert_equal {b 1 c 2} [r zinter 2 zseta zsetb aggregate min withscores]
}
test "ZUNIONSTORE with AGGREGATE MAX - $encoding" {
assert_equal 4 [r zunionstore zsetc 2 zseta zsetb aggregate max]
assert_equal {a 1 b 2 c 3 d 3} [r zrange zsetc 0 -1 withscores]
}
test "ZUNION/ZINTER with AGGREGATE MAX - $encoding" {
assert_equal {a 1 b 2 c 3 d 3} [r zunion 2 zseta zsetb aggregate max withscores]
assert_equal {b 2 c 3} [r zinter 2 zseta zsetb aggregate max withscores]
}
test "ZINTERSTORE basics - $encoding" {
assert_equal 2 [r zinterstore zsetc 2 zseta zsetb]
assert_equal {b 3 c 5} [r zrange zsetc 0 -1 withscores]
}
test "ZINTER basics - $encoding" {
assert_equal {b 3 c 5} [r zinter 2 zseta zsetb withscores]
}
test "ZINTER RESP3 - $encoding" {
r hello 3
assert_equal {{b 3.0} {c 5.0}} [r zinter 2 zseta zsetb withscores]
}
r hello 2
test "ZINTERSTORE with weights - $encoding" {
assert_equal 2 [r zinterstore zsetc 2 zseta zsetb weights 2 3]
assert_equal {b 7 c 12} [r zrange zsetc 0 -1 withscores]
}
test "ZINTER with weights - $encoding" {
assert_equal {b 7 c 12} [r zinter 2 zseta zsetb weights 2 3 withscores]
}
test "ZINTERSTORE with a regular set and weights - $encoding" {
r del seta
r sadd seta a
@@ -665,6 +785,80 @@ start_server {tags {"zset"}} {
}
}
test "ZDIFFSTORE basics - $encoding" {
assert_equal 1 [r zdiffstore zsetc 2 zseta zsetb]
assert_equal {a 1} [r zrange zsetc 0 -1 withscores]
}
test "ZDIFF basics - $encoding" {
assert_equal {a 1} [r zdiff 2 zseta zsetb withscores]
}
test "ZDIFFSTORE with a regular set - $encoding" {
r del seta
r sadd seta a
r sadd seta b
r sadd seta c
assert_equal 1 [r zdiffstore zsetc 2 seta zsetb]
assert_equal {a 1} [r zrange zsetc 0 -1 withscores]
}
test "ZDIFF subtracting set from itself - $encoding" {
assert_equal 0 [r zdiffstore zsetc 2 zseta zseta]
assert_equal {} [r zrange zsetc 0 -1 withscores]
}
test "ZDIFF algorithm 1 - $encoding" {
r del zseta zsetb zsetc
r zadd zseta 1 a
r zadd zseta 2 b
r zadd zseta 3 c
r zadd zsetb 1 b
r zadd zsetb 2 c
r zadd zsetb 3 d
assert_equal 1 [r zdiffstore zsetc 2 zseta zsetb]
assert_equal {a 1} [r zrange zsetc 0 -1 withscores]
}
test "ZDIFF algorithm 2 - $encoding" {
r del zseta zsetb zsetc zsetd zsete
r zadd zseta 1 a
r zadd zseta 2 b
r zadd zseta 3 c
r zadd zseta 5 e
r zadd zsetb 1 b
r zadd zsetc 1 c
r zadd zsetd 1 d
assert_equal 2 [r zdiffstore zsete 4 zseta zsetb zsetc zsetd]
assert_equal {a 1 e 5} [r zrange zsete 0 -1 withscores]
}
test "ZDIFF fuzzing" {
for {set j 0} {$j < 100} {incr j} {
unset -nocomplain s
array set s {}
set args {}
set num_sets [expr {[randomInt 10]+1}]
for {set i 0} {$i < $num_sets} {incr i} {
set num_elements [randomInt 100]
r del zset_$i
lappend args zset_$i
while {$num_elements} {
set ele [randomValue]
r zadd zset_$i [randomInt 100] $ele
if {$i == 0} {
set s($ele) x
} else {
unset -nocomplain s($ele)
}
incr num_elements -1
}
}
set result [lsort [r zdiff [llength $args] {*}$args]]
assert_equal $result [lsort [array names s]]
}
}
test "Basic ZPOP with a single key - $encoding" {
r del zset
assert_equal {} [r zpopmin zset]
@@ -733,6 +927,9 @@ start_server {tags {"zset"}} {
assert_equal 0 [r zcard z1]
assert_equal 1 [r zcard z2]
}
r config set zset-max-ziplist-entries $original_max_entries
r config set zset-max-ziplist-value $original_max_value
}
basics ziplist
@@ -781,11 +978,57 @@ start_server {tags {"zset"}} {
}
}
test "ZUNIONSTORE/ZINTERSTORE/ZDIFFSTORE error if using WITHSCORES " {
assert_error "*ERR*syntax*" {r zunionstore foo 2 zsetd zsetf withscores}
assert_error "*ERR*syntax*" {r zinterstore foo 2 zsetd zsetf withscores}
assert_error "*ERR*syntax*" {r zdiffstore foo 2 zsetd zsetf withscores}
}
test {ZMSCORE retrieve} {
r del zmscoretest
r zadd zmscoretest 10 x
r zadd zmscoretest 20 y
r zmscore zmscoretest x y
} {10 20}
test {ZMSCORE retrieve from empty set} {
r del zmscoretest
r zmscore zmscoretest x y
} {{} {}}
test {ZMSCORE retrieve with missing member} {
r del zmscoretest
r zadd zmscoretest 10 x
r zmscore zmscoretest x y
} {10 {}}
test {ZMSCORE retrieve single member} {
r del zmscoretest
r zadd zmscoretest 10 x
r zadd zmscoretest 20 y
r zmscore zmscoretest x
} {10}
test {ZMSCORE retrieve requires one or more members} {
r del zmscoretest
r zadd zmscoretest 10 x
r zadd zmscoretest 20 y
catch {r zmscore zmscoretest} e
assert_match {*ERR*wrong*number*arg*} $e
}
test "ZSET commands don't accept the empty strings as valid score" {
assert_error "*not*float*" {r zadd myzset "" abc}
}
proc stressers {encoding} {
set original_max_entries [lindex [r config get zset-max-ziplist-entries] 1]
set original_max_value [lindex [r config get zset-max-ziplist-value] 1]
if {$encoding == "ziplist"} {
# Little extra to allow proper fuzzing in the sorting stresser
r config set zset-max-ziplist-entries 256
@@ -815,6 +1058,21 @@ start_server {tags {"zset"}} {
}
}
test "ZMSCORE - $encoding" {
r del zscoretest
set aux {}
for {set i 0} {$i < $elements} {incr i} {
set score [expr rand()]
lappend aux $score
r zadd zscoretest $score $i
}
assert_encoding $encoding zscoretest
for {set i 0} {$i < $elements} {incr i} {
assert_equal [lindex $aux $i] [r zmscore zscoretest $i]
}
}
test "ZSCORE after a DEBUG RELOAD - $encoding" {
r del zscoretest
set aux {}
@@ -1195,6 +1453,8 @@ start_server {tags {"zset"}} {
r zadd zset 0 foo
assert_equal {zset foo 0} [$rd read]
}
r config set zset-max-ziplist-entries $original_max_entries
r config set zset-max-ziplist-value $original_max_value
}
tags {"slow"} {
@@ -1227,4 +1487,272 @@ start_server {tags {"zset"}} {
}
r config set zset-max-ziplist-entries $original_max
}
test {ZRANGESTORE basic} {
r flushall
r zadd z1 1 a 2 b 3 c 4 d
set res [r zrangestore z2 z1 0 -1]
assert_equal $res 4
r zrange z2 0 -1 withscores
} {a 1 b 2 c 3 d 4}
test {ZRANGESTORE RESP3} {
r hello 3
r zrange z2 0 -1 withscores
} {{a 1.0} {b 2.0} {c 3.0} {d 4.0}}
r hello 2
test {ZRANGESTORE range} {
set res [r zrangestore z2 z1 1 2]
assert_equal $res 2
r zrange z2 0 -1 withscores
} {b 2 c 3}
test {ZRANGESTORE BYLEX} {
set res [r zrangestore z2 z1 \[b \[c BYLEX]
assert_equal $res 2
r zrange z2 0 -1 withscores
} {b 2 c 3}
test {ZRANGESTORE BYSCORE} {
set res [r zrangestore z2 z1 1 2 BYSCORE]
assert_equal $res 2
r zrange z2 0 -1 withscores
} {a 1 b 2}
test {ZRANGESTORE BYSCORE LIMIT} {
set res [r zrangestore z2 z1 0 5 BYSCORE LIMIT 0 2]
assert_equal $res 2
r zrange z2 0 -1 withscores
} {a 1 b 2}
test {ZRANGESTORE BYSCORE REV LIMIT} {
set res [r zrangestore z2 z1 5 0 BYSCORE REV LIMIT 0 2]
assert_equal $res 2
r zrange z2 0 -1 withscores
} {c 3 d 4}
test {ZRANGE BYSCORE REV LIMIT} {
r zrange z1 5 0 BYSCORE REV LIMIT 0 2 WITHSCORES
} {d 4 c 3}
test {ZRANGESTORE - empty range} {
set res [r zrangestore z2 z1 5 6]
assert_equal $res 0
r exists z2
} {0}
test {ZRANGESTORE BYLEX - empty range} {
set res [r zrangestore z2 z1 \[f \[g BYLEX]
assert_equal $res 0
r exists z2
} {0}
test {ZRANGESTORE BYSCORE - empty range} {
set res [r zrangestore z2 z1 5 6 BYSCORE]
assert_equal $res 0
r exists z2
} {0}
test {ZRANGE BYLEX} {
r zrange z1 \[b \[c BYLEX
} {b c}
test {ZRANGESTORE invalid syntax} {
catch {r zrangestore z2 z1 0 -1 limit 1 2} err
assert_match "*syntax*" $err
catch {r zrangestore z2 z1 0 -1 WITHSCORES} err
assert_match "*syntax*" $err
}
test {ZRANGE invalid syntax} {
catch {r zrange z1 0 -1 limit 1 2} err
assert_match "*syntax*" $err
catch {r zrange z1 0 -1 BYLEX WITHSCORES} err
assert_match "*syntax*" $err
catch {r zrevrange z1 0 -1 BYSCORE} err
assert_match "*syntax*" $err
catch {r zrangebyscore z1 0 -1 REV} err
assert_match "*syntax*" $err
}
proc get_keys {l} {
set res {}
foreach {score key} $l {
lappend res $key
}
return $res
}
foreach {type contents} "ziplist {1 a 2 b 3 c} skiplist {1 a 2 b 3 [randstring 70 90 alpha]}" {
set original_max_value [lindex [r config get zset-max-ziplist-value] 1]
r config set zset-max-ziplist-value 10
create_zset myzset $contents
assert_encoding $type myzset
test "ZRANDMEMBER - $type" {
unset -nocomplain myzset
array set myzset {}
for {set i 0} {$i < 100} {incr i} {
set key [r zrandmember myzset]
set myzset($key) 1
}
assert_equal [lsort [get_keys $contents]] [lsort [array names myzset]]
}
r config set zset-max-ziplist-value $original_max_value
}
test "ZRANDMEMBER with RESP3" {
r hello 3
set res [r zrandmember myzset 3 withscores]
assert_equal [llength $res] 3
assert_equal [llength [lindex $res 1]] 2
set res [r zrandmember myzset 3]
assert_equal [llength $res] 3
assert_equal [llength [lindex $res 1]] 1
}
r hello 2
test "ZRANDMEMBER count of 0 is handled correctly" {
r zrandmember myzset 0
} {}
test "ZRANDMEMBER with <count> against non existing key" {
r zrandmember nonexisting_key 100
} {}
foreach {type contents} "
skiplist {1 a 2 b 3 c 4 d 5 e 6 f 7 g 7 h 9 i 10 [randstring 70 90 alpha]}
ziplist {1 a 2 b 3 c 4 d 5 e 6 f 7 g 7 h 9 i 10 j} " {
test "ZRANDMEMBER with <count> - $type" {
set original_max_value [lindex [r config get zset-max-ziplist-value] 1]
r config set zset-max-ziplist-value 10
create_zset myzset $contents
assert_encoding $type myzset
# create a dict for easy lookup
unset -nocomplain mydict
foreach {k v} [r zrange myzset 0 -1 withscores] {
dict append mydict $k $v
}
# We'll stress different parts of the code, see the implementation
# of ZRANDMEMBER for more information, but basically there are
# four different code paths.
# PATH 1: Use negative count.
# 1) Check that it returns repeated elements with and without values.
set res [r zrandmember myzset -20]
assert_equal [llength $res] 20
set res [r zrandmember myzset -1001]
assert_equal [llength $res] 1001
# again with WITHSCORES
set res [r zrandmember myzset -20 withscores]
assert_equal [llength $res] 40
set res [r zrandmember myzset -1001 withscores]
assert_equal [llength $res] 2002
# Test random uniform distribution
set res [r zrandmember myzset -1000]
assert_equal [check_histogram_distribution $res 0.05 0.15] true
# 2) Check that all the elements actually belong to the original zset.
foreach {key val} $res {
assert {[dict exists $mydict $key]}
}
# 3) Check that eventually all the elements are returned.
# Use both WITHSCORES and without
unset -nocomplain auxset
set iterations 1000
while {$iterations != 0} {
incr iterations -1
if {[expr {$iterations % 2}] == 0} {
set res [r zrandmember myzset -3 withscores]
foreach {key val} $res {
dict append auxset $key $val
}
} else {
set res [r zrandmember myzset -3]
foreach key $res {
dict append auxset $key $val
}
}
if {[lsort [dict keys $mydict]] eq
[lsort [dict keys $auxset]]} {
break;
}
}
assert {$iterations != 0}
# PATH 2: positive count (unique behavior) with requested size
# equal or greater than set size.
foreach size {10 20} {
set res [r zrandmember myzset $size]
assert_equal [llength $res] 10
assert_equal [lsort $res] [lsort [dict keys $mydict]]
# again with WITHSCORES
set res [r zrandmember myzset $size withscores]
assert_equal [llength $res] 20
assert_equal [lsort $res] [lsort $mydict]
}
# PATH 3: Ask almost as elements as there are in the set.
# In this case the implementation will duplicate the original
# set and will remove random elements up to the requested size.
#
# PATH 4: Ask a number of elements definitely smaller than
# the set size.
#
# We can test both the code paths just changing the size but
# using the same code.
foreach size {8 2} {
set res [r zrandmember myzset $size]
assert_equal [llength $res] $size
# again with WITHSCORES
set res [r zrandmember myzset $size withscores]
assert_equal [llength $res] [expr {$size * 2}]
# 1) Check that all the elements actually belong to the
# original set.
foreach ele [dict keys $res] {
assert {[dict exists $mydict $ele]}
}
# 2) Check that eventually all the elements are returned.
# Use both WITHSCORES and without
unset -nocomplain auxset
unset -nocomplain allkey
set iterations [expr {1000 / $size}]
set all_ele_return false
while {$iterations != 0} {
incr iterations -1
if {[expr {$iterations % 2}] == 0} {
set res [r zrandmember myzset $size withscores]
foreach {key value} $res {
dict append auxset $key $value
lappend allkey $key
}
} else {
set res [r zrandmember myzset $size]
foreach key $res {
dict append auxset $key
lappend allkey $key
}
}
if {[lsort [dict keys $mydict]] eq
[lsort [dict keys $auxset]]} {
set all_ele_return true
}
}
assert_equal $all_ele_return true
assert_equal [check_histogram_distribution $allkey 0.05 0.15] true
}
}
r config set zset-max-ziplist-value $original_max_value
}
}
+18 -5
View File
@@ -1,10 +1,11 @@
source tests/support/cli.tcl
start_server {tags {"wait"}} {
start_server {tags {"wait network"}} {
start_server {} {
set slave [srv 0 client]
set slave_host [srv 0 host]
set slave_port [srv 0 port]
set slave_pid [srv 0 pid]
set master [srv -1 client]
set master_host [srv -1 host]
set master_port [srv -1 port]
@@ -33,13 +34,25 @@ start_server {} {
}
test {WAIT should not acknowledge 1 additional copy if slave is blocked} {
set cmd [rediscli $slave_host $slave_port "debug sleep 5"]
exec {*}$cmd > /dev/null 2> /dev/null &
after 1000 ;# Give keydb-cli the time to execute the command.
exec kill -SIGSTOP $slave_pid
$master set foo 0
$master incr foo
$master incr foo
$master incr foo
assert {[$master wait 1 3000] == 0}
assert {[$master wait 1 1000] == 0}
exec kill -SIGCONT $slave_pid
assert {[$master wait 1 1000] == 1}
}
test {WAIT implicitly blocks on client pause since ACKs aren't sent} {
exec kill -SIGSTOP $slave_pid
$master multi
$master incr foo
$master client pause 10000 write
$master exec
assert {[$master wait 1 1000] == 0}
$master client unpause
exec kill -SIGCONT $slave_pid
assert {[$master wait 1 1000] == 1}
}
}}