Skip to content

Instantly share code, notes, and snippets.

@josiahcarlson
Created May 12, 2012 20:28
Show Gist options
  • Save josiahcarlson/2668805 to your computer and use it in GitHub Desktop.
Save josiahcarlson/2668805 to your computer and use it in GitHub Desktop.
Redis sentinel monitor assignments
# A proposed method for choosing which slaves to monitor within the
# Redis HA sentinel monitors
def select_slaves_to_monitor(slave_info, all_sentinels, my_id, my_slaves):
'''
slave_info = [
('ip_or_host:port', ['sentinel-id, ...]),
...
]
all_sentinels = ['sentinel-id', ...]
'''
# sorting used as an precondition for the sentinel choice algorithm
slave_info.sort()
all_sentinels.sort()
slaves = 2 * zip(*slave_info)[0]
# each sentinel will monitor 'count' slaves, and the first 'extra'
# sentinels in the all_sentinels list will monitor 1 additional slave
count, extra = divmod(len(slaves), len(all_sentinels))
# we don't need to generate the full assignment list, but we do here for
# the sake of understanding what is going on
assignments = {}
index = 0
for spos, sentinel in enumerate(all_sentinels):
scount = count + (spos < extra)
assignments[sentinel] = set(slaves[index:index+scount])
index += scount
# a few small adjustments to the data to make access fast
my_assignment = assignments[my_id]
current_slaves = dict(slave_info)
my_slaves = set(my_slaves)
# find slaves that we need to stop monitoring
to_disconnect = []
for slave in my_slaves - my_assignment:
# we need to wait to disconnect until there are at least 2 monitoring
# sentinels
if len(current_slaves[slave]) > 2:
to_disconnect.append(slave)
# find slaves that we are supposed to monitor, but have not yet monitored
to_connect = list(my_assignment - my_slaves)
return to_connect, to_disconnect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment