Skip to content

Instantly share code, notes, and snippets.

@matetsu
Created December 28, 2012 03:48
Show Gist options
  • Save matetsu/4394274 to your computer and use it in GitHub Desktop.
Save matetsu/4394274 to your computer and use it in GitHub Desktop.
Redisにslaveofコマンドを送るためだけのスクリプト。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import redis
import logging
import socket
import traceback
LOGFILE = "/var/log/redis-ha.log"
def main():
# logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
fh = logging.FileHandler(filename=LOGFILE)
fh.setLevel(logging.INFO)
fh.setFormatter(formatter)
logger.addHandler(fh)
master_host = sys.argv[1]
master_port = sys.argv[2]
hostname = socket.gethostname()
# 認証を有効にしているので、passwordを指定する必要あり
r = redis.Redis(host='127.0.0.1', port=6379, db=0, password='[password]')
try:
redis_info = r.info()
if redis_info['role'] == 'master' or (master_host == 'no' and master_port == 'one') \
or not (redis_info['master_host'] == master_host and redis_info['master_port'] == master_port):
if r.slaveof(master_host, master_port):
logging.info('execute slaveof %s %s.' % (master_host, master_port))
sys.exit(0)
else:
logging.critical('Failed to execute slaveof command.')
sys.exit(1)
else:
logging.info("This node is already slave of %s:%s" % (master_host, master_port))
except Exception as e:
logging.error(traceback.format_exc(sys.exc_info()[2]))
logging.critical('Failed slaveof command with exceptions.')
sys.exit(1)
if __name__ == '__main__':
if len(sys.argv) == 3:
main()
else:
print 'invalid argument.\n[usage] %s [master_host] [master_port]' % sys.argv[0]
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment