Merge "Corrected links associated with release docs. To be updated along with the...
[genesis.git] / compass / deploy / ansible / openstack_juno / roles / ha / templates / failover.j2
1 import ConfigParser, os, socket
2 import logging as LOG
3 import pxssh
4 import sys
5 import re
6
7 LOG_FILE="/var/log/mysql_failover"
8 try:
9     os.remove(LOG_FILE)
10 except:
11     pass
12
13 LOG.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', filename=LOG_FILE,level=LOG.DEBUG)
14 ha_vip = {{ HA_VIP }} 
15 LOG.info("ha_vip: %s" % ha_vip)
16
17 #ha_vip = "10.1.0.50"
18 galera_path = '/etc/mysql/conf.d/wsrep.cnf'
19 pattern = re.compile(r"gcomm://(?P<prev_ip>.*)")
20
21 def ssh_get_hostname(ip):
22     try:
23         s = pxssh.pxssh()
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.")
31         raise
32
33 def failover(mode):
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"]
39
40     LOG.info("old wsrep_cluster_address = %s" % wsrep_cluster_address)
41
42     if mode == "master":
43         # refresh wsrep_cluster_address to null
44         LOG.info("I'm being master, set wsrep_cluster_address to null")
45         wsrep_cluster_address = ""
46
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")
52
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)
58         config.write(fp)
59    
60     os.system("service mysql restart")
61     LOG.info("failover success!!!")
62
63 if __name__ == "__main__":
64     LOG.debug("call me: %s" % sys.argv)
65     failover(sys.argv[1])