instances.tcl 14.1 KB
Newer Older
1 2 3 4 5 6
# Multi-instance test framework.
# This is used in order to test Sentinel and Redis Cluster, and provides
# basic capabilities for spawning and handling N parallel Redis / Sentinel
# instances.
#
# Copyright (C) 2014 Salvatore Sanfilippo antirez@gmail.com
M
Matt Stancliff 已提交
7
# This software is released under the BSD License. See the COPYING file for
A
antirez 已提交
8 9 10 11 12
# more information.

package require Tcl 8.5

set tcl_precision 17
13 14 15 16
source ../support/redis.tcl
source ../support/util.tcl
source ../support/server.tcl
source ../support/test.tcl
A
antirez 已提交
17 18

set ::verbose 0
19
set ::valgrind 0
20
set ::pause_on_error 0
21
set ::simulate_error 0
22
set ::failed 0
A
antirez 已提交
23 24 25 26 27 28
set ::sentinel_instances {}
set ::redis_instances {}
set ::sentinel_base_port 20000
set ::redis_base_port 30000
set ::pids {} ; # We kill everything at exit
set ::dirs {} ; # We remove all the temp dirs at exit
29
set ::run_matching {} ; # If non empty, only tests matching pattern are run.
A
antirez 已提交
30

31 32
if {[catch {cd tmp}]} {
    puts "tmp directory not found."
A
antirez 已提交
33 34 35 36
    puts "Please run this test from the Redis source root."
    exit 1
}

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
# Execute the specified instance of the server specified by 'type', using
# the provided configuration file. Returns the PID of the process.
proc exec_instance {type cfgfile} {
    if {$type eq "redis"} {
        set prgname redis-server
    } elseif {$type eq "sentinel"} {
        set prgname redis-sentinel
    } else {
        error "Unknown instance type."
    }

    if {$::valgrind} {
        set pid [exec valgrind --track-origins=yes --suppressions=../../../src/valgrind.sup --show-reachable=no --show-possibly-lost=no --leak-check=full ../../../src/${prgname} $cfgfile &]
    } else {
        set pid [exec ../../../src/${prgname} $cfgfile &]
    }
    return $pid
}

A
antirez 已提交
56
# Spawn a redis or sentinel instance, depending on 'type'.
57
proc spawn_instance {type base_port count {conf {}}} {
A
antirez 已提交
58 59 60 61 62
    for {set j 0} {$j < $count} {incr j} {
        set port [find_available_port $base_port]
        incr base_port
        puts "Starting $type #$j at port $port"

63
        # Create a directory for this instance.
A
antirez 已提交
64 65 66 67 68
        set dirname "${type}_${j}"
        lappend ::dirs $dirname
        catch {exec rm -rf $dirname}
        file mkdir $dirname

69
        # Write the instance config file.
A
antirez 已提交
70 71 72 73 74
        set cfgfile [file join $dirname $type.conf]
        set cfg [open $cfgfile w]
        puts $cfg "port $port"
        puts $cfg "dir ./$dirname"
        puts $cfg "logfile log.txt"
75 76 77 78
        # Add additional config files
        foreach directive $conf {
            puts $cfg $directive
        }
A
antirez 已提交
79 80 81
        close $cfg

        # Finally exec it and remember the pid for later cleanup.
82
        set pid [exec_instance $type $cfgfile]
83
        lappend ::pids $pid
A
antirez 已提交
84 85 86 87 88 89 90

        # Check availability
        if {[server_is_up 127.0.0.1 $port 100] == 0} {
            abort_sentinel_test "Problems starting $type #$j: ping timeout"
        }

        # Push the instance into the right list
91 92
        set link [redis 127.0.0.1 $port]
        $link reconnect 1
93
        lappend ::${type}_instances [list \
94
            pid $pid \
A
antirez 已提交
95 96
            host 127.0.0.1 \
            port $port \
97
            link $link \
A
antirez 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
        ]
    }
}

proc cleanup {} {
    puts "Cleaning up..."
    foreach pid $::pids {
        catch {exec kill -9 $pid}
    }
    foreach dir $::dirs {
        catch {exec rm -rf $dir}
    }
}

proc abort_sentinel_test msg {
    puts "WARNING: Aborting the test."
    puts ">>>>>>>> $msg"
115
    if {$::pause_on_error} pause_on_error
A
antirez 已提交
116 117 118 119
    cleanup
    exit 1
}

120 121 122 123 124 125 126
proc parse_options {} {
    for {set j 0} {$j < [llength $::argv]} {incr j} {
        set opt [lindex $::argv $j]
        set val [lindex $::argv [expr $j+1]]
        if {$opt eq "--single"} {
            incr j
            set ::run_matching "*${val}*"
127 128
        } elseif {$opt eq "--pause-on-error"} {
            set ::pause_on_error 1
129 130
        } elseif {$opt eq "--fail"} {
            set ::simulate_error 1
131 132
        } elseif {$opt eq {--valgrind}} {
            set ::valgrind 1
133 134 135
        } elseif {$opt eq "--help"} {
            puts "Hello, I'm sentinel.tcl and I run Sentinel unit tests."
            puts "\nOptions:"
136 137
            puts "--single <pattern>      Only runs tests specified by pattern."
            puts "--pause-on-error        Pause for manual inspection on error."
138
            puts "--fail                  Simulate a test failure."
139
            puts "--help                  Shows this help."
140 141 142 143 144 145 146 147
            exit 0
        } else {
            puts "Unknown option $opt"
            exit 1
        }
    }
}

148 149 150 151
# If --pause-on-error option was passed at startup this function is called
# on error in order to give the developer a chance to understand more about
# the error condition while the instances are still running.
proc pause_on_error {} {
152
    puts ""
153
    puts [colorstr yellow "*** Please inspect the error now ***"]
154
    puts "\nType \"continue\" to resume the test, \"help\" for help screen.\n"
155 156
    while 1 {
        puts -nonewline "> "
157
        flush stdout
158 159 160 161 162
        set line [gets stdin]
        set argv [split $line " "]
        set cmd [lindex $argv 0]
        if {$cmd eq {continue}} {
            break
163 164 165 166 167 168 169 170
        } elseif {$cmd eq {show-redis-logs}} {
            set count 10
            if {[lindex $argv 1] ne {}} {set count [lindex $argv 1]}
            foreach_redis_id id {
                puts "=== REDIS $id ===="
                puts [exec tail -$count redis_$id/log.txt]
                puts "---------------------\n"
            }
171 172 173 174 175 176 177 178
        } elseif {$cmd eq {show-sentinel-logs}} {
            set count 10
            if {[lindex $argv 1] ne {}} {set count [lindex $argv 1]}
            foreach_sentinel_id id {
                puts "=== SENTINEL $id ===="
                puts [exec tail -$count sentinel_$id/log.txt]
                puts "---------------------\n"
            }
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
        } elseif {$cmd eq {ls}} {
            foreach_redis_id id {
                puts -nonewline "Redis $id"
                set errcode [catch {
                    set str {}
                    append str "@[RI $id tcp_port]: "
                    append str "[RI $id role] "
                    if {[RI $id role] eq {slave}} {
                        append str "[RI $id master_host]:[RI $id master_port]"
                    }
                    set str
                } retval]
                if {$errcode} {
                    puts " -- $retval"
                } else {
                    puts $retval
                }
            }
            foreach_sentinel_id id {
                puts -nonewline "Sentinel $id"
                set errcode [catch {
                    set str {}
                    append str "@[SI $id tcp_port]: "
                    append str "[join [S $id sentinel get-master-addr-by-name mymaster]]"
                    set str
                } retval]
                if {$errcode} {
                    puts " -- $retval"
                } else {
                    puts $retval
                }
            }
        } elseif {$cmd eq {help}} {
            puts "ls                     List Sentinel and Redis instances."
            puts "show-sentinel-logs \[N\] Show latest N lines of logs."
214
            puts "show-redis-logs \[N\]    Show latest N lines of logs."
215 216 217 218 219
            puts "S <id> cmd ... arg     Call command in Sentinel <id>."
            puts "R <id> cmd ... arg     Call command in Redis <id>."
            puts "SI <id> <field>        Show Sentinel <id> INFO <field>."
            puts "RI <id> <field>        Show Sentinel <id> INFO <field>."
            puts "continue               Resume test."
220 221
        } else {
            set errcode [catch {eval $line} retval]
222
            if {$retval ne {}} {puts "$retval"}
223
        }
224 225 226
    }
}

A
antirez 已提交
227 228 229
# We redefine 'test' as for Sentinel we don't use the server-client
# architecture for the test, everything is sequential.
proc test {descr code} {
230 231
    set ts [clock format [clock seconds] -format %H:%M:%S]
    puts -nonewline "$ts> $descr: "
A
antirez 已提交
232 233 234
    flush stdout

    if {[catch {set retval [uplevel 1 $code]} error]} {
235
        incr ::failed
A
antirez 已提交
236 237 238
        if {[string match "assertion:*" $error]} {
            set msg [string range $error 10 end]
            puts [colorstr red $msg]
239
            if {$::pause_on_error} pause_on_error
240 241
            puts "(Jumping to next unit after error)"
            return -code continue
A
antirez 已提交
242 243 244 245 246 247 248 249 250
        } else {
            # Re-raise, let handler up the stack take care of this.
            error $error $::errorInfo
        }
    } else {
        puts [colorstr green OK]
    }
}

251
# Execute all the units inside the 'tests' directory.
A
antirez 已提交
252
proc run_tests {} {
253
    set tests [lsort [glob ../tests/*]]
A
antirez 已提交
254
    foreach test $tests {
255 256 257
        if {$::run_matching ne {} && [string match $::run_matching $test] == 0} {
            continue
        }
258
        if {[file isdirectory $test]} continue
259
        puts [colorstr yellow "Testing unit: [lindex [file split $test] end]"]
A
antirez 已提交
260 261 262 263
        source $test
    }
}

264 265 266 267 268 269 270 271 272 273 274
# Print a message and exists with 0 / 1 according to zero or more failures.
proc end_tests {} {
    if {$::failed == 0} {
        puts "GOOD! No errors."
        exit 0
    } else {
        puts "WARNING $::failed tests faield."
        exit 1
    }
}

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
# The "S" command is used to interact with the N-th Sentinel.
# The general form is:
#
# S <sentinel-id> command arg arg arg ...
#
# Example to ping the Sentinel 0 (first instance): S 0 PING
proc S {n args} {
    set s [lindex $::sentinel_instances $n]
    [dict get $s link] {*}$args
}

# Like R but to chat with Redis instances.
proc R {n args} {
    set r [lindex $::redis_instances $n]
    [dict get $r link] {*}$args
}

292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
proc get_info_field {info field} {
    set fl [string length $field]
    append field :
    foreach line [split $info "\n"] {
        set line [string trim $line "\r\n "]
        if {[string range $line 0 $fl] eq $field} {
            return [string range $line [expr {$fl+1}] end]
        }
    }
    return {}
}

proc SI {n field} {
    get_info_field [S $n info] $field
}

proc RI {n field} {
    get_info_field [R $n info] $field
}

312
# Iterate over IDs of sentinel or redis instances.
313
proc foreach_instance_id {instances idvar code} {
314
    upvar 1 $idvar id
315 316 317 318
    for {set id 0} {$id < [llength $instances]} {incr id} {
        set errcode [catch {uplevel 1 $code} result]
        if {$errcode == 1} {
            error $result $::errorInfo $::errorCode
319 320
        } elseif {$errcode == 4} {
            continue
321 322
        } elseif {$errcode == 3} {
            break
323 324 325
        } elseif {$errcode != 0} {
            return -code $errcode $result
        }
326 327 328
    }
}

329 330 331 332 333
proc foreach_sentinel_id {idvar code} {
    set errcode [catch {uplevel 1 [list foreach_instance_id $::sentinel_instances $idvar $code]} result]
    return -code $errcode $result
}

334
proc foreach_redis_id {idvar code} {
335 336
    set errcode [catch {uplevel 1 [list foreach_instance_id $::redis_instances $idvar $code]} result]
    return -code $errcode $result
337 338
}

339 340 341 342 343
# Get the specific attribute of the specified instance type, id.
proc get_instance_attrib {type id attrib} {
    dict get [lindex [set ::${type}_instances] $id] $attrib
}

344 345 346 347 348 349 350
# Set the specific attribute of the specified instance type, id.
proc set_instance_attrib {type id attrib newval} {
    set d [lindex [set ::${type}_instances] $id]
    dict set d $attrib $newval
    lset ::${type}_instances $id $d
}

351 352 353 354 355 356 357 358
# Create a master-slave cluster of the given number of total instances.
# The first instance "0" is the master, all others are configured as
# slaves.
proc create_redis_master_slave_cluster n {
    foreach_redis_id id {
        if {$id == 0} {
            # Our master.
            R $id slaveof no one
359
            R $id flushall
360 361 362 363 364 365 366 367 368
        } elseif {$id < $n} {
            R $id slaveof [get_instance_attrib redis 0 host] \
                          [get_instance_attrib redis 0 port]
        } else {
            # Instances not part of the cluster.
            R $id slaveof no one
        }
    }
    # Wait for all the slaves to sync.
369
    wait_for_condition 1000 50 {
370 371 372 373 374 375
        [RI 0 connected_slaves] == ($n-1)
    } else {
        fail "Unable to create a master-slaves cluster."
    }
}

376 377 378 379 380 381 382 383 384
proc get_instance_id_by_port {type port} {
    foreach_${type}_id id {
        if {[get_instance_attrib $type $id port] == $port} {
            return $id
        }
    }
    fail "Instance $type port $port not found."
}

385 386 387 388 389 390 391 392
# Kill an instance of the specified type/id with SIGKILL.
# This function will mark the instance PID as -1 to remember that this instance
# is no longer running and will remove its PID from the list of pids that
# we kill at cleanup.
#
# The instance can be restarted with restart-instance.
proc kill_instance {type id} {
    set pid [get_instance_attrib $type $id pid]
393 394
    set port [get_instance_attrib $type $id port]

395 396 397
    if {$pid == -1} {
        error "You tried to kill $type $id twice."
    }
398

399 400 401 402 403 404
    exec kill -9 $pid
    set_instance_attrib $type $id pid -1
    set_instance_attrib $type $id link you_tried_to_talk_with_killed_instance

    # Remove the PID from the list of pids to kill at exit.
    set ::pids [lsearch -all -inline -not -exact $::pids $pid]
405 406 407 408 409 410 411 412 413 414 415 416 417

    # Wait for the port it was using to be available again, so that's not
    # an issue to start a new server ASAP with the same port.
    set retry 10
    while {[incr retry -1]} {
        set port_is_free [catch {set s [socket 127.0.01 $port]}]
        if {$port_is_free} break
        catch {close $s}
        after 1000
    }
    if {$retry == 0} {
        error "Port $port does not return available after killing instance."
    }
418 419
}

420 421 422
# Return true of the instance of the specified type/id is killed.
proc instance_is_killed {type id} {
    set pid [get_instance_attrib $type $id pid]
423
    expr {$pid == -1}
424 425
}

426 427 428 429 430 431 432 433
# Restart an instance previously killed by kill_instance
proc restart_instance {type id} {
    set dirname "${type}_${id}"
    set cfgfile [file join $dirname $type.conf]
    set port [get_instance_attrib $type $id port]

    # Execute the instance with its old setup and append the new pid
    # file for cleanup.
434
    set pid [exec_instance $type $cfgfile]
435
    set_instance_attrib $type $id pid $pid
436 437 438 439
    lappend ::pids $pid

    # Check that the instance is running
    if {[server_is_up 127.0.0.1 $port 100] == 0} {
440
        abort_sentinel_test "Problems starting $type #$id: ping timeout"
441 442 443
    }

    # Connect with it with a fresh link
444 445 446
    set link [redis 127.0.0.1 $port]
    $link reconnect 1
    set_instance_attrib $type $id link $link
447 448
}