instances.tcl 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. # Multi-instance test framework.
  2. # This is used in order to test Sentinel and Redis Cluster, and provides
  3. # basic capabilities for spawning and handling N parallel Redis / Sentinel
  4. # instances.
  5. #
  6. # Copyright (C) 2014 Salvatore Sanfilippo antirez@gmail.com
  7. # This software is released under the BSD License. See the COPYING file for
  8. # more information.
  9. package require Tcl 8.5
  10. set tcl_precision 17
  11. source ../support/redis.tcl
  12. source ../support/util.tcl
  13. source ../support/server.tcl
  14. source ../support/test.tcl
  15. set ::verbose 0
  16. set ::valgrind 0
  17. set ::pause_on_error 0
  18. set ::simulate_error 0
  19. set ::sentinel_instances {}
  20. set ::redis_instances {}
  21. set ::sentinel_base_port 20000
  22. set ::redis_base_port 30000
  23. set ::pids {} ; # We kill everything at exit
  24. set ::dirs {} ; # We remove all the temp dirs at exit
  25. set ::run_matching {} ; # If non empty, only tests matching pattern are run.
  26. if {[catch {cd tmp}]} {
  27. puts "tmp directory not found."
  28. puts "Please run this test from the Redis source root."
  29. exit 1
  30. }
  31. # Execute the specified instance of the server specified by 'type', using
  32. # the provided configuration file. Returns the PID of the process.
  33. proc exec_instance {type cfgfile} {
  34. if {$type eq "redis"} {
  35. set prgname redis-server
  36. } elseif {$type eq "sentinel"} {
  37. set prgname redis-sentinel
  38. } else {
  39. error "Unknown instance type."
  40. }
  41. if {$::valgrind} {
  42. set pid [exec valgrind --track-origins=yes --suppressions=../../../src/valgrind.sup --show-reachable=no --show-possibly-lost=no --leak-check=full ../../../src/${prgname} $cfgfile &]
  43. } else {
  44. set pid [exec ../../../src/${prgname} $cfgfile &]
  45. }
  46. return $pid
  47. }
  48. # Spawn a redis or sentinel instance, depending on 'type'.
  49. proc spawn_instance {type base_port count {conf {}}} {
  50. for {set j 0} {$j < $count} {incr j} {
  51. set port [find_available_port $base_port]
  52. incr base_port
  53. puts "Starting $type #$j at port $port"
  54. # Create a directory for this instance.
  55. set dirname "${type}_${j}"
  56. lappend ::dirs $dirname
  57. catch {exec rm -rf $dirname}
  58. file mkdir $dirname
  59. # Write the instance config file.
  60. set cfgfile [file join $dirname $type.conf]
  61. set cfg [open $cfgfile w]
  62. puts $cfg "port $port"
  63. puts $cfg "dir ./$dirname"
  64. puts $cfg "logfile log.txt"
  65. # Add additional config files
  66. foreach directive $conf {
  67. puts $cfg $directive
  68. }
  69. close $cfg
  70. # Finally exec it and remember the pid for later cleanup.
  71. set pid [exec_instance $type $cfgfile]
  72. lappend ::pids $pid
  73. # Check availability
  74. if {[server_is_up 127.0.0.1 $port 100] == 0} {
  75. abort_sentinel_test "Problems starting $type #$j: ping timeout"
  76. }
  77. # Push the instance into the right list
  78. set link [redis 127.0.0.1 $port]
  79. $link reconnect 1
  80. lappend ::${type}_instances [list \
  81. pid $pid \
  82. host 127.0.0.1 \
  83. port $port \
  84. link $link \
  85. ]
  86. }
  87. }
  88. proc cleanup {} {
  89. puts "Cleaning up..."
  90. foreach pid $::pids {
  91. catch {exec kill -9 $pid}
  92. }
  93. foreach dir $::dirs {
  94. catch {exec rm -rf $dir}
  95. }
  96. }
  97. proc abort_sentinel_test msg {
  98. puts "WARNING: Aborting the test."
  99. puts ">>>>>>>> $msg"
  100. if {$::pause_on_error} pause_on_error
  101. cleanup
  102. exit 1
  103. }
  104. proc parse_options {} {
  105. for {set j 0} {$j < [llength $::argv]} {incr j} {
  106. set opt [lindex $::argv $j]
  107. set val [lindex $::argv [expr $j+1]]
  108. if {$opt eq "--single"} {
  109. incr j
  110. set ::run_matching "*${val}*"
  111. } elseif {$opt eq "--pause-on-error"} {
  112. set ::pause_on_error 1
  113. } elseif {$opt eq "--fail"} {
  114. set ::simulate_error 1
  115. } elseif {$opt eq {--valgrind}} {
  116. set ::valgrind 1
  117. } elseif {$opt eq "--help"} {
  118. puts "Hello, I'm sentinel.tcl and I run Sentinel unit tests."
  119. puts "\nOptions:"
  120. puts "--single <pattern> Only runs tests specified by pattern."
  121. puts "--pause-on-error Pause for manual inspection on error."
  122. puts "--fail Simulate a test failure."
  123. puts "--help Shows this help."
  124. exit 0
  125. } else {
  126. puts "Unknown option $opt"
  127. exit 1
  128. }
  129. }
  130. }
  131. # If --pause-on-error option was passed at startup this function is called
  132. # on error in order to give the developer a chance to understand more about
  133. # the error condition while the instances are still running.
  134. proc pause_on_error {} {
  135. puts ""
  136. puts [colorstr yellow "*** Please inspect the error now ***"]
  137. puts "\nType \"continue\" to resume the test, \"help\" for help screen.\n"
  138. while 1 {
  139. puts -nonewline "> "
  140. flush stdout
  141. set line [gets stdin]
  142. set argv [split $line " "]
  143. set cmd [lindex $argv 0]
  144. if {$cmd eq {continue}} {
  145. break
  146. } elseif {$cmd eq {show-redis-logs}} {
  147. set count 10
  148. if {[lindex $argv 1] ne {}} {set count [lindex $argv 1]}
  149. foreach_redis_id id {
  150. puts "=== REDIS $id ===="
  151. puts [exec tail -$count redis_$id/log.txt]
  152. puts "---------------------\n"
  153. }
  154. } elseif {$cmd eq {show-sentinel-logs}} {
  155. set count 10
  156. if {[lindex $argv 1] ne {}} {set count [lindex $argv 1]}
  157. foreach_sentinel_id id {
  158. puts "=== SENTINEL $id ===="
  159. puts [exec tail -$count sentinel_$id/log.txt]
  160. puts "---------------------\n"
  161. }
  162. } elseif {$cmd eq {ls}} {
  163. foreach_redis_id id {
  164. puts -nonewline "Redis $id"
  165. set errcode [catch {
  166. set str {}
  167. append str "@[RI $id tcp_port]: "
  168. append str "[RI $id role] "
  169. if {[RI $id role] eq {slave}} {
  170. append str "[RI $id master_host]:[RI $id master_port]"
  171. }
  172. set str
  173. } retval]
  174. if {$errcode} {
  175. puts " -- $retval"
  176. } else {
  177. puts $retval
  178. }
  179. }
  180. foreach_sentinel_id id {
  181. puts -nonewline "Sentinel $id"
  182. set errcode [catch {
  183. set str {}
  184. append str "@[SI $id tcp_port]: "
  185. append str "[join [S $id sentinel get-master-addr-by-name mymaster]]"
  186. set str
  187. } retval]
  188. if {$errcode} {
  189. puts " -- $retval"
  190. } else {
  191. puts $retval
  192. }
  193. }
  194. } elseif {$cmd eq {help}} {
  195. puts "ls List Sentinel and Redis instances."
  196. puts "show-sentinel-logs \[N\] Show latest N lines of logs."
  197. puts "show-redis-logs \[N\] Show latest N lines of logs."
  198. puts "S <id> cmd ... arg Call command in Sentinel <id>."
  199. puts "R <id> cmd ... arg Call command in Redis <id>."
  200. puts "SI <id> <field> Show Sentinel <id> INFO <field>."
  201. puts "RI <id> <field> Show Sentinel <id> INFO <field>."
  202. puts "continue Resume test."
  203. } else {
  204. set errcode [catch {eval $line} retval]
  205. if {$retval ne {}} {puts "$retval"}
  206. }
  207. }
  208. }
  209. # We redefine 'test' as for Sentinel we don't use the server-client
  210. # architecture for the test, everything is sequential.
  211. proc test {descr code} {
  212. set ts [clock format [clock seconds] -format %H:%M:%S]
  213. puts -nonewline "$ts> $descr: "
  214. flush stdout
  215. if {[catch {set retval [uplevel 1 $code]} error]} {
  216. if {[string match "assertion:*" $error]} {
  217. set msg [string range $error 10 end]
  218. puts [colorstr red $msg]
  219. if {$::pause_on_error} pause_on_error
  220. puts "(Jumping to next unit after error)"
  221. return -code continue
  222. } else {
  223. # Re-raise, let handler up the stack take care of this.
  224. error $error $::errorInfo
  225. }
  226. } else {
  227. puts [colorstr green OK]
  228. }
  229. }
  230. proc run_tests {} {
  231. set tests [lsort [glob ../tests/*]]
  232. foreach test $tests {
  233. if {$::run_matching ne {} && [string match $::run_matching $test] == 0} {
  234. continue
  235. }
  236. if {[file isdirectory $test]} continue
  237. puts [colorstr yellow "Testing unit: [lindex [file split $test] end]"]
  238. source $test
  239. }
  240. }
  241. # The "S" command is used to interact with the N-th Sentinel.
  242. # The general form is:
  243. #
  244. # S <sentinel-id> command arg arg arg ...
  245. #
  246. # Example to ping the Sentinel 0 (first instance): S 0 PING
  247. proc S {n args} {
  248. set s [lindex $::sentinel_instances $n]
  249. [dict get $s link] {*}$args
  250. }
  251. # Like R but to chat with Redis instances.
  252. proc R {n args} {
  253. set r [lindex $::redis_instances $n]
  254. [dict get $r link] {*}$args
  255. }
  256. proc get_info_field {info field} {
  257. set fl [string length $field]
  258. append field :
  259. foreach line [split $info "\n"] {
  260. set line [string trim $line "\r\n "]
  261. if {[string range $line 0 $fl] eq $field} {
  262. return [string range $line [expr {$fl+1}] end]
  263. }
  264. }
  265. return {}
  266. }
  267. proc SI {n field} {
  268. get_info_field [S $n info] $field
  269. }
  270. proc RI {n field} {
  271. get_info_field [R $n info] $field
  272. }
  273. # Iterate over IDs of sentinel or redis instances.
  274. proc foreach_instance_id {instances idvar code} {
  275. upvar 1 $idvar id
  276. for {set id 0} {$id < [llength $instances]} {incr id} {
  277. set errcode [catch {uplevel 1 $code} result]
  278. if {$errcode == 1} {
  279. error $result $::errorInfo $::errorCode
  280. } elseif {$errcode == 4} {
  281. continue
  282. } elseif {$errcode == 3} {
  283. break
  284. } elseif {$errcode != 0} {
  285. return -code $errcode $result
  286. }
  287. }
  288. }
  289. proc foreach_sentinel_id {idvar code} {
  290. set errcode [catch {uplevel 1 [list foreach_instance_id $::sentinel_instances $idvar $code]} result]
  291. return -code $errcode $result
  292. }
  293. proc foreach_redis_id {idvar code} {
  294. set errcode [catch {uplevel 1 [list foreach_instance_id $::redis_instances $idvar $code]} result]
  295. return -code $errcode $result
  296. }
  297. # Get the specific attribute of the specified instance type, id.
  298. proc get_instance_attrib {type id attrib} {
  299. dict get [lindex [set ::${type}_instances] $id] $attrib
  300. }
  301. # Set the specific attribute of the specified instance type, id.
  302. proc set_instance_attrib {type id attrib newval} {
  303. set d [lindex [set ::${type}_instances] $id]
  304. dict set d $attrib $newval
  305. lset ::${type}_instances $id $d
  306. }
  307. # Create a master-slave cluster of the given number of total instances.
  308. # The first instance "0" is the master, all others are configured as
  309. # slaves.
  310. proc create_redis_master_slave_cluster n {
  311. foreach_redis_id id {
  312. if {$id == 0} {
  313. # Our master.
  314. R $id slaveof no one
  315. R $id flushall
  316. } elseif {$id < $n} {
  317. R $id slaveof [get_instance_attrib redis 0 host] \
  318. [get_instance_attrib redis 0 port]
  319. } else {
  320. # Instances not part of the cluster.
  321. R $id slaveof no one
  322. }
  323. }
  324. # Wait for all the slaves to sync.
  325. wait_for_condition 1000 50 {
  326. [RI 0 connected_slaves] == ($n-1)
  327. } else {
  328. fail "Unable to create a master-slaves cluster."
  329. }
  330. }
  331. proc get_instance_id_by_port {type port} {
  332. foreach_${type}_id id {
  333. if {[get_instance_attrib $type $id port] == $port} {
  334. return $id
  335. }
  336. }
  337. fail "Instance $type port $port not found."
  338. }
  339. # Kill an instance of the specified type/id with SIGKILL.
  340. # This function will mark the instance PID as -1 to remember that this instance
  341. # is no longer running and will remove its PID from the list of pids that
  342. # we kill at cleanup.
  343. #
  344. # The instance can be restarted with restart-instance.
  345. proc kill_instance {type id} {
  346. set pid [get_instance_attrib $type $id pid]
  347. set port [get_instance_attrib $type $id port]
  348. if {$pid == -1} {
  349. error "You tried to kill $type $id twice."
  350. }
  351. exec kill -9 $pid
  352. set_instance_attrib $type $id pid -1
  353. set_instance_attrib $type $id link you_tried_to_talk_with_killed_instance
  354. # Remove the PID from the list of pids to kill at exit.
  355. set ::pids [lsearch -all -inline -not -exact $::pids $pid]
  356. # Wait for the port it was using to be available again, so that's not
  357. # an issue to start a new server ASAP with the same port.
  358. set retry 10
  359. while {[incr retry -1]} {
  360. set port_is_free [catch {set s [socket 127.0.01 $port]}]
  361. if {$port_is_free} break
  362. catch {close $s}
  363. after 1000
  364. }
  365. if {$retry == 0} {
  366. error "Port $port does not return available after killing instance."
  367. }
  368. }
  369. # Return true of the instance of the specified type/id is killed.
  370. proc instance_is_killed {type id} {
  371. set pid [get_instance_attrib $type $id pid]
  372. expr {$pid == -1}
  373. }
  374. # Restart an instance previously killed by kill_instance
  375. proc restart_instance {type id} {
  376. set dirname "${type}_${id}"
  377. set cfgfile [file join $dirname $type.conf]
  378. set port [get_instance_attrib $type $id port]
  379. # Execute the instance with its old setup and append the new pid
  380. # file for cleanup.
  381. set pid [exec_instance $type $cfgfile]
  382. set_instance_attrib $type $id pid $pid
  383. lappend ::pids $pid
  384. # Check that the instance is running
  385. if {[server_is_up 127.0.0.1 $port 100] == 0} {
  386. abort_sentinel_test "Problems starting $type #$id: ping timeout"
  387. }
  388. # Connect with it with a fresh link
  389. set link [redis 127.0.0.1 $port]
  390. $link reconnect 1
  391. set_instance_attrib $type $id link $link
  392. }