instances.tcl 12 KB

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