Archive for June, 2015

MySQL replication is the process by which a single data set, stored in a MySQL database, will be live-copied to a second server. This configuration, called “master-slave” replication, is a typical setup. Our setup will be better than that, because master-master replication allows data to be copied from either server to the other one. This subtle but important difference allows us to perform mysql read or writes from either server. This configuration adds redundancy and increases efficiency when dealing with accessing the data.

The examples in this article will be based on two VM Guests, named vdb1 and vdb2.  We’re also going to note that vdb1 will have already contained multiple databases and is currently in production.

vdb1: 1.1.1.1

vdb2: 2.2.2.2

Step 1 – Install and Configure MySQL on vdb1

The first thing we need to do is to install the mysql-server and mysql-client packages on our server. We can do that by typing the following:

apt-get install mysql-server mysql-client

By default, the mysql process will only accept connections on localhost (127.0.0.1). To change this default behavior and change a few other settings necessary for replication to work properly, we need to edit /etc/mysql/my.cnf on vdb1. We need to stop binding to the loopback address which is currently set to the following:

bind-address            = 127.0.0.1

This line tells our server to accept connections from anywhere (by not listening on 127.0.0.1)

#bind-address           = 127.0.0.1

Now make sure the includedir for configuration files are part of the primary my.cnf:

#
# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#
!includedir /etc/mysql/conf.d/

Once you verify the includedir is part of your my.cnf, then go to the conf.d directory and create a file that will contain your replication configurations:

cd conf.d
vi replications.cnf
[mysqld]
#           _ _     _ 
# __   ____| | |__ / |
# \ \ / / _ | '_ \| |
#  \ V / (_| | |_) | |
#   \_/ \__,_|_.__/|_|
#                     
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
#       other settings you may need to change.
server-id                   = 1
log_bin                     = /var/log/mysql/mysql-bin.log
expire_logs_days            = 20
max_binlog_size             = 500M
# By setting the auto_increment_increment and auto_increment_offset values independent
# servers will create unique auto_increment values allowing for replication without fear
# of collision!
replicate-same-server-id    = 0
log-slave-updates           = true
auto_increment_increment    = 2
auto_increment_offset       = 1
relay-log                   = /var/lib/mysql/slave-relay.log
relay-log-index             = /var/lib/mysql/slave-relay-log.index
binlog_format               = MIXED</pre>
Now we need to restart mysql:
<pre>service mysql restart
</pre>
We next need to change some command-line settings within our mysql instance. Back at our shell, we can get to our root mysql user by typing the following:
<pre>mysql -hlocalhost -uroot -p 
</pre>
Please note that the password this command will prompt you for is that of the root <span style="text-decoration: underline; font-style: italic;">mysql user</span>, not the root user the server. To confirm that you are logged in to the mysql shell, the prompt should look like the following.
<pre>mysql> 
</pre>
Once we are logged in, we need to set some things up.

We need to create a pseudo-user that will be used for replicating data between our two VMs. The examples in this article will assume that you name this user "replicator". Replace "password" with the password you wish to use for replication.
<pre>CREATE USER 'replicator'@'%' IDENTIFIED BY 'password'; 
</pre>
Next, we need to give this user permissions to replicate our mysql data:
<pre>GRANT REPLICATION SLAVE ON *.* TO 'replicator'@'%'; 
</pre>
Permissions for replication cannot, unfortunately, be given on a per-database basis. Our user will only replicate the database(s) that we instruct it to in our config file.

For the final step of the initial vdb1 configuration, we need to get some information about the current MySQL instance which we will later provide to vdb2.

The following command will output a few pieces of important information, which we will need to make note of:
<pre>show master status; 
</pre>
The output will looking something like the following, and will have two pieces of critical information:
<pre>+------------------+-----------+--------------+------------------+
| File             | Position  | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+-----------+--------------+------------------+
| mysql-bin.000004 | 114764712 |              |                  |
+------------------+-----------+--------------+------------------+
1 row in set (0.00 sec)
</pre>
We need to make a note of the file and position which will be used in the next step.
<h2>Step 2 - Install and Configure MySQL on vdb2</h2>
We need to repeat the same steps that we followed on vdb1. First we need to install it, which we can do with the following command:
<pre>apt-get install mysql-server mysql-client
</pre>
Once the two packages are properly installed, we need to configure it in much the same way as we configured vdb1. We will start by editing the /etc/mysql/my.cnf file<span style="font-family: monospace;"><span style="font-family: proxima-nova,sans-serif;"> and o</span></span>nce again, by default the mysql process will only accept connections on localhost (127.0.0.1). To change this default behavior and change a few other settings necessary for replication to work properly, we need to edit /etc/mysql/my.cnf on vdb1. We need to stop binding to the loopback address which is currently set to the following:
<pre>vi /etc/mysql/my.cnf</pre>
<pre>bind-address            = 127.0.0.1
</pre>
This line tells our server to accept connections from anywhere (by not listening on 127.0.0.1)
<pre>bind-address           = 127.0.0.1
</pre>
Now make sure the includedir for configuration files are part of the primary my.cnf:
<pre>#
# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#
!includedir /etc/mysql/conf.d/</pre>
<span style="font-family: monospace;"><span style="font-family: proxima-nova,sans-serif;"> Once you verify the includedir is part of your my.cnf, then go to the conf.d directory <span style="text-decoration: underline;">and create a file that will contain your replication configurations</span>:</span>
</span>
<pre>cd conf.d
vi replications.cnf</pre>
<pre class="">[mysqld]
#           _ _    ____  
# __   ____| | |__|___ \ 
# \ \ / / _ | '_ \ __) |
#  \ V / (_| | |_) / __/ 
#   \_/ \__,_|_.__/_____|
#                        
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
# other settings you may need to change.
server-id                   = 2
log_bin                     = /var/log/mysql/mysql-bin.log
expire_logs_days            = 20
max_binlog_size             = 500M
# By setting the auto_increment_increment and auto_increment_offset values independent
# servers will create unique auto_increment values allowing for replication without fear
# of collision!
replicate-same-server-id    = 0
log-slave-updates           = true
auto_increment_increment    = 2
auto_increment_offset       = 2
relay-log                   = /var/lib/mysql/slave-relay.log
relay-log-index             = /var/lib/mysql/slave-relay-log.index
binlog_format               = MIXED

Please note, that unlike vdb1, the server-id for vdb2 cannot be set to 1.  Now we need to restart mysql:

service mysql restart

It is time to go into the mysql shell and set some more configuration options.

mysql -hlocalhost -uroot -p 

First, just as on vdb1, we are going to create the pseudo-user which will be responsible for the replication. Replace “password” with the password you wish to use.

CREATE USER 'replicator'@'%' IDENTIFIED BY 'password'; 

Give our newly created ‘replication’ user permissions to replicate.

GRANT REPLICATION SLAVE ON *.* TO 'replicator'@'%'; 

The next step involves taking the information that we took a note of earlier and applying it to our mysql instance. This will allow replication to begin. The following should be typed at the mysql shell… Special note though, if you’re using a existing MySQL database that you’re trying to turn into a master-master configuration, do Step A first.  Otherwise, skip this and move on the step B.

Step A – If you are using an existing populated MySQL server with various databases already in existence.  Log back into vdb1 and get the latest position since the system is LIVE.  Then temporarily flush and global lock the tables while we perform this next step:

mysql> RESET MASTER;
mysql> FLUSH PRIVILEGES;

mysql> FLUSH TABLES WITH READ LOCK;

Stay logged into your mysql session.  Otherwise it will unlock the tables automatically… Now check the current Position once again.  If your session is still active, then the Position should not increase if you issue the “show master status;” command multiple times:

mysql> show master status;
+------------------+-----------+--------------+------------------+
| File             | Position  | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+-----------+--------------+------------------+
| mysql-bin.000001 | 117423221 |              |                  |
+------------------+-----------+--------------+------------------+
1 row in set (0.00 sec)

Step B – Set the initial replication & Restore from vdb1

mysql> SLAVE STOP;

On vdb2, let’s dump vdb1 while it’s locked and restore here on vdb2:

# mysqldump -uMYSQLROOTUSER -pMYSQLROOTPW -hVDB1 --all-databases --delete-master-logs --flush-logs| mysql -uMYSQLROOTUSER -pMYSQLROOTPW
mysql> CHANGE MASTER TO MASTER_HOST = '1.1.1.1', MASTER_USER = 'replicator', MASTER_PASSWORD = 'password', MASTER_LOG_FILE = 'mysql-bin.000001', MASTER_LOG_POS = 117423221; 
mysql> SLAVE START;

You need to replace ‘password’ with the password that you have chosen for replication. Your values for MASTER_LOG_FILE and MASTER_LOG_POS may differ than those above. You should copy the values that “SHOW MASTER STATUS” returns on vdb1.

If you performed Step A, then on vdb1, unlock the tables you had locked on the session you had open on vdb1:

mysql> UNLOCK TABLES;

The last thing we have to do before we complete the mysql master-master replication is to make note of the master log file and position to use to replicate in the other direction (from vdb2 to vdb1).  Unlike having to flush and lock tables, you shouldn’t have to do it here since it’s acting as a slave for the moment.

Now, start up the slave (to pull and update from vdb1) on vdb1:

mysql> START SLAVE;
mysql> SHOW SLAVE STATUS\G

Look for a line like this:

     Seconds_Behind_Master: 31

We need to give vdb2 a chance to catch up and wait until it’s caught up and the Seconds_Behind_Master is 0.

Once at this point, we can now flush and lock the tables on vdb2:

mysql> FLUSH TABLES WITH READ LOCK;

We can check the file and position by typing the following on vdb2:

mysql> SHOW MASTER STATUS; 

The output will look something like the following:

+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 |      101 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

Take note of the file and position, as we will have to enter those on vdb1, to complete the two-way replication.

The next step will explain how to do that.

Step 3 – Completing Replication on vdb1

Back on vdb1, we need to finish configuring replication on the command line. Running this command will replicate all data from vdb2.

mysql> SLAVE STOP; 
mysql> CHANGE MASTER TO MASTER_HOST = '2.2.2.2', MASTER_USER = 'replicator', MASTER_PASSWORD = 'password', MASTER_LOG_FILE = 'mysql-bin.000001', MASTER_LOG_POS = 101; 
mysql> SLAVE START; 

Keep in mind that your values may differ from those above. Please also replace the value of MASTER_PASSWORD with the password you created when setting up the replication user.

The output will look something like the following:

Query OK, 0 rows affected (0.01 sec)

The last thing to do is to test that replication is working on both VMs. The last step will explain an easy way to test this configuration.

Step 4 – Testing Master-Master Replication

Now that have all the configuration set up, we are going to test it now. To do this, we are going to create a table in our example database on vdb1 and check on vdb2 to see if it shows up. Then, we are going to delete it from vdb2 and make sure it’s no longer showing up on vdb1.

We now need to create the database that will be replicated between the servers. We can do that by typing the following at the mysql shell:

create database example; 

Once that’s done, let’s create a dummy table on vdb1:

create table example.dummy (id varchar(10)); 

We now are going to check vdb2 to see if our table exists.

show tables in example; 

We should see output similar to the following:

+-------------------+
| Tables_in_example |
+-------------------+
| dummy             |
+-------------------+
1 row in set (0.00 sec)

The last test to do is to delete our dummy table from vdb2. It should also be deleted from vdb1.

We can do this by entering the following on vdb2:

DROP TABLE dummy; 

To confirm this, running the “show tables” command on vdb1 will show no tables:

Empty set (0.00 sec)

And there it is!   A working mysql master-master replication.

You could also check the consistency between the two using the pt-table-checksum tool from Percona.

# pt-table-checksum --host=vdb1 --user=MYSQLROOTUSR --password=MYSQLROOTPW --no-check-binlog-format

Then, if there are any issue, you can sync those databases/tables with the vdb2 in a master-master config with the tool from Percona

# pt-table-sync --execute --sync-to-master h=vdb2 --user=MYSQLROOTUSR --password=MYSQLROOTPW