2
0

instances.tcl 14 KB

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