redis-trib.rb 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696
  1. #!/usr/bin/env ruby
  2. # TODO (temporary here, we'll move this into the Github issues once
  3. # redis-trib initial implementation is completed).
  4. #
  5. # - Make sure that if the rehashing fails in the middle redis-trib will try
  6. # to recover.
  7. # - When redis-trib performs a cluster check, if it detects a slot move in
  8. # progress it should prompt the user to continue the move from where it
  9. # stopped.
  10. # - Gracefully handle Ctrl+C in move_slot to prompt the user if really stop
  11. # while rehashing, and performing the best cleanup possible if the user
  12. # forces the quit.
  13. # - When doing "fix" set a global Fix to true, and prompt the user to
  14. # fix the problem if automatically fixable every time there is something
  15. # to fix. For instance:
  16. # 1) If there is a node that pretend to receive a slot, or to migrate a
  17. # slot, but has no entries in that slot, fix it.
  18. # 2) If there is a node having keys in slots that are not owned by it
  19. # fix this condition moving the entries in the same node.
  20. # 3) Perform more possibly slow tests about the state of the cluster.
  21. # 4) When aborted slot migration is detected, fix it.
  22. require 'rubygems'
  23. require 'redis'
  24. ClusterHashSlots = 16384
  25. MigrateDefaultTimeout = 60000
  26. MigrateDefaultPipeline = 10
  27. RebalanceDefaultThreshold = 2
  28. $verbose = false
  29. def xputs(s)
  30. case s[0..2]
  31. when ">>>"
  32. color="29;1"
  33. when "[ER"
  34. color="31;1"
  35. when "[WA"
  36. color="31;1"
  37. when "[OK"
  38. color="32"
  39. when "[FA","***"
  40. color="33"
  41. else
  42. color=nil
  43. end
  44. color = nil if ENV['TERM'] != "xterm"
  45. print "\033[#{color}m" if color
  46. print s
  47. print "\033[0m" if color
  48. print "\n"
  49. end
  50. class ClusterNode
  51. def initialize(addr)
  52. s = addr.split("@")[0].split(":")
  53. if s.length < 2
  54. puts "Invalid IP or Port (given as #{addr}) - use IP:Port format"
  55. exit 1
  56. end
  57. port = s.pop # removes port from split array
  58. ip = s.join(":") # if s.length > 1 here, it's IPv6, so restore address
  59. @r = nil
  60. @info = {}
  61. @info[:host] = ip
  62. @info[:port] = port
  63. @info[:slots] = {}
  64. @info[:migrating] = {}
  65. @info[:importing] = {}
  66. @info[:replicate] = false
  67. @dirty = false # True if we need to flush slots info into node.
  68. @friends = []
  69. end
  70. def friends
  71. @friends
  72. end
  73. def slots
  74. @info[:slots]
  75. end
  76. def has_flag?(flag)
  77. @info[:flags].index(flag)
  78. end
  79. def to_s
  80. "#{@info[:host]}:#{@info[:port]}"
  81. end
  82. def connect(o={})
  83. return if @r
  84. print "Connecting to node #{self}: " if $verbose
  85. STDOUT.flush
  86. begin
  87. @r = Redis.new(:host => @info[:host], :port => @info[:port], :timeout => 60)
  88. @r.ping
  89. rescue
  90. xputs "[ERR] Sorry, can't connect to node #{self}"
  91. exit 1 if o[:abort]
  92. @r = nil
  93. end
  94. xputs "OK" if $verbose
  95. end
  96. def assert_cluster
  97. info = @r.info
  98. if !info["cluster_enabled"] || info["cluster_enabled"].to_i == 0
  99. xputs "[ERR] Node #{self} is not configured as a cluster node."
  100. exit 1
  101. end
  102. end
  103. def assert_empty
  104. if !(@r.cluster("info").split("\r\n").index("cluster_known_nodes:1")) ||
  105. (@r.info['db0'])
  106. xputs "[ERR] Node #{self} is not empty. Either the node already knows other nodes (check with CLUSTER NODES) or contains some key in database 0."
  107. exit 1
  108. end
  109. end
  110. def load_info(o={})
  111. self.connect
  112. nodes = @r.cluster("nodes").split("\n")
  113. nodes.each{|n|
  114. # name addr flags role ping_sent ping_recv link_status slots
  115. split = n.split
  116. name,addr,flags,master_id,ping_sent,ping_recv,config_epoch,link_status = split[0..6]
  117. slots = split[8..-1]
  118. info = {
  119. :name => name,
  120. :addr => addr,
  121. :flags => flags.split(","),
  122. :replicate => master_id,
  123. :ping_sent => ping_sent.to_i,
  124. :ping_recv => ping_recv.to_i,
  125. :link_status => link_status
  126. }
  127. info[:replicate] = false if master_id == "-"
  128. if info[:flags].index("myself")
  129. @info = @info.merge(info)
  130. @info[:slots] = {}
  131. slots.each{|s|
  132. if s[0..0] == '['
  133. if s.index("->-") # Migrating
  134. slot,dst = s[1..-1].split("->-")
  135. @info[:migrating][slot.to_i] = dst
  136. elsif s.index("-<-") # Importing
  137. slot,src = s[1..-1].split("-<-")
  138. @info[:importing][slot.to_i] = src
  139. end
  140. elsif s.index("-")
  141. start,stop = s.split("-")
  142. self.add_slots((start.to_i)..(stop.to_i))
  143. else
  144. self.add_slots((s.to_i)..(s.to_i))
  145. end
  146. } if slots
  147. @dirty = false
  148. @r.cluster("info").split("\n").each{|e|
  149. k,v=e.split(":")
  150. k = k.to_sym
  151. v.chop!
  152. if k != :cluster_state
  153. @info[k] = v.to_i
  154. else
  155. @info[k] = v
  156. end
  157. }
  158. elsif o[:getfriends]
  159. @friends << info
  160. end
  161. }
  162. end
  163. def add_slots(slots)
  164. slots.each{|s|
  165. @info[:slots][s] = :new
  166. }
  167. @dirty = true
  168. end
  169. def set_as_replica(node_id)
  170. @info[:replicate] = node_id
  171. @dirty = true
  172. end
  173. def flush_node_config
  174. return if !@dirty
  175. if @info[:replicate]
  176. begin
  177. @r.cluster("replicate",@info[:replicate])
  178. rescue
  179. # If the cluster did not already joined it is possible that
  180. # the slave does not know the master node yet. So on errors
  181. # we return ASAP leaving the dirty flag set, to flush the
  182. # config later.
  183. return
  184. end
  185. else
  186. new = []
  187. @info[:slots].each{|s,val|
  188. if val == :new
  189. new << s
  190. @info[:slots][s] = true
  191. end
  192. }
  193. @r.cluster("addslots",*new)
  194. end
  195. @dirty = false
  196. end
  197. def info_string
  198. # We want to display the hash slots assigned to this node
  199. # as ranges, like in: "1-5,8-9,20-25,30"
  200. #
  201. # Note: this could be easily written without side effects,
  202. # we use 'slots' just to split the computation into steps.
  203. # First step: we want an increasing array of integers
  204. # for instance: [1,2,3,4,5,8,9,20,21,22,23,24,25,30]
  205. slots = @info[:slots].keys.sort
  206. # As we want to aggregate adjacent slots we convert all the
  207. # slot integers into ranges (with just one element)
  208. # So we have something like [1..1,2..2, ... and so forth.
  209. slots.map!{|x| x..x}
  210. # Finally we group ranges with adjacent elements.
  211. slots = slots.reduce([]) {|a,b|
  212. if !a.empty? && b.first == (a[-1].last)+1
  213. a[0..-2] + [(a[-1].first)..(b.last)]
  214. else
  215. a + [b]
  216. end
  217. }
  218. # Now our task is easy, we just convert ranges with just one
  219. # element into a number, and a real range into a start-end format.
  220. # Finally we join the array using the comma as separator.
  221. slots = slots.map{|x|
  222. x.count == 1 ? x.first.to_s : "#{x.first}-#{x.last}"
  223. }.join(",")
  224. role = self.has_flag?("master") ? "M" : "S"
  225. if self.info[:replicate] and @dirty
  226. is = "S: #{self.info[:name]} #{self.to_s}"
  227. else
  228. is = "#{role}: #{self.info[:name]} #{self.to_s}\n"+
  229. " slots:#{slots} (#{self.slots.length} slots) "+
  230. "#{(self.info[:flags]-["myself"]).join(",")}"
  231. end
  232. if self.info[:replicate]
  233. is += "\n replicates #{info[:replicate]}"
  234. elsif self.has_flag?("master") && self.info[:replicas]
  235. is += "\n #{info[:replicas].length} additional replica(s)"
  236. end
  237. is
  238. end
  239. # Return a single string representing nodes and associated slots.
  240. # TODO: remove slaves from config when slaves will be handled
  241. # by Redis Cluster.
  242. def get_config_signature
  243. config = []
  244. @r.cluster("nodes").each_line{|l|
  245. s = l.split
  246. slots = s[8..-1].select {|x| x[0..0] != "["}
  247. next if slots.length == 0
  248. config << s[0]+":"+(slots.sort.join(","))
  249. }
  250. config.sort.join("|")
  251. end
  252. def info
  253. @info
  254. end
  255. def is_dirty?
  256. @dirty
  257. end
  258. def r
  259. @r
  260. end
  261. end
  262. class RedisTrib
  263. def initialize
  264. @nodes = []
  265. @fix = false
  266. @errors = []
  267. @timeout = MigrateDefaultTimeout
  268. end
  269. def check_arity(req_args, num_args)
  270. if ((req_args > 0 and num_args != req_args) ||
  271. (req_args < 0 and num_args < req_args.abs))
  272. xputs "[ERR] Wrong number of arguments for specified sub command"
  273. exit 1
  274. end
  275. end
  276. def add_node(node)
  277. @nodes << node
  278. end
  279. def reset_nodes
  280. @nodes = []
  281. end
  282. def cluster_error(msg)
  283. @errors << msg
  284. xputs msg
  285. end
  286. # Return the node with the specified ID or Nil.
  287. def get_node_by_name(name)
  288. @nodes.each{|n|
  289. return n if n.info[:name] == name.downcase
  290. }
  291. return nil
  292. end
  293. # Like get_node_by_name but the specified name can be just the first
  294. # part of the node ID as long as the prefix in unique across the
  295. # cluster.
  296. def get_node_by_abbreviated_name(name)
  297. l = name.length
  298. candidates = []
  299. @nodes.each{|n|
  300. if n.info[:name][0...l] == name.downcase
  301. candidates << n
  302. end
  303. }
  304. return nil if candidates.length != 1
  305. candidates[0]
  306. end
  307. # This function returns the master that has the least number of replicas
  308. # in the cluster. If there are multiple masters with the same smaller
  309. # number of replicas, one at random is returned.
  310. def get_master_with_least_replicas
  311. masters = @nodes.select{|n| n.has_flag? "master"}
  312. sorted = masters.sort{|a,b|
  313. a.info[:replicas].length <=> b.info[:replicas].length
  314. }
  315. sorted[0]
  316. end
  317. def check_cluster(opt={})
  318. xputs ">>> Performing Cluster Check (using node #{@nodes[0]})"
  319. show_nodes if !opt[:quiet]
  320. check_config_consistency
  321. check_open_slots
  322. check_slots_coverage
  323. end
  324. def show_cluster_info
  325. masters = 0
  326. keys = 0
  327. @nodes.each{|n|
  328. if n.has_flag?("master")
  329. puts "#{n} (#{n.info[:name][0...8]}...) -> #{n.r.dbsize} keys | #{n.slots.length} slots | "+
  330. "#{n.info[:replicas].length} slaves."
  331. masters += 1
  332. keys += n.r.dbsize
  333. end
  334. }
  335. xputs "[OK] #{keys} keys in #{masters} masters."
  336. keys_per_slot = sprintf("%.2f",keys/16384.0)
  337. puts "#{keys_per_slot} keys per slot on average."
  338. end
  339. # Merge slots of every known node. If the resulting slots are equal
  340. # to ClusterHashSlots, then all slots are served.
  341. def covered_slots
  342. slots = {}
  343. @nodes.each{|n|
  344. slots = slots.merge(n.slots)
  345. }
  346. slots
  347. end
  348. def check_slots_coverage
  349. xputs ">>> Check slots coverage..."
  350. slots = covered_slots
  351. if slots.length == ClusterHashSlots
  352. xputs "[OK] All #{ClusterHashSlots} slots covered."
  353. else
  354. cluster_error \
  355. "[ERR] Not all #{ClusterHashSlots} slots are covered by nodes."
  356. fix_slots_coverage if @fix
  357. end
  358. end
  359. def check_open_slots
  360. xputs ">>> Check for open slots..."
  361. open_slots = []
  362. @nodes.each{|n|
  363. if n.info[:migrating].size > 0
  364. cluster_error \
  365. "[WARNING] Node #{n} has slots in migrating state (#{n.info[:migrating].keys.join(",")})."
  366. open_slots += n.info[:migrating].keys
  367. end
  368. if n.info[:importing].size > 0
  369. cluster_error \
  370. "[WARNING] Node #{n} has slots in importing state (#{n.info[:importing].keys.join(",")})."
  371. open_slots += n.info[:importing].keys
  372. end
  373. }
  374. open_slots.uniq!
  375. if open_slots.length > 0
  376. xputs "[WARNING] The following slots are open: #{open_slots.join(",")}"
  377. end
  378. if @fix
  379. open_slots.each{|slot| fix_open_slot slot}
  380. end
  381. end
  382. def nodes_with_keys_in_slot(slot)
  383. nodes = []
  384. @nodes.each{|n|
  385. next if n.has_flag?("slave")
  386. nodes << n if n.r.cluster("getkeysinslot",slot,1).length > 0
  387. }
  388. nodes
  389. end
  390. def fix_slots_coverage
  391. not_covered = (0...ClusterHashSlots).to_a - covered_slots.keys
  392. xputs ">>> Fixing slots coverage..."
  393. xputs "List of not covered slots: " + not_covered.join(",")
  394. # For every slot, take action depending on the actual condition:
  395. # 1) No node has keys for this slot.
  396. # 2) A single node has keys for this slot.
  397. # 3) Multiple nodes have keys for this slot.
  398. slots = {}
  399. not_covered.each{|slot|
  400. nodes = nodes_with_keys_in_slot(slot)
  401. slots[slot] = nodes
  402. xputs "Slot #{slot} has keys in #{nodes.length} nodes: #{nodes.join(", ")}"
  403. }
  404. none = slots.select {|k,v| v.length == 0}
  405. single = slots.select {|k,v| v.length == 1}
  406. multi = slots.select {|k,v| v.length > 1}
  407. # Handle case "1": keys in no node.
  408. if none.length > 0
  409. xputs "The folowing uncovered slots have no keys across the cluster:"
  410. xputs none.keys.join(",")
  411. yes_or_die "Fix these slots by covering with a random node?"
  412. none.each{|slot,nodes|
  413. node = @nodes.sample
  414. xputs ">>> Covering slot #{slot} with #{node}"
  415. node.r.cluster("addslots",slot)
  416. }
  417. end
  418. # Handle case "2": keys only in one node.
  419. if single.length > 0
  420. xputs "The folowing uncovered slots have keys in just one node:"
  421. puts single.keys.join(",")
  422. yes_or_die "Fix these slots by covering with those nodes?"
  423. single.each{|slot,nodes|
  424. xputs ">>> Covering slot #{slot} with #{nodes[0]}"
  425. nodes[0].r.cluster("addslots",slot)
  426. }
  427. end
  428. # Handle case "3": keys in multiple nodes.
  429. if multi.length > 0
  430. xputs "The folowing uncovered slots have keys in multiple nodes:"
  431. xputs multi.keys.join(",")
  432. yes_or_die "Fix these slots by moving keys into a single node?"
  433. multi.each{|slot,nodes|
  434. target = get_node_with_most_keys_in_slot(nodes,slot)
  435. xputs ">>> Covering slot #{slot} moving keys to #{target}"
  436. target.r.cluster('addslots',slot)
  437. target.r.cluster('setslot',slot,'stable')
  438. nodes.each{|src|
  439. next if src == target
  440. # Set the source node in 'importing' state (even if we will
  441. # actually migrate keys away) in order to avoid receiving
  442. # redirections for MIGRATE.
  443. src.r.cluster('setslot',slot,'importing',target.info[:name])
  444. move_slot(src,target,slot,:dots=>true,:fix=>true,:cold=>true)
  445. src.r.cluster('setslot',slot,'stable')
  446. }
  447. }
  448. end
  449. end
  450. # Return the owner of the specified slot
  451. def get_slot_owners(slot)
  452. owners = []
  453. @nodes.each{|n|
  454. next if n.has_flag?("slave")
  455. n.slots.each{|s,_|
  456. owners << n if s == slot
  457. }
  458. }
  459. owners
  460. end
  461. # Return the node, among 'nodes' with the greatest number of keys
  462. # in the specified slot.
  463. def get_node_with_most_keys_in_slot(nodes,slot)
  464. best = nil
  465. best_numkeys = 0
  466. @nodes.each{|n|
  467. next if n.has_flag?("slave")
  468. numkeys = n.r.cluster("countkeysinslot",slot)
  469. if numkeys > best_numkeys || best == nil
  470. best = n
  471. best_numkeys = numkeys
  472. end
  473. }
  474. return best
  475. end
  476. # Slot 'slot' was found to be in importing or migrating state in one or
  477. # more nodes. This function fixes this condition by migrating keys where
  478. # it seems more sensible.
  479. def fix_open_slot(slot)
  480. puts ">>> Fixing open slot #{slot}"
  481. # Try to obtain the current slot owner, according to the current
  482. # nodes configuration.
  483. owners = get_slot_owners(slot)
  484. owner = owners[0] if owners.length == 1
  485. migrating = []
  486. importing = []
  487. @nodes.each{|n|
  488. next if n.has_flag? "slave"
  489. if n.info[:migrating][slot]
  490. migrating << n
  491. elsif n.info[:importing][slot]
  492. importing << n
  493. elsif n.r.cluster("countkeysinslot",slot) > 0 && n != owner
  494. xputs "*** Found keys about slot #{slot} in node #{n}!"
  495. importing << n
  496. end
  497. }
  498. puts "Set as migrating in: #{migrating.join(",")}"
  499. puts "Set as importing in: #{importing.join(",")}"
  500. # If there is no slot owner, set as owner the slot with the biggest
  501. # number of keys, among the set of migrating / importing nodes.
  502. if !owner
  503. xputs ">>> Nobody claims ownership, selecting an owner..."
  504. owner = get_node_with_most_keys_in_slot(@nodes,slot)
  505. # If we still don't have an owner, we can't fix it.
  506. if !owner
  507. xputs "[ERR] Can't select a slot owner. Impossible to fix."
  508. exit 1
  509. end
  510. # Use ADDSLOTS to assign the slot.
  511. puts "*** Configuring #{owner} as the slot owner"
  512. owner.r.cluster("setslot",slot,"stable")
  513. owner.r.cluster("addslots",slot)
  514. # Make sure this information will propagate. Not strictly needed
  515. # since there is no past owner, so all the other nodes will accept
  516. # whatever epoch this node will claim the slot with.
  517. owner.r.cluster("bumpepoch")
  518. # Remove the owner from the list of migrating/importing
  519. # nodes.
  520. migrating.delete(owner)
  521. importing.delete(owner)
  522. end
  523. # If there are multiple owners of the slot, we need to fix it
  524. # so that a single node is the owner and all the other nodes
  525. # are in importing state. Later the fix can be handled by one
  526. # of the base cases above.
  527. #
  528. # Note that this case also covers multiple nodes having the slot
  529. # in migrating state, since migrating is a valid state only for
  530. # slot owners.
  531. if owners.length > 1
  532. owner = get_node_with_most_keys_in_slot(owners,slot)
  533. owners.each{|n|
  534. next if n == owner
  535. n.r.cluster('delslots',slot)
  536. n.r.cluster('setslot',slot,'importing',owner.info[:name])
  537. importing.delete(n) # Avoid duplciates
  538. importing << n
  539. }
  540. owner.r.cluster('bumpepoch')
  541. end
  542. # Case 1: The slot is in migrating state in one slot, and in
  543. # importing state in 1 slot. That's trivial to address.
  544. if migrating.length == 1 && importing.length == 1
  545. move_slot(migrating[0],importing[0],slot,:dots=>true,:fix=>true)
  546. # Case 2: There are multiple nodes that claim the slot as importing,
  547. # they probably got keys about the slot after a restart so opened
  548. # the slot. In this case we just move all the keys to the owner
  549. # according to the configuration.
  550. elsif migrating.length == 0 && importing.length > 0
  551. xputs ">>> Moving all the #{slot} slot keys to its owner #{owner}"
  552. importing.each {|node|
  553. next if node == owner
  554. move_slot(node,owner,slot,:dots=>true,:fix=>true,:cold=>true)
  555. xputs ">>> Setting #{slot} as STABLE in #{node}"
  556. node.r.cluster("setslot",slot,"stable")
  557. }
  558. # Case 3: There are no slots claiming to be in importing state, but
  559. # there is a migrating node that actually don't have any key. We
  560. # can just close the slot, probably a reshard interrupted in the middle.
  561. elsif importing.length == 0 && migrating.length == 1 &&
  562. migrating[0].r.cluster("getkeysinslot",slot,10).length == 0
  563. migrating[0].r.cluster("setslot",slot,"stable")
  564. else
  565. xputs "[ERR] Sorry, Redis-trib can't fix this slot yet (work in progress). Slot is set as migrating in #{migrating.join(",")}, as importing in #{importing.join(",")}, owner is #{owner}"
  566. end
  567. end
  568. # Check if all the nodes agree about the cluster configuration
  569. def check_config_consistency
  570. if !is_config_consistent?
  571. cluster_error "[ERR] Nodes don't agree about configuration!"
  572. else
  573. xputs "[OK] All nodes agree about slots configuration."
  574. end
  575. end
  576. def is_config_consistent?
  577. signatures=[]
  578. @nodes.each{|n|
  579. signatures << n.get_config_signature
  580. }
  581. return signatures.uniq.length == 1
  582. end
  583. def wait_cluster_join
  584. print "Waiting for the cluster to join"
  585. while !is_config_consistent?
  586. print "."
  587. STDOUT.flush
  588. sleep 1
  589. end
  590. print "\n"
  591. end
  592. def alloc_slots
  593. nodes_count = @nodes.length
  594. masters_count = @nodes.length / (@replicas+1)
  595. masters = []
  596. # The first step is to split instances by IP. This is useful as
  597. # we'll try to allocate master nodes in different physical machines
  598. # (as much as possible) and to allocate slaves of a given master in
  599. # different physical machines as well.
  600. #
  601. # This code assumes just that if the IP is different, than it is more
  602. # likely that the instance is running in a different physical host
  603. # or at least a different virtual machine.
  604. ips = {}
  605. @nodes.each{|n|
  606. ips[n.info[:host]] = [] if !ips[n.info[:host]]
  607. ips[n.info[:host]] << n
  608. }
  609. # Select master instances
  610. puts "Using #{masters_count} masters:"
  611. interleaved = []
  612. stop = false
  613. while not stop do
  614. # Take one node from each IP until we run out of nodes
  615. # across every IP.
  616. ips.each do |ip,nodes|
  617. if nodes.empty?
  618. # if this IP has no remaining nodes, check for termination
  619. if interleaved.length == nodes_count
  620. # stop when 'interleaved' has accumulated all nodes
  621. stop = true
  622. next
  623. end
  624. else
  625. # else, move one node from this IP to 'interleaved'
  626. interleaved.push nodes.shift
  627. end
  628. end
  629. end
  630. masters = interleaved.slice!(0, masters_count)
  631. nodes_count -= masters.length
  632. masters.each{|m| puts m}
  633. # Alloc slots on masters
  634. slots_per_node = ClusterHashSlots.to_f / masters_count
  635. first = 0
  636. cursor = 0.0
  637. masters.each_with_index{|n,masternum|
  638. last = (cursor+slots_per_node-1).round
  639. if last > ClusterHashSlots || masternum == masters.length-1
  640. last = ClusterHashSlots-1
  641. end
  642. last = first if last < first # Min step is 1.
  643. n.add_slots first..last
  644. first = last+1
  645. cursor += slots_per_node
  646. }
  647. # Select N replicas for every master.
  648. # We try to split the replicas among all the IPs with spare nodes
  649. # trying to avoid the host where the master is running, if possible.
  650. #
  651. # Note we loop two times. The first loop assigns the requested
  652. # number of replicas to each master. The second loop assigns any
  653. # remaining instances as extra replicas to masters. Some masters
  654. # may end up with more than their requested number of replicas, but
  655. # all nodes will be used.
  656. assignment_verbose = false
  657. [:requested,:unused].each do |assign|
  658. masters.each do |m|
  659. assigned_replicas = 0
  660. while assigned_replicas < @replicas
  661. break if nodes_count == 0
  662. if assignment_verbose
  663. if assign == :requested
  664. puts "Requesting total of #{@replicas} replicas " \
  665. "(#{assigned_replicas} replicas assigned " \
  666. "so far with #{nodes_count} total remaining)."
  667. elsif assign == :unused
  668. puts "Assigning extra instance to replication " \
  669. "role too (#{nodes_count} remaining)."
  670. end
  671. end
  672. # Return the first node not matching our current master
  673. node = interleaved.find{|n| n.info[:host] != m.info[:host]}
  674. # If we found a node, use it as a best-first match.
  675. # Otherwise, we didn't find a node on a different IP, so we
  676. # go ahead and use a same-IP replica.
  677. if node
  678. slave = node
  679. interleaved.delete node
  680. else
  681. slave = interleaved.shift
  682. end
  683. slave.set_as_replica(m.info[:name])
  684. nodes_count -= 1
  685. assigned_replicas += 1
  686. puts "Adding replica #{slave} to #{m}"
  687. # If we are in the "assign extra nodes" loop,
  688. # we want to assign one extra replica to each
  689. # master before repeating masters.
  690. # This break lets us assign extra replicas to masters
  691. # in a round-robin way.
  692. break if assign == :unused
  693. end
  694. end
  695. end
  696. end
  697. def flush_nodes_config
  698. @nodes.each{|n|
  699. n.flush_node_config
  700. }
  701. end
  702. def show_nodes
  703. @nodes.each{|n|
  704. xputs n.info_string
  705. }
  706. end
  707. # Redis Cluster config epoch collision resolution code is able to eventually
  708. # set a different epoch to each node after a new cluster is created, but
  709. # it is slow compared to assign a progressive config epoch to each node
  710. # before joining the cluster. However we do just a best-effort try here
  711. # since if we fail is not a problem.
  712. def assign_config_epoch
  713. config_epoch = 1
  714. @nodes.each{|n|
  715. begin
  716. n.r.cluster("set-config-epoch",config_epoch)
  717. rescue
  718. end
  719. config_epoch += 1
  720. }
  721. end
  722. def join_cluster
  723. # We use a brute force approach to make sure the node will meet
  724. # each other, that is, sending CLUSTER MEET messages to all the nodes
  725. # about the very same node.
  726. # Thanks to gossip this information should propagate across all the
  727. # cluster in a matter of seconds.
  728. first = false
  729. @nodes.each{|n|
  730. if !first then first = n.info; next; end # Skip the first node
  731. n.r.cluster("meet",first[:host],first[:port])
  732. }
  733. end
  734. def yes_or_die(msg)
  735. print "#{msg} (type 'yes' to accept): "
  736. STDOUT.flush
  737. if !(STDIN.gets.chomp.downcase == "yes")
  738. xputs "*** Aborting..."
  739. exit 1
  740. end
  741. end
  742. def load_cluster_info_from_node(nodeaddr)
  743. node = ClusterNode.new(nodeaddr)
  744. node.connect(:abort => true)
  745. node.assert_cluster
  746. node.load_info(:getfriends => true)
  747. add_node(node)
  748. node.friends.each{|f|
  749. next if f[:flags].index("noaddr") ||
  750. f[:flags].index("disconnected") ||
  751. f[:flags].index("fail")
  752. fnode = ClusterNode.new(f[:addr])
  753. fnode.connect()
  754. next if !fnode.r
  755. begin
  756. fnode.load_info()
  757. add_node(fnode)
  758. rescue => e
  759. xputs "[ERR] Unable to load info for node #{fnode}"
  760. end
  761. }
  762. populate_nodes_replicas_info
  763. end
  764. # This function is called by load_cluster_info_from_node in order to
  765. # add additional information to every node as a list of replicas.
  766. def populate_nodes_replicas_info
  767. # Start adding the new field to every node.
  768. @nodes.each{|n|
  769. n.info[:replicas] = []
  770. }
  771. # Populate the replicas field using the replicate field of slave
  772. # nodes.
  773. @nodes.each{|n|
  774. if n.info[:replicate]
  775. master = get_node_by_name(n.info[:replicate])
  776. if !master
  777. xputs "*** WARNING: #{n} claims to be slave of unknown node ID #{n.info[:replicate]}."
  778. else
  779. master.info[:replicas] << n
  780. end
  781. end
  782. }
  783. end
  784. # Given a list of source nodes return a "resharding plan"
  785. # with what slots to move in order to move "numslots" slots to another
  786. # instance.
  787. def compute_reshard_table(sources,numslots)
  788. moved = []
  789. # Sort from bigger to smaller instance, for two reasons:
  790. # 1) If we take less slots than instances it is better to start
  791. # getting from the biggest instances.
  792. # 2) We take one slot more from the first instance in the case of not
  793. # perfect divisibility. Like we have 3 nodes and need to get 10
  794. # slots, we take 4 from the first, and 3 from the rest. So the
  795. # biggest is always the first.
  796. sources = sources.sort{|a,b| b.slots.length <=> a.slots.length}
  797. source_tot_slots = sources.inject(0) {|sum,source|
  798. sum+source.slots.length
  799. }
  800. sources.each_with_index{|s,i|
  801. # Every node will provide a number of slots proportional to the
  802. # slots it has assigned.
  803. n = (numslots.to_f/source_tot_slots*s.slots.length)
  804. if i == 0
  805. n = n.ceil
  806. else
  807. n = n.floor
  808. end
  809. s.slots.keys.sort[(0...n)].each{|slot|
  810. if moved.length < numslots
  811. moved << {:source => s, :slot => slot}
  812. end
  813. }
  814. }
  815. return moved
  816. end
  817. def show_reshard_table(table)
  818. table.each{|e|
  819. puts " Moving slot #{e[:slot]} from #{e[:source].info[:name]}"
  820. }
  821. end
  822. # Move slots between source and target nodes using MIGRATE.
  823. #
  824. # Options:
  825. # :verbose -- Print a dot for every moved key.
  826. # :fix -- We are moving in the context of a fix. Use REPLACE.
  827. # :cold -- Move keys without opening slots / reconfiguring the nodes.
  828. # :update -- Update nodes.info[:slots] for source/target nodes.
  829. # :quiet -- Don't print info messages.
  830. def move_slot(source,target,slot,o={})
  831. o = {:pipeline => MigrateDefaultPipeline}.merge(o)
  832. # We start marking the slot as importing in the destination node,
  833. # and the slot as migrating in the target host. Note that the order of
  834. # the operations is important, as otherwise a client may be redirected
  835. # to the target node that does not yet know it is importing this slot.
  836. if !o[:quiet]
  837. print "Moving slot #{slot} from #{source} to #{target}: "
  838. STDOUT.flush
  839. end
  840. if !o[:cold]
  841. target.r.cluster("setslot",slot,"importing",source.info[:name])
  842. source.r.cluster("setslot",slot,"migrating",target.info[:name])
  843. end
  844. # Migrate all the keys from source to target using the MIGRATE command
  845. while true
  846. keys = source.r.cluster("getkeysinslot",slot,o[:pipeline])
  847. break if keys.length == 0
  848. begin
  849. source.r.client.call(["migrate",target.info[:host],target.info[:port],"",0,@timeout,:keys,*keys])
  850. rescue => e
  851. if o[:fix] && e.to_s =~ /BUSYKEY/
  852. xputs "*** Target key exists. Replacing it for FIX."
  853. source.r.client.call(["migrate",target.info[:host],target.info[:port],"",0,@timeout,:replace,:keys,*keys])
  854. else
  855. puts ""
  856. xputs "[ERR] Calling MIGRATE: #{e}"
  857. exit 1
  858. end
  859. end
  860. print "."*keys.length if o[:dots]
  861. STDOUT.flush
  862. end
  863. puts if !o[:quiet]
  864. # Set the new node as the owner of the slot in all the known nodes.
  865. if !o[:cold]
  866. @nodes.each{|n|
  867. next if n.has_flag?("slave")
  868. n.r.cluster("setslot",slot,"node",target.info[:name])
  869. }
  870. end
  871. # Update the node logical config
  872. if o[:update] then
  873. source.info[:slots].delete(slot)
  874. target.info[:slots][slot] = true
  875. end
  876. end
  877. # redis-trib subcommands implementations.
  878. def check_cluster_cmd(argv,opt)
  879. load_cluster_info_from_node(argv[0])
  880. check_cluster
  881. end
  882. def info_cluster_cmd(argv,opt)
  883. load_cluster_info_from_node(argv[0])
  884. show_cluster_info
  885. end
  886. def rebalance_cluster_cmd(argv,opt)
  887. opt = {
  888. 'pipeline' => MigrateDefaultPipeline,
  889. 'threshold' => RebalanceDefaultThreshold
  890. }.merge(opt)
  891. # Load nodes info before parsing options, otherwise we can't
  892. # handle --weight.
  893. load_cluster_info_from_node(argv[0])
  894. # Options parsing
  895. threshold = opt['threshold'].to_i
  896. autoweights = opt['auto-weights']
  897. weights = {}
  898. opt['weight'].each{|w|
  899. fields = w.split("=")
  900. node = get_node_by_abbreviated_name(fields[0])
  901. if !node || !node.has_flag?("master")
  902. puts "*** No such master node #{fields[0]}"
  903. exit 1
  904. end
  905. weights[node.info[:name]] = fields[1].to_f
  906. } if opt['weight']
  907. useempty = opt['use-empty-masters']
  908. # Assign a weight to each node, and compute the total cluster weight.
  909. total_weight = 0
  910. nodes_involved = 0
  911. @nodes.each{|n|
  912. if n.has_flag?("master")
  913. next if !useempty && n.slots.length == 0
  914. n.info[:w] = weights[n.info[:name]] ? weights[n.info[:name]] : 1
  915. total_weight += n.info[:w]
  916. nodes_involved += 1
  917. end
  918. }
  919. # Check cluster, only proceed if it looks sane.
  920. check_cluster(:quiet => true)
  921. if @errors.length != 0
  922. puts "*** Please fix your cluster problems before rebalancing"
  923. exit 1
  924. end
  925. # Calculate the slots balance for each node. It's the number of
  926. # slots the node should lose (if positive) or gain (if negative)
  927. # in order to be balanced.
  928. threshold = opt['threshold'].to_f
  929. threshold_reached = false
  930. @nodes.each{|n|
  931. if n.has_flag?("master")
  932. next if !n.info[:w]
  933. expected = ((ClusterHashSlots.to_f / total_weight) *
  934. n.info[:w]).to_i
  935. n.info[:balance] = n.slots.length - expected
  936. # Compute the percentage of difference between the
  937. # expected number of slots and the real one, to see
  938. # if it's over the threshold specified by the user.
  939. over_threshold = false
  940. if threshold > 0
  941. if n.slots.length > 0
  942. err_perc = (100-(100.0*expected/n.slots.length)).abs
  943. over_threshold = true if err_perc > threshold
  944. elsif expected > 0
  945. over_threshold = true
  946. end
  947. end
  948. threshold_reached = true if over_threshold
  949. end
  950. }
  951. if !threshold_reached
  952. xputs "*** No rebalancing needed! All nodes are within the #{threshold}% threshold."
  953. return
  954. end
  955. # Only consider nodes we want to change
  956. sn = @nodes.select{|n|
  957. n.has_flag?("master") && n.info[:w]
  958. }
  959. # Because of rounding, it is possible that the balance of all nodes
  960. # summed does not give 0. Make sure that nodes that have to provide
  961. # slots are always matched by nodes receiving slots.
  962. total_balance = sn.map{|x| x.info[:balance]}.reduce{|a,b| a+b}
  963. while total_balance > 0
  964. sn.each{|n|
  965. if n.info[:balance] < 0 && total_balance > 0
  966. n.info[:balance] -= 1
  967. total_balance -= 1
  968. end
  969. }
  970. end
  971. # Sort nodes by their slots balance.
  972. sn = sn.sort{|a,b|
  973. a.info[:balance] <=> b.info[:balance]
  974. }
  975. xputs ">>> Rebalancing across #{nodes_involved} nodes. Total weight = #{total_weight}"
  976. if $verbose
  977. sn.each{|n|
  978. puts "#{n} balance is #{n.info[:balance]} slots"
  979. }
  980. end
  981. # Now we have at the start of the 'sn' array nodes that should get
  982. # slots, at the end nodes that must give slots.
  983. # We take two indexes, one at the start, and one at the end,
  984. # incrementing or decrementing the indexes accordingly til we
  985. # find nodes that need to get/provide slots.
  986. dst_idx = 0
  987. src_idx = sn.length - 1
  988. while dst_idx < src_idx
  989. dst = sn[dst_idx]
  990. src = sn[src_idx]
  991. numslots = [dst.info[:balance],src.info[:balance]].map{|n|
  992. n.abs
  993. }.min
  994. if numslots > 0
  995. puts "Moving #{numslots} slots from #{src} to #{dst}"
  996. # Actaully move the slots.
  997. reshard_table = compute_reshard_table([src],numslots)
  998. if reshard_table.length != numslots
  999. xputs "*** Assertio failed: Reshard table != number of slots"
  1000. exit 1
  1001. end
  1002. if opt['simulate']
  1003. print "#"*reshard_table.length
  1004. else
  1005. reshard_table.each{|e|
  1006. move_slot(e[:source],dst,e[:slot],
  1007. :quiet=>true,
  1008. :dots=>false,
  1009. :update=>true,
  1010. :pipeline=>opt['pipeline'])
  1011. print "#"
  1012. STDOUT.flush
  1013. }
  1014. end
  1015. puts
  1016. end
  1017. # Update nodes balance.
  1018. dst.info[:balance] += numslots
  1019. src.info[:balance] -= numslots
  1020. dst_idx += 1 if dst.info[:balance] == 0
  1021. src_idx -= 1 if src.info[:balance] == 0
  1022. end
  1023. end
  1024. def fix_cluster_cmd(argv,opt)
  1025. @fix = true
  1026. @timeout = opt['timeout'].to_i if opt['timeout']
  1027. load_cluster_info_from_node(argv[0])
  1028. check_cluster
  1029. end
  1030. def reshard_cluster_cmd(argv,opt)
  1031. opt = {'pipeline' => MigrateDefaultPipeline}.merge(opt)
  1032. load_cluster_info_from_node(argv[0])
  1033. check_cluster
  1034. if @errors.length != 0
  1035. puts "*** Please fix your cluster problems before resharding"
  1036. exit 1
  1037. end
  1038. @timeout = opt['timeout'].to_i if opt['timeout'].to_i
  1039. # Get number of slots
  1040. if opt['slots']
  1041. numslots = opt['slots'].to_i
  1042. else
  1043. numslots = 0
  1044. while numslots <= 0 or numslots > ClusterHashSlots
  1045. print "How many slots do you want to move (from 1 to #{ClusterHashSlots})? "
  1046. numslots = STDIN.gets.to_i
  1047. end
  1048. end
  1049. # Get the target instance
  1050. if opt['to']
  1051. target = get_node_by_name(opt['to'])
  1052. if !target || target.has_flag?("slave")
  1053. xputs "*** The specified node is not known or not a master, please retry."
  1054. exit 1
  1055. end
  1056. else
  1057. target = nil
  1058. while not target
  1059. print "What is the receiving node ID? "
  1060. target = get_node_by_name(STDIN.gets.chop)
  1061. if !target || target.has_flag?("slave")
  1062. xputs "*** The specified node is not known or not a master, please retry."
  1063. target = nil
  1064. end
  1065. end
  1066. end
  1067. # Get the source instances
  1068. sources = []
  1069. if opt['from']
  1070. opt['from'].split(',').each{|node_id|
  1071. if node_id == "all"
  1072. sources = "all"
  1073. break
  1074. end
  1075. src = get_node_by_name(node_id)
  1076. if !src || src.has_flag?("slave")
  1077. xputs "*** The specified node is not known or is not a master, please retry."
  1078. exit 1
  1079. end
  1080. sources << src
  1081. }
  1082. else
  1083. xputs "Please enter all the source node IDs."
  1084. xputs " Type 'all' to use all the nodes as source nodes for the hash slots."
  1085. xputs " Type 'done' once you entered all the source nodes IDs."
  1086. while true
  1087. print "Source node ##{sources.length+1}:"
  1088. line = STDIN.gets.chop
  1089. src = get_node_by_name(line)
  1090. if line == "done"
  1091. break
  1092. elsif line == "all"
  1093. sources = "all"
  1094. break
  1095. elsif !src || src.has_flag?("slave")
  1096. xputs "*** The specified node is not known or is not a master, please retry."
  1097. elsif src.info[:name] == target.info[:name]
  1098. xputs "*** It is not possible to use the target node as source node."
  1099. else
  1100. sources << src
  1101. end
  1102. end
  1103. end
  1104. if sources.length == 0
  1105. puts "*** No source nodes given, operation aborted"
  1106. exit 1
  1107. end
  1108. # Handle soures == all.
  1109. if sources == "all"
  1110. sources = []
  1111. @nodes.each{|n|
  1112. next if n.info[:name] == target.info[:name]
  1113. next if n.has_flag?("slave")
  1114. sources << n
  1115. }
  1116. end
  1117. # Check if the destination node is the same of any source nodes.
  1118. if sources.index(target)
  1119. xputs "*** Target node is also listed among the source nodes!"
  1120. exit 1
  1121. end
  1122. puts "\nReady to move #{numslots} slots."
  1123. puts " Source nodes:"
  1124. sources.each{|s| puts " "+s.info_string}
  1125. puts " Destination node:"
  1126. puts " #{target.info_string}"
  1127. reshard_table = compute_reshard_table(sources,numslots)
  1128. puts " Resharding plan:"
  1129. show_reshard_table(reshard_table)
  1130. if !opt['yes']
  1131. print "Do you want to proceed with the proposed reshard plan (yes/no)? "
  1132. yesno = STDIN.gets.chop
  1133. exit(1) if (yesno != "yes")
  1134. end
  1135. reshard_table.each{|e|
  1136. move_slot(e[:source],target,e[:slot],
  1137. :dots=>true,
  1138. :pipeline=>opt['pipeline'])
  1139. }
  1140. end
  1141. # This is an helper function for create_cluster_cmd that verifies if
  1142. # the number of nodes and the specified replicas have a valid configuration
  1143. # where there are at least three master nodes and enough replicas per node.
  1144. def check_create_parameters
  1145. masters = @nodes.length/(@replicas+1)
  1146. if masters < 3
  1147. puts "*** ERROR: Invalid configuration for cluster creation."
  1148. puts "*** Redis Cluster requires at least 3 master nodes."
  1149. puts "*** This is not possible with #{@nodes.length} nodes and #{@replicas} replicas per node."
  1150. puts "*** At least #{3*(@replicas+1)} nodes are required."
  1151. exit 1
  1152. end
  1153. end
  1154. def create_cluster_cmd(argv,opt)
  1155. opt = {'replicas' => 0}.merge(opt)
  1156. @replicas = opt['replicas'].to_i
  1157. xputs ">>> Creating cluster"
  1158. argv[0..-1].each{|n|
  1159. node = ClusterNode.new(n)
  1160. node.connect(:abort => true)
  1161. node.assert_cluster
  1162. node.load_info
  1163. node.assert_empty
  1164. add_node(node)
  1165. }
  1166. check_create_parameters
  1167. xputs ">>> Performing hash slots allocation on #{@nodes.length} nodes..."
  1168. alloc_slots
  1169. show_nodes
  1170. yes_or_die "Can I set the above configuration?"
  1171. flush_nodes_config
  1172. xputs ">>> Nodes configuration updated"
  1173. xputs ">>> Assign a different config epoch to each node"
  1174. assign_config_epoch
  1175. xputs ">>> Sending CLUSTER MEET messages to join the cluster"
  1176. join_cluster
  1177. # Give one second for the join to start, in order to avoid that
  1178. # wait_cluster_join will find all the nodes agree about the config as
  1179. # they are still empty with unassigned slots.
  1180. sleep 1
  1181. wait_cluster_join
  1182. flush_nodes_config # Useful for the replicas
  1183. check_cluster
  1184. end
  1185. def addnode_cluster_cmd(argv,opt)
  1186. xputs ">>> Adding node #{argv[0]} to cluster #{argv[1]}"
  1187. # Check the existing cluster
  1188. load_cluster_info_from_node(argv[1])
  1189. check_cluster
  1190. # If --master-id was specified, try to resolve it now so that we
  1191. # abort before starting with the node configuration.
  1192. if opt['slave']
  1193. if opt['master-id']
  1194. master = get_node_by_name(opt['master-id'])
  1195. if !master
  1196. xputs "[ERR] No such master ID #{opt['master-id']}"
  1197. end
  1198. else
  1199. master = get_master_with_least_replicas
  1200. xputs "Automatically selected master #{master}"
  1201. end
  1202. end
  1203. # Add the new node
  1204. new = ClusterNode.new(argv[0])
  1205. new.connect(:abort => true)
  1206. new.assert_cluster
  1207. new.load_info
  1208. new.assert_empty
  1209. first = @nodes.first.info
  1210. add_node(new)
  1211. # Send CLUSTER MEET command to the new node
  1212. xputs ">>> Send CLUSTER MEET to node #{new} to make it join the cluster."
  1213. new.r.cluster("meet",first[:host],first[:port])
  1214. # Additional configuration is needed if the node is added as
  1215. # a slave.
  1216. if opt['slave']
  1217. wait_cluster_join
  1218. xputs ">>> Configure node as replica of #{master}."
  1219. new.r.cluster("replicate",master.info[:name])
  1220. end
  1221. xputs "[OK] New node added correctly."
  1222. end
  1223. def delnode_cluster_cmd(argv,opt)
  1224. id = argv[1].downcase
  1225. xputs ">>> Removing node #{id} from cluster #{argv[0]}"
  1226. # Load cluster information
  1227. load_cluster_info_from_node(argv[0])
  1228. # Check if the node exists and is not empty
  1229. node = get_node_by_name(id)
  1230. if !node
  1231. xputs "[ERR] No such node ID #{id}"
  1232. exit 1
  1233. end
  1234. if node.slots.length != 0
  1235. xputs "[ERR] Node #{node} is not empty! Reshard data away and try again."
  1236. exit 1
  1237. end
  1238. # Send CLUSTER FORGET to all the nodes but the node to remove
  1239. xputs ">>> Sending CLUSTER FORGET messages to the cluster..."
  1240. @nodes.each{|n|
  1241. next if n == node
  1242. if n.info[:replicate] && n.info[:replicate].downcase == id
  1243. # Reconfigure the slave to replicate with some other node
  1244. master = get_master_with_least_replicas
  1245. xputs ">>> #{n} as replica of #{master}"
  1246. n.r.cluster("replicate",master.info[:name])
  1247. end
  1248. n.r.cluster("forget",argv[1])
  1249. }
  1250. # Finally shutdown the node
  1251. xputs ">>> SHUTDOWN the node."
  1252. node.r.shutdown
  1253. end
  1254. def set_timeout_cluster_cmd(argv,opt)
  1255. timeout = argv[1].to_i
  1256. if timeout < 100
  1257. puts "Setting a node timeout of less than 100 milliseconds is a bad idea."
  1258. exit 1
  1259. end
  1260. # Load cluster information
  1261. load_cluster_info_from_node(argv[0])
  1262. ok_count = 0
  1263. err_count = 0
  1264. # Send CLUSTER FORGET to all the nodes but the node to remove
  1265. xputs ">>> Reconfiguring node timeout in every cluster node..."
  1266. @nodes.each{|n|
  1267. begin
  1268. n.r.config("set","cluster-node-timeout",timeout)
  1269. n.r.config("rewrite")
  1270. ok_count += 1
  1271. xputs "*** New timeout set for #{n}"
  1272. rescue => e
  1273. puts "ERR setting node-timeot for #{n}: #{e}"
  1274. err_count += 1
  1275. end
  1276. }
  1277. xputs ">>> New node timeout set. #{ok_count} OK, #{err_count} ERR."
  1278. end
  1279. def call_cluster_cmd(argv,opt)
  1280. cmd = argv[1..-1]
  1281. cmd[0] = cmd[0].upcase
  1282. # Load cluster information
  1283. load_cluster_info_from_node(argv[0])
  1284. xputs ">>> Calling #{cmd.join(" ")}"
  1285. @nodes.each{|n|
  1286. begin
  1287. res = n.r.send(*cmd)
  1288. puts "#{n}: #{res}"
  1289. rescue => e
  1290. puts "#{n}: #{e}"
  1291. end
  1292. }
  1293. end
  1294. def import_cluster_cmd(argv,opt)
  1295. source_addr = opt['from']
  1296. xputs ">>> Importing data from #{source_addr} to cluster #{argv[1]}"
  1297. use_copy = opt['copy']
  1298. use_replace = opt['replace']
  1299. # Check the existing cluster.
  1300. load_cluster_info_from_node(argv[0])
  1301. check_cluster
  1302. # Connect to the source node.
  1303. xputs ">>> Connecting to the source Redis instance"
  1304. src_host,src_port = source_addr.split(":")
  1305. source = Redis.new(:host =>src_host, :port =>src_port)
  1306. if source.info['cluster_enabled'].to_i == 1
  1307. xputs "[ERR] The source node should not be a cluster node."
  1308. end
  1309. xputs "*** Importing #{source.dbsize} keys from DB 0"
  1310. # Build a slot -> node map
  1311. slots = {}
  1312. @nodes.each{|n|
  1313. n.slots.each{|s,_|
  1314. slots[s] = n
  1315. }
  1316. }
  1317. # Use SCAN to iterate over the keys, migrating to the
  1318. # right node as needed.
  1319. cursor = nil
  1320. while cursor != 0
  1321. cursor,keys = source.scan(cursor, :count => 1000)
  1322. cursor = cursor.to_i
  1323. keys.each{|k|
  1324. # Migrate keys using the MIGRATE command.
  1325. slot = key_to_slot(k)
  1326. target = slots[slot]
  1327. print "Migrating #{k} to #{target}: "
  1328. STDOUT.flush
  1329. begin
  1330. cmd = ["migrate",target.info[:host],target.info[:port],k,0,@timeout]
  1331. cmd << :copy if use_copy
  1332. cmd << :replace if use_replace
  1333. source.client.call(cmd)
  1334. rescue => e
  1335. puts e
  1336. else
  1337. puts "OK"
  1338. end
  1339. }
  1340. end
  1341. end
  1342. def help_cluster_cmd(argv,opt)
  1343. show_help
  1344. exit 0
  1345. end
  1346. # Parse the options for the specific command "cmd".
  1347. # Returns an hash populate with option => value pairs, and the index of
  1348. # the first non-option argument in ARGV.
  1349. def parse_options(cmd)
  1350. idx = 1 ; # Current index into ARGV
  1351. options={}
  1352. while idx < ARGV.length && ARGV[idx][0..1] == '--'
  1353. if ARGV[idx][0..1] == "--"
  1354. option = ARGV[idx][2..-1]
  1355. idx += 1
  1356. # --verbose is a global option
  1357. if option == "verbose"
  1358. $verbose = true
  1359. next
  1360. end
  1361. if ALLOWED_OPTIONS[cmd] == nil || ALLOWED_OPTIONS[cmd][option] == nil
  1362. puts "Unknown option '#{option}' for command '#{cmd}'"
  1363. exit 1
  1364. end
  1365. if ALLOWED_OPTIONS[cmd][option] != false
  1366. value = ARGV[idx]
  1367. idx += 1
  1368. else
  1369. value = true
  1370. end
  1371. # If the option is set to [], it's a multiple arguments
  1372. # option. We just queue every new value into an array.
  1373. if ALLOWED_OPTIONS[cmd][option] == []
  1374. options[option] = [] if !options[option]
  1375. options[option] << value
  1376. else
  1377. options[option] = value
  1378. end
  1379. else
  1380. # Remaining arguments are not options.
  1381. break
  1382. end
  1383. end
  1384. # Enforce mandatory options
  1385. if ALLOWED_OPTIONS[cmd]
  1386. ALLOWED_OPTIONS[cmd].each {|option,val|
  1387. if !options[option] && val == :required
  1388. puts "Option '--#{option}' is required "+ \
  1389. "for subcommand '#{cmd}'"
  1390. exit 1
  1391. end
  1392. }
  1393. end
  1394. return options,idx
  1395. end
  1396. end
  1397. #################################################################################
  1398. # Libraries
  1399. #
  1400. # We try to don't depend on external libs since this is a critical part
  1401. # of Redis Cluster.
  1402. #################################################################################
  1403. # This is the CRC16 algorithm used by Redis Cluster to hash keys.
  1404. # Implementation according to CCITT standards.
  1405. #
  1406. # This is actually the XMODEM CRC 16 algorithm, using the
  1407. # following parameters:
  1408. #
  1409. # Name : "XMODEM", also known as "ZMODEM", "CRC-16/ACORN"
  1410. # Width : 16 bit
  1411. # Poly : 1021 (That is actually x^16 + x^12 + x^5 + 1)
  1412. # Initialization : 0000
  1413. # Reflect Input byte : False
  1414. # Reflect Output CRC : False
  1415. # Xor constant to output CRC : 0000
  1416. # Output for "123456789" : 31C3
  1417. module RedisClusterCRC16
  1418. def RedisClusterCRC16.crc16(bytes)
  1419. crc = 0
  1420. bytes.each_byte{|b|
  1421. crc = ((crc<<8) & 0xffff) ^ XMODEMCRC16Lookup[((crc>>8)^b) & 0xff]
  1422. }
  1423. crc
  1424. end
  1425. private
  1426. XMODEMCRC16Lookup = [
  1427. 0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,
  1428. 0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,
  1429. 0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,
  1430. 0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,
  1431. 0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,
  1432. 0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,
  1433. 0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,
  1434. 0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,
  1435. 0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,
  1436. 0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,
  1437. 0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,
  1438. 0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,
  1439. 0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,
  1440. 0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,
  1441. 0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,
  1442. 0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,
  1443. 0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,
  1444. 0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,
  1445. 0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,
  1446. 0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,
  1447. 0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,
  1448. 0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,
  1449. 0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,
  1450. 0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,
  1451. 0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,
  1452. 0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,
  1453. 0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,
  1454. 0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,
  1455. 0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,
  1456. 0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,
  1457. 0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,
  1458. 0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0
  1459. ]
  1460. end
  1461. # Turn a key name into the corrisponding Redis Cluster slot.
  1462. def key_to_slot(key)
  1463. # Only hash what is inside {...} if there is such a pattern in the key.
  1464. # Note that the specification requires the content that is between
  1465. # the first { and the first } after the first {. If we found {} without
  1466. # nothing in the middle, the whole key is hashed as usually.
  1467. s = key.index "{"
  1468. if s
  1469. e = key.index "}",s+1
  1470. if e && e != s+1
  1471. key = key[s+1..e-1]
  1472. end
  1473. end
  1474. RedisClusterCRC16.crc16(key) % 16384
  1475. end
  1476. #################################################################################
  1477. # Definition of commands
  1478. #################################################################################
  1479. COMMANDS={
  1480. "create" => ["create_cluster_cmd", -2, "host1:port1 ... hostN:portN"],
  1481. "check" => ["check_cluster_cmd", 2, "host:port"],
  1482. "info" => ["info_cluster_cmd", 2, "host:port"],
  1483. "fix" => ["fix_cluster_cmd", 2, "host:port"],
  1484. "reshard" => ["reshard_cluster_cmd", 2, "host:port"],
  1485. "rebalance" => ["rebalance_cluster_cmd", -2, "host:port"],
  1486. "add-node" => ["addnode_cluster_cmd", 3, "new_host:new_port existing_host:existing_port"],
  1487. "del-node" => ["delnode_cluster_cmd", 3, "host:port node_id"],
  1488. "set-timeout" => ["set_timeout_cluster_cmd", 3, "host:port milliseconds"],
  1489. "call" => ["call_cluster_cmd", -3, "host:port command arg arg .. arg"],
  1490. "import" => ["import_cluster_cmd", 2, "host:port"],
  1491. "help" => ["help_cluster_cmd", 1, "(show this help)"]
  1492. }
  1493. ALLOWED_OPTIONS={
  1494. "create" => {"replicas" => true},
  1495. "add-node" => {"slave" => false, "master-id" => true},
  1496. "import" => {"from" => :required, "copy" => false, "replace" => false},
  1497. "reshard" => {"from" => true, "to" => true, "slots" => true, "yes" => false, "timeout" => true, "pipeline" => true},
  1498. "rebalance" => {"weight" => [], "auto-weights" => false, "use-empty-masters" => false, "timeout" => true, "simulate" => false, "pipeline" => true, "threshold" => true},
  1499. "fix" => {"timeout" => MigrateDefaultTimeout},
  1500. }
  1501. def show_help
  1502. puts "Usage: redis-trib <command> <options> <arguments ...>\n\n"
  1503. COMMANDS.each{|k,v|
  1504. o = ""
  1505. puts " #{k.ljust(15)} #{v[2]}"
  1506. if ALLOWED_OPTIONS[k]
  1507. ALLOWED_OPTIONS[k].each{|optname,has_arg|
  1508. puts " --#{optname}" + (has_arg ? " <arg>" : "")
  1509. }
  1510. end
  1511. }
  1512. puts "\nFor check, fix, reshard, del-node, set-timeout you can specify the host and port of any working node in the cluster.\n"
  1513. end
  1514. # Sanity check
  1515. if ARGV.length == 0
  1516. show_help
  1517. exit 1
  1518. end
  1519. rt = RedisTrib.new
  1520. cmd_spec = COMMANDS[ARGV[0].downcase]
  1521. if !cmd_spec
  1522. puts "Unknown redis-trib subcommand '#{ARGV[0]}'"
  1523. exit 1
  1524. end
  1525. # Parse options
  1526. cmd_options,first_non_option = rt.parse_options(ARGV[0].downcase)
  1527. rt.check_arity(cmd_spec[1],ARGV.length-(first_non_option-1))
  1528. # Dispatch
  1529. rt.send(cmd_spec[0],ARGV[first_non_option..-1],cmd_options)