1 import ConfigParser, os, socket
7 LOG_FILE="/var/log/mysql_failover"
13 LOG.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', filename=LOG_FILE,level=LOG.DEBUG)
15 LOG.info("ha_vip: %s" % ha_vip)
18 galera_path = '/etc/mysql/conf.d/wsrep.cnf'
19 pattern = re.compile(r"gcomm://(?P<prev_ip>.*)")
21 def ssh_get_hostname(ip):
24 s.login("%s" % ip, "root", "root")
25 s.sendline('hostname') # run a command
26 s.prompt() # match the prompt
27 result = s.before.strip() # print everything before the prompt.
28 return result.split(os.linesep)[1]
29 except pxssh.ExceptionPxssh as e:
30 LOG.error("pxssh failed on login.")
34 config = ConfigParser.ConfigParser()
35 config.optionxform = str
36 config.readfp(open(galera_path))
37 wsrep_cluster_address = config.get("mysqld", "wsrep_cluster_address")
38 wsrep_cluster_address = pattern.match(wsrep_cluster_address).groupdict()["prev_ip"]
40 LOG.info("old wsrep_cluster_address = %s" % wsrep_cluster_address)
43 # refresh wsrep_cluster_address to null
44 LOG.info("I'm being master, set wsrep_cluster_address to null")
45 wsrep_cluster_address = ""
47 elif mode == "backup":
48 # refresh wsrep_cluster_address to master int ip
49 hostname = ssh_get_hostname(ha_vip)
50 wsrep_cluster_address = socket.gethostbyname(hostname)
51 LOG.info("I'm being slave, set wsrep_cluster_address to master internal ip")
53 LOG.info("new wsrep_cluster_address = %s" % wsrep_cluster_address)
54 wsrep_cluster_address = "gcomm://%s" % wsrep_cluster_address
55 config.set("mysqld", "wsrep_cluster_address", wsrep_cluster_address)
56 with open(galera_path, 'wb') as fp:
57 #config.write(sys.stdout)
60 os.system("service mysql restart")
61 LOG.info("failover success!!!")
63 if __name__ == "__main__":
64 LOG.debug("call me: %s" % sys.argv)