Skip to content

Commit df689ba

Browse files
committed
Merge pull request alphagov#184 from alphagov/add-initial-setup-mysql-slave
Add task for initial setup for MySQL slave
2 parents 6c7a443 + be3e939 commit df689ba

File tree

1 file changed

+33
-3
lines changed

1 file changed

+33
-3
lines changed

mysql.py

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from fabric.api import *
2+
from fabric.operations import prompt
23

34

45
def run_mysql_command(cmd):
@@ -40,13 +41,36 @@ def fix_replication_from_slow_query_log_after_upgrade():
4041
@task
4142
def setup_slave_from_master(master):
4243
"""
43-
Sets up a slave from a master by taking a dump from the master,
44-
copying it to the slave and then restoring the dump.
44+
Sets up a slave from a master by:
45+
- configuring MySQL replication config
46+
- using the replicate_slave_from_master task to do an initial dump to the slave
4547
4648
Usage: fab environment -H mysql-slave-1.backend mysql.setup_slave_from_master:'mysql-master-1.backend'
4749
"""
4850
if len(env.hosts) > 1:
49-
print 'This job is currently only setup to run against one slave at a time'
51+
exit('This job is currently only setup to run against one slave at a time')
52+
53+
mysql_master = prompt("Master host (eg 'master.mysql' or 'whitehall-master.mysql'):")
54+
replication_username = 'replica_user'
55+
replication_password = prompt("Password for MySQL user {0}:".format(replication_username))
56+
57+
run_mysql_command("STOP SLAVE;")
58+
run_mysql_command("CHANGE MASTER TO MASTER_HOST='{0}', MASTER_USER='{1}', MASTER_PASSWORD='{2}';".format(
59+
mysql_master, replication_username, replication_password))
60+
61+
replicate_slave_from_master(master)
62+
63+
64+
@task
65+
def replicate_slave_from_master(master):
66+
"""
67+
Updates a slave from a master by taking a dump from the master,
68+
copying it to the slave and then restoring the dump.
69+
70+
Usage: fab environment -H mysql-slave-1.backend mysql.replicate_slave_from_master:'mysql-master-1.backend'
71+
"""
72+
if len(env.hosts) > 1:
73+
exit('This job is currently only setup to run against one slave at a time')
5074

5175
with settings(host_string=master):
5276
# The use of `--master-data` here implies `--lock-all-tables` per the
@@ -62,8 +86,14 @@ def setup_slave_from_master(master):
6286
run_mysql_command("STOP SLAVE")
6387
run_mysql_command("SET GLOBAL slow_query_log=OFF")
6488

89+
with hide('running', 'stdout'):
90+
database_file_size = run("stat --format='%s' dump.sql")
91+
92+
print('Importing MySQL database which is {0}GB, this might take a while...'.format(round(int(database_file_size) / (1024*1024*1024*1.0), 1)))
6593
run('sudo -i mysql -uroot < dump.sql')
6694

95+
run('rm dump.sql')
96+
6797
run_mysql_command("START SLAVE")
6898
run_mysql_command("SET GLOBAL slow_query_log=ON")
6999

0 commit comments

Comments
 (0)